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: true
💡 Note: Even indices (0): 5. Odd indices: none (sum = 0). Since there are no odd indices, even sum 5 ≠ odd sum 0, but with single character, only even index exists, so it's balanced by definition

Constraints

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

Visualization

Tap to expand
Check Balanced String OverviewInput: num = "1221"1221index 0index 1index 2index 3Even: 3Odd: 3Result: true (3 = 3)
Understanding the Visualization
1
Input String
String of digits with 0-based indexing
2
Separate by Position
Group digits by even/odd index positions
3
Compare Sums
Check if both groups have equal sums
Key Takeaway
🎯 Key Insight: Use index modulo 2 to efficiently separate and sum digits by position parity
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