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

1
2
3
4
5
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 is `2 + 4 == 6`.
  * Since 4 is not equal to 6, `num` is not balanced.

Example 2

1
2
3
4
5
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 is `4 + 2 == 6`.
  * Since both are equal the `num` is balanced.

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:

  1. Initialize two variables for even and odd index sums.
  2. 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.
  3. Return true if the two sums are equal, false otherwise.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
    public boolean isBalanced(String num) {
        int even = 0, odd = 0;
        for (int i = 0; i < num.length(); i++) {
            int d = num.charAt(i) - '0';
            if (i % 2 == 0) even += d;
            else odd += d;
        }
        return even == odd;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
    def isBalanced(self, num: str) -> bool:
        even = 0
        odd = 0
        for i, ch in enumerate(num):
            d = int(ch)
            if i % 2 == 0:
                even += d
            else:
                odd += d
        return even == odd

Complexity

  • ⏰ Time complexity: O(n), where n is the length of the string.
  • 🧺 Space complexity: O(1)