3461. Check If Digits Are Equal in String After Operations I
EasyView on LeetCode
Time: O(n²)
Space: O(n)
Problem Overview
Repeatedly replace each adjacent pair (a,b) with (a+b) mod 10 until two digits remain.
Advertisement
Intuition
Repeatedly replace each adjacent pair (a,b) with (a+b) mod 10 until two digits remain. All strings in the input must end with the same two digits after this process. Simulate the triangular reduction on each string and compare finals.
Algorithm
- 1For each string, copy to char array.
- 2While length > 2: for i = 0..len-2, set s[i] = (s[i]+s[i+1]) % 10 as char (shrink effective length by 1 per outer loop).
- 3After reduction, check s[0] == s[1].
- 4Return true only if every string matches the first string's final pair.
Example Walkthrough
Input: s = "3902", compare with other strings
- 1.Reduce "3902" → adjacent sums mod 10 until 2 chars remain.
- 2.Repeat for each string; all final pairs must be equal.
Output: true if all match
Common Pitfalls
- •Mod 10 after each adjacent sum — not raw sum.
- •Outer loop reduces length by one per pass (triangle/Pascal style).
- •Compare all strings to the same target final two digits.
3461.cs
C#
// Approach: Reduce string by summing adjacent digits mod 10 repeatedly; check final two digits equal.
// Time: O(n²) Space: O(n)
public class Solution
{
public bool HasSameDigits(string s)
{
// Convert the input string to a character array for manipulation
char[] digitArray = s.ToCharArray();
int arrayLength = digitArray.Length;
// Perform triangular reduction
// Start from the last position and work backwards to position 1
// This ensures we end up with exactly 2 elements
for (int currentLength = arrayLength - 1; currentLength > 1; --currentLength)
{
// For each iteration, compute new values for positions 0 to currentLength-1
// Each new value is the sum of adjacent digits modulo 10
for (int position = 0; position < currentLength; ++position)
{
// Calculate sum of current digit and next digit
int currentDigit = digitArray[position] - '0';
int nextDigit = digitArray[position + 1] - '0';
int sumModTen = (currentDigit + nextDigit) % 10;
// Store the result back as a character
digitArray[position] = (char)(sumModTen + '0');
}
}
// Check if the final two remaining digits are equal
return digitArray[0] == digitArray[1];
}
}Advertisement
Was this solution helpful?
Related Problems
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 14. Longest Common Prefix(Easy)
- 22. Generate Parentheses(Medium)
- 29. Divide Two Integers(Medium)
- 30. Substring with Concatenation of All Words(Hard)