Check Balanced String - Problem
Imagine you have a digital scale with two plates - one for even positions and one for odd positions. Your task is to determine if a string of digits is perfectly balanced!
Given a string num consisting of only digits, a string is called balanced if:
- The sum of digits at even indices (0, 2, 4, ...) equals
- The sum of digits at odd indices (1, 3, 5, ...)
Return true if the string is balanced, false otherwise.
Example: For "1234" โ Even indices: 1+3=4, Odd indices: 2+4=6 โ Not balanced!
Input & Output
example_1.py โ Basic Balanced String
$
Input:
num = "1221"
โบ
Output:
true
๐ก Note:
Even indices (0,2): 1+2=3, Odd indices (1,3): 2+1=3. Since 3==3, the string is balanced.
example_2.py โ Unbalanced String
$
Input:
num = "123"
โบ
Output:
false
๐ก Note:
Even indices (0,2): 1+3=4, Odd indices (1): 2. Since 4โ 2, the string is not balanced.
example_3.py โ Single Digit
$
Input:
num = "5"
โบ
Output:
true
๐ก Note:
Only one digit at even index 0. Odd sum is 0. Even sum is 5, odd sum is 0. Wait - this should be false! Even=5, Odd=0.
Visualization
Tap to expand
Understanding the Visualization
1
Setup Scale
Prepare two plates - left for even indices, right for odd indices
2
Place Weights
Go through each digit and place it on the appropriate plate
3
Check Balance
See if both plates have equal total weight
Key Takeaway
๐ฏ Key Insight: We can solve this in one pass by maintaining two running sums, eliminating the need for multiple traversals or extra data structures.
Time & Space Complexity
Time Complexity
O(n)
Single pass through string of length n
โ Linear Growth
Space Complexity
O(1)
Only using two integer variables for the sums
โ Linear Space
Constraints
- 1 โค num.length โค 100
-
numconsists of digits only - Each character is a digit from '0' to '9'
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code