Program to Find Out the Number of Corrections to be Done to Fix an Equation in Python

Given a string representing an equation in the form x+y=z, we need to find the minimum number of digits to insert to make the equation mathematically correct. This problem uses dynamic programming to explore all possible digit insertions.

For example, with the equation "2+6=7", we can insert digits to make it "21+6=27", requiring 2 insertions.

Approach

The solution uses dynamic programming with the following strategy ?

  • Split the equation into three parts: left operand (A), right operand (B), and result (C)

  • Process digits from right to left (like manual addition)

  • At each position, try different operations: use existing digits, insert new digits, or modify the result

  • Track carry values as we move from right to left

Implementation

class Solution:
    def solve(self, s):
        # Split equation into components
        A, rest = s.split("+")
        B, C = rest.split("=")
        
        def dp(i, j, k, carry):
            # Base case: all positions processed
            if i <= -1 and j <= -1 and k <= -1:
                return 0 if carry == 0 else 1
            
            # Get current digits (0 if position is out of bounds)
            last1 = int(A[i]) if i >= 0 else 0
            last2 = int(B[j]) if j >= 0 else 0
            last3 = int(C[k]) if k >= 0 else 0
            
            # Get prefix values for current positions
            prefix1 = int(A[:i + 1]) if i >= 0 else 0
            prefix2 = int(B[:j + 1]) if j >= 0 else 0
            prefix3 = int(C[:k + 1]) if k >= 0 else 0
            
            # Case: both operands exhausted, only result remains
            if i <= -1 and j <= -1:
                rhs = prefix3 - carry
                if rhs <= 0:
                    return abs(rhs)
                if i == -1 or j == -1:
                    return len(str(rhs))
                else:
                    assert False
            
            # Case: result exhausted, need to handle remaining sum
            if k <= -1:
                return len(str(prefix1 + prefix2 + carry))
            
            ans = float("inf")
            
            # Try using existing digits without insertion
            carry2, lhs = divmod(carry + last1 + last2, 10)
            if lhs == last3:
                ans = dp(i - 1, j - 1, k - 1, carry2)
            
            # Try inserting digit in first operand
            req = last3 - carry - last2
            extra_zeros = max(0, -1 - i)
            carry2 = 1 if req < 0 else 0
            ans = min(ans, 1 + extra_zeros + dp(max(-1, i), j - 1, k - 1, carry2))
            
            # Try inserting digit in second operand
            req = last3 - carry - last1
            extra_zeros = max(0, -1 - j)
            carry2 = 1 if req < 0 else 0
            ans = min(ans, 1 + extra_zeros + dp(i - 1, max(-1, j), k - 1, carry2))
            
            # Try inserting digit in result
            carry2, lhs = divmod(last1 + last2 + carry, 10)
            ans = min(ans, 1 + dp(i - 1, j - 1, k, carry2))
            
            return ans
        
        return dp(len(A) - 1, len(B) - 1, len(C) - 1, 0)

# Test the solution
ob = Solution()
print(ob.solve('2+6=7'))

Example Walkthrough

For the input "2+6=7" ?

ob = Solution()
result = ob.solve('2+6=7')
print(f"Minimum insertions needed: {result}")

# The algorithm finds that inserting "1" and "2" gives us "21+6=27"
# which is a valid equation, requiring 2 insertions
Minimum insertions needed: 2

How It Works

The algorithm processes the equation from right to left, simulating manual addition. At each step, it considers four possibilities ?

  1. No insertion ? Use existing digits if they form a valid addition step

  2. Insert in first operand ? Add a digit to make the addition work

  3. Insert in second operand ? Add a digit to make the addition work

  4. Insert in result ? Add a digit to accommodate the sum

The dynamic programming approach ensures we find the minimum number of insertions across all possible combinations.

Conclusion

This solution uses dynamic programming to find the minimum digit insertions needed to fix an equation. The algorithm considers all possible insertion points and chooses the optimal strategy for each position.

Updated on: 2026-03-25T13:57:11+05:30

296 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements