#3461
Check If Digits Are Equal in String After Operations I
EasyMathStringSimulationCombinatoricsNumber TheorySimulationMathematical Operations
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of simulating the entire process, we can observe that the final digits depend only on the parity of the sums of the original digits.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the sum of the digits in the string.
- 2Step 2: Check if the last two digits of this sum (modulo 10) are equal.
- 3Step 3: Return true if they are equal, otherwise return false.
solution.py3 lines
1def checkEqualDigits(s):
2 total = sum(int(d) for d in s)
3 return (total % 10) == ((total // 10) % 10)ℹ
Complexity note: We only traverse the string once to sum the digits, leading to O(n) complexity.
- 1The final digits depend on the sum of the original digits.
- 2Modulo 10 operations simplify the problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.