Skip to content

3340. Check Balanced String 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  bool isBalanced(string num) {
    int balance = 0;
    int sign = 1;

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

    return balance == 0;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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;
  }
}
1
2
3
4
class Solution:
  def isBalanced(self, num: str) -> bool:
    nums = list(map(int, num))
    return sum(nums[::2]) == sum(nums[1::2])