MediumNo. 1881

Maximum Value after Insertion — LeetCode 1881 Python Solution

Pattern
Greedy
Topics
Greedy, String
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

PythonSolution
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

Time
O(m)where m is the length of n
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0179Largest NumberMedium
0316Remove Duplicate LettersMedium
0402Remove K DigitsMedium
0420Strong Password CheckerHard
0649Dota2 SenateMedium
0680Valid Palindrome IIEasy

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.

Free to download. Check it runs on your machine, then pick a plan.