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

You are given a string s consisting of digits. Perform the following operation repeatedly until the string has exactly two digits:

For each pair of consecutive digits in s, starting from the first digit, calculate a new digit as the sum of the two digits modulo 10. Replace s with the sequence of newly calculated digits, maintaining the order in which they are computed.

Return true if the final two digits in s are the same; otherwise, return false.

Input & Output

Example 1 — Basic Reduction
$ Input: s = "1234"
Output: false
💡 Note: Step 1: "1234" → "357" (1+2=3, 2+3=5, 3+4=7). Step 2: "357" → "82" (3+5=8, 5+7=12→2). Final: 8 ≠ 2, so return false.
Example 2 — Equal Final Digits
$ Input: s = "808"
Output: true
💡 Note: Step 1: "808" → "88" (8+0=8, 0+8=8). Final: 8 = 8, so return true.
Example 3 — Already Two Digits
$ Input: s = "11"
Output: true
💡 Note: String already has 2 digits: 1 = 1, so return true.

Constraints

  • 2 ≤ s.length ≤ 1000
  • s consists of digits only

Visualization

Tap to expand
Check If Digits Are Equal After Operations INPUT String s = "1234" 1 2 3 4 i=0 i=1 i=2 i=3 4 digits initially Goal: Reduce to 2 digits Check if they are equal Operation Formula: new[i] = (s[i] + s[i+1]) % 10 ALGORITHM STEPS 1 Round 1: "1234" (1+2)%10=3, (2+3)%10=5, (3+4)%10=7 3 5 7 --> "357" 2 Round 2: "357" (3+5)%10=8, (5+7)%10=2 8 2 --> "82" 3 Final: "82" Length = 2, STOP 4 Compare Digits s[0]='8' vs s[1]='2' 8 != 2, return false Time: O(n^2) | Space: O(n) FINAL RESULT Transformation Path: "1234" (4 digits) "357" (3 digits) "82" (2 digits) Comparison: 8 != 2 Output: false Key Insight: Each round reduces string length by 1. For n digits, we need (n-2) rounds to get 2 digits. The optimal approach uses binomial coefficients: final digits follow Pascal's triangle pattern (mod 10). Result[i] = Sum of (C(n-2,j) * s[i+j]) mod 10 for j from 0 to n-2, avoiding repeated iteration. TutorialsPoint - Check If Digits Are Equal in String After Operations II | Optimal Solution
Asked in
Google 25 Microsoft 18
9.0K Views
Medium Frequency
~25 min Avg. Time
234 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