#1881

Maximum Value after Insertion

Medium
StringGreedyGreedyString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

In the optimal approach, we can directly determine where to insert 'x' by iterating through the string once. We check if inserting 'x' before a digit will yield a larger number, and we stop as soon as we find the correct position.

⚙️

Algorithm

4 steps
  1. 1Step 1: Check if the number is negative. If so, handle it differently by looking for the first digit greater than 'x'.
  2. 2Step 2: Loop through the digits of 'n'.
  3. 3Step 3: If 'x' is greater than the current digit, insert 'x' before it and break the loop.
  4. 4Step 4: If no insertion has been made, append 'x' at the end.
solution.py13 lines
1def insert_max(n, x):
2    if n[0] == '-':
3        for i in range(1, len(n)):
4            if x < n[i]:
5                return n[:i] + str(x) + n[i:]
6        return n + str(x)
7    else:
8        for i in range(len(n)):
9            if x > n[i]:
10                return n[:i] + str(x) + n[i:]
11        return n + str(x)
12
13print(insert_max("99", 9))

Complexity note: This complexity is linear because we only make a single pass through the string to find the correct insertion point, and the space complexity is O(n) due to the new string created during insertion.

  • 1Inserting 'x' before a smaller digit maximizes the value for positive numbers.
  • 2For negative numbers, inserting 'x' before a larger digit minimizes the value, which is optimal.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.