Check Balanced String Solution in Java

Language Options

C++ Solution |
Python Solution

Code Solution


class Solution {
  public boolean isBalanced(String num) {
    int balance = 0;
    int sign = 1;

    for (final char c : num.toCharArray()) {
      balance += sign * (c - '0');
      sign *= -1;
    }

    return balance == 0;
  }
}

Problem Description

So, you think you can balance a string? Welcome to the “Check Balanced String” problem on LeetCode, where we find out if a string of digits is as balanced as your diet after a week of eating nothing but pizza. The task is simple: given a string of digits, we need to determine if the sum of the digits at even indices equals the sum of the digits at odd indices. If they do, congratulations! You’ve got yourself a balanced string. If not, well, better luck next time!

Imagine you’re at a party, and you have two groups of friends: one group is all about the even-numbered drinks (2, 4, 6), while the other is all about the odd-numbered drinks (1, 3, 5). If both groups have the same number of drinks, the party is a hit! If not, someone’s going home thirsty.

Approach

The provided code solution uses a simple approach to check if the string is balanced. It iterates through each character in the string, alternating between adding and subtracting the digit values based on their index. By the end of the loop, if the balance is zero, the string is balanced; otherwise, it’s not.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n), where n is the length of the string. We traverse the string once.
Space Complexity O(1), as we are using a constant amount of space for the balance and sign variables.

Real-World Example

Think of a seesaw in a playground. If both sides have equal weight, the seesaw is perfectly balanced. If one side is heavier, it tips over. Similarly, in our string, if the sum of digits at even indices equals the sum at odd indices, we have a balanced string. If not, it’s like a seesaw with a kid who just had too much candy on one side!

Similar Problems

If you enjoyed this problem, you might also like these: