Problem
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
.
Examples
Example 1
|
|
Example 2
|
|
Constraints
2 <= num.length <= 100
num
consists of digits only
Solution
Method 1 – Index Parity Sum Comparison
Intuition: A string is balanced if the sum of digits at even indices equals the sum at odd indices. We can iterate through the string, summing digits at even and odd indices separately, and compare the results.
Approach:
- Initialize two variables for even and odd index sums.
- Iterate through the string:
- If the index is even, add the digit to the even sum.
- If the index is odd, add the digit to the odd sum.
- Return true if the two sums are equal, false otherwise.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the string. - 🧺 Space complexity:
O(1)