VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-the-number-formed-by-replacing-adjacent-pair-of-digits-with-their-sum/

⇱ Minimize the number formed by replacing adjacent pair of digits with their sum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimize the number formed by replacing adjacent pair of digits with their sum

Last Updated : 23 Jul, 2025

Given string s denoting a number. The task is to find the minimum number that can be formed after replacing two consecutive digits of s by their sum.

Examples:

Input: s = "1005"
Output: 105
Explanation: Select and replace any two consecutive digits with its sum 

Input: s = "56773"
Output: 11773
Explanation: Select and replace first two consecutive digits (5 and 6) with its sum (11) 

Approach:  This problem can be solved by using the Greedy Approach. Use the following observation:

If there exists at least one pair having sum less than 10:

  • The sum will always be greater than or equal to the elements of the adjacent pair.
  • So replacing the last arrival of such pair will give the minimum number possible. Otherwise, the number will increase.
  • For example, 2381 can be made 581 or 239 and 239 is the minimum between these two.
  • This condition is given priority because it decreases the number of digits in the number and makes the value less than any number having same number of digits as the actual number.

If there is no such pair having sum less than 10:

  • The sum will always be less than the number formed by the adjacent digits.
  • So replacing the first occurrence of such a pair will give the minimum number as it makes the most significant part minimum.
  • For example, 386 can be made 116 or 314. 116 is the lesser one.

Follow the steps below to solve the given problem using the above observation.

  • Firstly assume that there exists at least one pair of consecutive elements whose sum is less than 10.
    • Iterate the numeric string from the back.
    • Find the first pair of consecutive digits whose sum is less than 10.
    • Replace them with their sum and return the string.
  • Now, handle cases in which there is not a single pair of consecutive elements whose sum is less than 10.
    • Iterate the numeric string from the start.
    • The first pair of consecutive digits whose sum is equal to or greater than 10 is the optimal answer.

Below is the implementation of the above approach:

 
 


Output
11773


 

Time Complexity: O(N) where N is the size of the string
Auxiliary Space: O(N)


 

Comment