3340. Check Balanced String
Description
You are given a string num consisting of only digits. A string of digits is called balanced if the sum of the digits at even indices is equal to the sum of digits at odd indices.
Return true if num is balanced, otherwise return false.
Example 1:
Input: num = "1234"
Output: false
Explanation:
- The sum of digits at even indices is
1 + 3 == 4, and the sum of digits at odd indices is2 + 4 == 6. - Since 4 is not equal to 6,
numis not balanced.
Example 2:
Input: num = "24123"
Output: true
Explanation:
- The sum of digits at even indices is
2 + 1 + 3 == 6, and the sum of digits at odd indices is4 + 2 == 6. - Since both are equal the
numis balanced.
Constraints:
2 <= num.length <= 100numconsists of digits only
Solutions
Solution 1: Simulation
Thinking
A balanced string has equal digit sums on even and odd indices. With \(n \le 100\), one scan is enough.
A two-cell array accumulates by \(i \bmod 2\); the string is balanced iff the cells are equal.
We never materialize the two subsequences; parity of the index is sufficient.
We can use an array \(f\) of length \(2\) to record the sum of numbers at even indices and odd indices. Then, we traverse the string \(\textit{nums}\) and add the numbers to the corresponding positions based on the parity of the indices. Finally, we check whether \(f[0]\) is equal to \(f[1]\).
The time complexity is \(O(n)\), where \(n\) is the length of the string \(\textit{nums}\). The space complexity is \(O(1)\).
1 2 3 4 5 6 | |
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 | |