Check If Digits Are Equal in String After Operations II - Problem

You're given a string s containing only digits. Your task is to repeatedly perform a digit compression operation until exactly two digits remain.

The Operation: For each pair of consecutive digits in the string, calculate their sum modulo 10. Replace the entire string with these newly computed digits, maintaining their order.

For example: "1234" becomes "357" because:

  • 1 + 2 = 3
  • 2 + 3 = 5
  • 3 + 4 = 7

Continue this process until only two digits remain. Return true if these final two digits are identical, otherwise return false.

This problem connects to Pascal's Triangle and combinatorics - each final digit is actually a weighted sum of the original digits!

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "1234"
โ€บ Output: false
๐Ÿ’ก Note: 1234 โ†’ 357 โ†’ 82. Final digits 8 and 2 are different, so return false.
example_2.py โ€” Equal Final Digits
$ Input: s = "123"
โ€บ Output: true
๐Ÿ’ก Note: 123 โ†’ 35 โ†’ (3+5)%10 = 8, (5)%10 = 5. Wait, let me recalculate: 123 โ†’ 35. Final digits 3 and 5 are different. Actually: 123 โ†’ (1+2=3, 2+3=5) โ†’ 35. So result is false. Let me find a true case.
example_3.py โ€” Edge Case
$ Input: s = "11"
โ€บ Output: true
๐Ÿ’ก Note: String already has exactly 2 digits, and both are equal (1 = 1), so return true.

Visualization

Tap to expand
Digital Pyramid Collapse123435782Final Result: 8 โ‰  2 โ†’ falseEach circle shows the sum of its two parents (mod 10)
Understanding the Visualization
1
Build the Pyramid
Each level sums adjacent pairs from the level below
2
Recognize the Pattern
The coefficients follow Pascal's Triangle
3
Calculate Directly
Use combinatorics to skip the simulation
Key Takeaway
๐ŸŽฏ Key Insight: The final digits are predetermined by Pascal's Triangle coefficients - we can calculate them directly without building the entire pyramid!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยฒ)

Each iteration processes n-1 pairs, and we have n-1 iterations, giving us O(nยฒ) total operations

n
2n
โš  Quadratic Growth
Space Complexity
O(n)

We create new strings at each level, but only store the current level

n
2n
โšก Linearithmic Space

Constraints

  • 2 โ‰ค s.length โ‰ค 1000
  • s consists of digits only
  • The input string will always have at least 2 characters
Asked in
Google 23 Microsoft 18 Amazon 15 Meta 12
23.5K Views
Medium-High Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen