Check Balanced String

Easy
#2966Time: O(N), where N is the length of the string `num`. We traverse the string twice, once for even indices (~N/2 steps) and once for odd indices (~N/2 steps). The total number of operations is proportional to N.Space: O(1). We only use a few extra variables (`evenSum`, `oddSum`, and loop counters) regardless of the input string size.
Data structures

Prompt

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 is 2 + 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 is 4 + 2 == 6.
  • Since both are equal the num is balanced.

 

Constraints:

  • 2 <= num.length <= 100
  • num consists of digits only

Approaches

3 approaches with complexity analysis and trade-offs.

This approach involves iterating through the string twice. The first loop calculates the sum of digits at even indices, and the second loop calculates the sum of digits at odd indices. Finally, it compares the two sums to determine if the string is balanced.

Algorithm

  • Initialize two integer variables, evenSum and oddSum, to 0.
  • Create a for loop that iterates from index i = 0 to the end of the string, incrementing i by 2 in each step. Inside this loop, convert the character at the current even index to an integer and add it to evenSum.
  • Create a second for loop that iterates from index i = 1 to the end of the string, incrementing i by 2 in each step. Inside this loop, convert the character at the current odd index to an integer and add it to oddSum.
  • After both loops complete, compare evenSum and oddSum. If they are equal, return true; otherwise, return false.

Walkthrough

The core idea is to handle the even and odd indices in separate passes for clarity. We initialize two variables, evenSum and oddSum, to zero. The first loop iterates from index 0 with a step of 2. In each step, it reads the character, converts it to its integer equivalent (by subtracting the ASCII value of '0'), and adds it to evenSum. The second loop iterates from index 1 with a step of 2. Similarly, it processes the digits at odd indices and accumulates their sum in oddSum. After both loops complete, we check if evenSum is equal to oddSum. If they are equal, the string is balanced, and the function returns true; otherwise, it returns false.

class Solution {    public boolean isBalanced(String num) {        int evenSum = 0;        for (int i = 0; i < num.length(); i += 2) {            evenSum += num.charAt(i) - '0';        }         int oddSum = 0;        for (int i = 1; i < num.length(); i += 2) {            oddSum += num.charAt(i) - '0';        }         return evenSum == oddSum;    }}

Complexity

Time

O(N), where N is the length of the string `num`. We traverse the string twice, once for even indices (~N/2 steps) and once for odd indices (~N/2 steps). The total number of operations is proportional to N.

Space

O(1). We only use a few extra variables (`evenSum`, `oddSum`, and loop counters) regardless of the input string size.

Trade-offs

Pros

  • The logic is very straightforward and easy to understand.

  • It clearly separates the calculation for even and odd indices, which can make the code easier to read for beginners.

Cons

  • It iterates through the string's data twice, which is less efficient than a single-pass solution due to increased loop overhead and potentially worse cache performance.

Solutions

class Solution {public  boolean isBalanced(String num) {    int[] f = new int[2];    for (int i = 0; i < num.length(); ++i) {      f[i & 1] += num.charAt(i) - '0';    }    return f[0] == f[1];  }}

Video walkthrough

Newsletter

One sharp idea, every week

System design and interview prep — short enough to finish.

No spam. Unsubscribe anytime.

Practice

Same difficulty — related problems to reinforce the pattern.