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,
num
is 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
num
is balanced.
Constraints:
2 <= num.length <= 100
num
consists of digits only
Solutions
Solution 1: Simulation
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 |
|