Magicsheet logo

Largest Number After Mutating Substring

Medium
86.1%
Updated 6/1/2025

Asked by 1 Company

Largest Number After Mutating Substring

1. What is this problem about?

The Largest Number After Mutating Substring coding problem asks you to transform a given numerical string into the largest possible number by "mutating" a single contiguous substring. You are provided with a mapping array called change, where each index i represents a digit from 0-9 and change[i] is the digit it can be mutated into. You must decide which substring to mutate to maximize the resulting number's value.

2. Why is this asked in interviews?

This problem is a common feature in Infosys and other technical interviews because it tests a candidate's grasp of greedy algorithms and string manipulation. It requires you to understand that significant digits (those on the left) have a much greater impact on the number's total value than those on the right. Effectively identifying the optimal starting and ending points for the mutation is a key test of your logical precision.

3. Algorithmic pattern used

This problem follows the Greedy interview pattern. The strategy is to scan the string from left to right. As soon as you find a digit that can be mutated into something larger (change[digit] > digit), you start your mutation there. You continue mutating as long as the replacement digit is at least equal to the original digit (change[digit] >= digit). Once you encounter a digit that would be made smaller by mutation, you stop and return the result.

4. Example explanation

Original string: "132", Change map: {1:9, 2:2, 3:3} (others unchanged). Step 1: Check '1'. change[1] is 9. 9 > 1, so we start mutating. Current: "932". Step 2: Check '3'. change[3] is 3. 3 == 3. Since we've already started a mutation, we can include this in our substring. Current: "932". Step 3: Check '2'. change[2] is 2. 2 == 2. We can include this too. Current: "932". Final largest number: "932".

5. Common mistakes candidates make

A major mistake is not stopping the mutation as soon as a "worse" change is encountered, which would decrease the number's value. Another error is failing to start the mutation at the first possible opportunity for improvement. Some candidates also forget that once they stop a mutation, they cannot start another one elsewhere in the string, as only a single substring can be mutated.

6. Interview preparation tip

When working on "Array, String, Greedy interview pattern" problems, focus on the "most significant" parts of your data structure first. In numbers, this always means starting from the left. Practicing how to handle contiguous blocks or substrings efficiently will help you solve many similar greedy challenges.

Similar Questions