Check Balanced String - Problem

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.

Note: String indices are 0-based, so index 0 is considered even, index 1 is odd, index 2 is even, and so on.

Input & Output

Example 1 — 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, return true
Example 2 — Unbalanced String
$ Input: num = "123"
Output: false
💡 Note: Even indices (0,2): 1 + 3 = 4. Odd indices (1): 2. Since 4 ≠ 2, return false
Example 3 — Single Character
$ Input: num = "5"
Output: false
💡 Note: Even indices (0): 5. Odd indices: none (sum = 0). Since 5 ≠ 0, return false

Constraints

  • 1 ≤ num.length ≤ 100
  • num consists of digits only

Visualization

Tap to expand
Check Balanced String INPUT String: num = "1221" 0 1 2 3 1 2 2 1 EVEN ODD EVEN ODD Even index (0, 2) Odd index (1, 3) Input: num = "1221" Length: 4 characters ALGORITHM STEPS 1 Initialize Sums evenSum = 0, oddSum = 0 2 Iterate String Loop through each char 3 Add to Sum Even idx --> evenSum Odd idx --> oddSum 4 Compare Return evenSum == oddSum Calculations: evenSum = 1 + 2 = 3 oddSum = 2 + 1 = 3 3 == 3 --> true FINAL RESULT Even Sum 3 = Odd Sum 3 BALANCED true Output true String "1221" is balanced because 3 equals 3 [OK] Key Insight: Single-pass O(n) solution: Iterate once, tracking two running sums based on index parity. Use modulo operator (i % 2) to determine if index is even or odd. Compare sums at end. TutorialsPoint - Check Balanced String | Single-Pass Sum Calculation
Asked in
Google 12 Amazon 8 Microsoft 6
12.5K Views
Medium Frequency
~8 min Avg. Time
245 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