Check If Digits Are Equal in String After Operations I - 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 Case
$ Input: s = "1234"
Output: false
💡 Note: Round 1: "1234" → "357" (1+2=3, 2+3=5, 3+4=7). Round 2: "357" → "82" (3+5=8, 5+7=12→2). Final digits 8 and 2 are different, so return false.
Example 2 — Equal Result
$ Input: s = "999"
Output: true
💡 Note: Round 1: "999" → "88" (9+9=18→8, 9+9=18→8). Final digits are both 8, so return true.
Example 3 — Two Digits
$ Input: s = "12"
Output: false
💡 Note: String already has two digits. 1 ≠ 2, so return false.

Constraints

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

Visualization

Tap to expand
Digit Equality Check - String Operations INPUT String s = "1234" 1 i=0 2 i=1 3 i=2 4 i=3 Operation: For consecutive pairs: (s[i] + s[i+1]) % 10 Example pairs: (1+2)%10 = 3 (2+3)%10 = 5 (3+4)%10 = 7 Length: 4 digits ALGORITHM STEPS 1 Round 1: "1234" 3+5+7 = "357" 3 5 7 2 Round 2: "357" (3+5)%10=8, (5+7)%10=2 8 2 3 Final: "82" Length = 2 (stop) 4 Compare Digits Check: s[0] == s[1]? 8 != 2 Not Equal! FINAL RESULT Final String: "82" 8 2 8 != 2 Output: false Digits are NOT equal after all operations. Return: false Key Insight: Optimized String Building: Instead of creating new strings each iteration, we process pairs in-place. Each round reduces string length by 1 until we have 2 digits. Time Complexity: O(n^2) where n is string length. Space: O(n) for intermediate strings. TutorialsPoint - Check If Digits Are Equal in String After Operations I | Optimized String Building
Asked in
Google 15 Microsoft 8
12.5K Views
Medium Frequency
~15 min Avg. Time
235 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