Maximum Value after Insertion — LeetCode 1881 Python Solution

MediumGreedyString
Problem
#1881
Pattern
Greedy
Reading time
2 min

The 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.

Example

Input
n = "99", x = 9
Output
"999"
Explanation
The result is the same regardless of where you insert 9.

Python solution

Python
class Solution:
    def maxValue(self, n: str, x: int) -> str:
        i = 0
        if n[0] == "-":
            i += 1
            while i < len(n) and int(n[i]) <= x:
                i += 1
        else:
            while i < len(n) and int(n[i]) >= x:
                i += 1
        return n[:i] + str(x) + n[i:]

Complexity

MeasureComplexity
TimeO(m), where m is the length of n
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1881. Maximum Value after Insertion is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1881. Maximum Value after Insertion?
LeetCode 1881. Maximum Value after Insertion is rated Medium on LeetCode.
What is the time complexity of LeetCode 1881. Maximum Value after Insertion?
The Python solution on this page runs in O(m), where m is the length of n.
What is the space complexity of LeetCode 1881. Maximum Value after Insertion?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1881. Maximum Value after Insertion cover?
LeetCode 1881. Maximum Value after Insertion is tagged Greedy and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview