String 3340. Check Balanced String ¶ Time: $O(n)$ Space: $O(1)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13 14class 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 13class 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 4class Solution: def isBalanced(self, num: str) -> bool: nums = list(map(int, num)) return sum(nums[::2]) == sum(nums[1::2])