Check Balanced String — Solution in Python, Java & C++
Check Balanced String solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem, asked at Amazon.
Check Balanced String is an easy coding problem on strings, asked in Amazon interviews.
- Difficulty: Easy
- Topics: Strings
- Asked at: Amazon
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
You are given a string num made only of digits.
num is balanced if the sum of the digits at even indices equals the sum of the digits at odd indices (indices start at 0).
Return true if num is balanced, otherwise false.
Example 1
Input: num = "1234"
Output: false
Explanation: Even indices give 1 + 3 = 4, odd indices give 2 + 4 = 6.
Example 2
Input: num = "24123"
Output: true
Explanation: Even indices give 2 + 1 + 3 = 6, odd indices give 4 + 2 = 6.
Example 3
Input: num = "00"
Output: true
Constraints
2 <= num.length <= 100num consists of digits only
Hints for Check Balanced String
Hint 1
You only need the difference between the two sums.
Hint 2
Add digits at even indices and subtract digits at odd indices in one pass; the string is balanced when the result is 0.
How to solve Check Balanced String
Keep one running value: add each even-index digit and subtract each odd-index digit. The two sums are equal exactly when this difference ends at zero.
Approach
- Set
diff = 0. - For each index
i: addnum[i] - '0'ifiis even, subtract it ifiis odd. - Return
diff == 0.
Why it works
diff equals (sum at even indices) − (sum at odd indices) after the loop, which is zero iff the sums match.
Complexity
- Time —
O(n) - Space —
O(1)
Pitfalls
- Use the digit's value (
c - '0'), not its character code.
Reference solution
Python
def isBalanced(num: str) -> bool:
diff = 0
for i, c in enumerate(num):
d = ord(c) - 48
diff += d if i % 2 == 0 else -d
return diff == 0Java
public static boolean isBalanced(String num) {
int diff = 0;
for (int i = 0; i < num.length(); i++) {
int d = num.charAt(i) - '0';
diff += i % 2 == 0 ? d : -d;
}
return diff == 0;
}C++
bool isBalanced(string num) {
int diff = 0;
for (int i = 0; i < (int) num.size(); i++) {
int d = num[i] - '0';
diff += i % 2 == 0 ? d : -d;
}
return diff == 0;
}JavaScript
var isBalanced = function(num) {
var diff = 0;
for (var i = 0; i < num.length; i++) {
var d = num.charCodeAt(i) - 48;
diff += i % 2 === 0 ? d : -d;
}
return diff === 0;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings