Maximum Value after Insertion - Problem

You are given a very large integer n, represented as a string, and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number.

You want to maximize n's numerical value by inserting x anywhere in the decimal representation of n. You cannot insert x to the left of the negative sign.

Examples:

  • If n = "73" and x = 6, it would be best to insert it between 7 and 3, making n = "763".
  • If n = "-55" and x = 2, it would be best to insert it before the first 5, making n = "-255".

Return a string representing the maximum value of n after the insertion.

Input & Output

Example 1 — Positive Number
$ Input: n = "73", x = 6
Output: "763"
💡 Note: Insert 6 before digit 3 (first digit < 6): 7 → 76 → 763. This gives maximum value 763.
Example 2 — Negative Number
$ Input: n = "-55", x = 2
Output: "-255"
💡 Note: For negative numbers, insert before first digit > x: -5 → -25 → -255. This gives maximum value -255.
Example 3 — Append at End
$ Input: n = "999", x = 5
Output: "9995"
💡 Note: All digits (9) are ≥ 5, so append 5 at the end: 999 → 9995.

Constraints

  • 1 ≤ n.length ≤ 105
  • n consists of only digits, does not have leading zeros, and may have a leading negative sign
  • 1 ≤ x ≤ 9

Visualization

Tap to expand
Maximum Value after InsertionInputn = "73", x = 6StrategyInsert before digit < 6Output"763"73Original: "73"3 < 6, insert here!763Result: "763"💡 Key Insight: For positive numbers, insert before first smaller digit
Understanding the Visualization
1
Input
String n and digit x to insert
2
Strategy
Find optimal position based on positive/negative
3
Output
Maximum possible value as string
Key Takeaway
🎯 Key Insight: The optimal position depends on the sign - maximize positive numbers by placing larger digits first, minimize absolute value of negative numbers
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.5K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen