#3340
Check Balanced String
EasyStringArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution is similar to the brute force but focuses on a single pass through the string, calculating the sums directly without needing to store intermediate results in separate variables.
⚙️
Algorithm
3 steps- 1Step 1: Initialize two variables, even_sum and odd_sum, to 0.
- 2Step 2: Loop through the string. For each index, add the digit to even_sum if the index is even, or to odd_sum if the index is odd.
- 3Step 3: After the loop, return true if even_sum equals odd_sum, otherwise return false.
solution.py11 lines
1# Full working Python code
2
3def check_balanced_string(num):
4 even_sum = 0
5 odd_sum = 0
6 for i in range(len(num)):
7 if i % 2 == 0:
8 even_sum += int(num[i])
9 else:
10 odd_sum += int(num[i])
11 return even_sum == odd_sumℹ
Complexity note: The time complexity remains O(n) as we still traverse the string once. The space complexity is O(1) since we only use a fixed amount of extra space for the sums.
- 1The sums of digits at even and odd indices must be equal for the string to be balanced.
- 2The problem can be solved in a single pass through the string.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.