- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 35 lines of Python from the credited upstream file 640.py.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def solveEquation(self, equation: str) -> str:3 def calculate(s: str) -> tuple:4 coefficient = 05 constant = 06 num = 07 sign = 18 9 for i, c in enumerate(s):10 if c.isdigit():11 num = num * 10 + int(c)12 elif c in '+-':13 constant += sign * num14 sign = 1 if c == '+' else -115 num = 016 else:17 if i > 0 and num == 0 and s[i - 1] == '0':18 continue19 coefficient += sign if num == 0 else sign * num20 num = 021 22 return coefficient, constant + sign * num23 24 lhsEquation, rhsEquation = equation.split('=')25 lhsCoefficient, lhsConstant = calculate(lhsEquation)26 rhsCoefficient, rhsConstant = calculate(rhsEquation)27 coefficient = lhsCoefficient - rhsCoefficient28 constant = rhsConstant - lhsConstant29 30 if coefficient == 0 and constant == 0:31 return "Infinite solutions"32 if coefficient == 0 and constant != 0:33 return "No solution"34 return "x=" + str(constant coefficient)35