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
Balance Scale: "1234"Even Indices13Sum: 4Odd Indices24Sum: 6Scale Tips Right: Not Balanced!4 โ‰  6 โ†’ false
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

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using two integer variables for the sums

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค num.length โ‰ค 100
  • num consists of digits only
  • Each character is a digit from '0' to '9'
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 5
23.4K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen