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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code