Check Balanced String Problem
#3340
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3340.
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 <= 100numconsists of digits only
Solution
Approach: Simulation
Keep two sums, one for the digits at even indices and one for the digits at odd indices. Scan the string once, add each digit to the sum of its index parity, and compare the two sums at the end.
Complexity: O(n) time and O(1) extra space.
class Solution:
def isBalanced(self, num: str) -> bool:
f = [0, 0]
for i, x in enumerate(map(int, num)):
f[i & 1] += x
return f[0] == f[1]