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.
Example 1:
Input: num = "1234"
Output: false
Explanation:
1 + 3 == 4, and the sum of digits at odd indices is 2 + 4 == 6.num is not balanced.Example 2:
Input: num = "24123"
Output: true
Explanation:
2 + 1 + 3 == 6, and the sum of digits at odd indices is 4 + 2 == 6.num is balanced.
Constraints:
2 <= num.length <= 100num consists of digits onlyThis approach involves iterating over the string and maintaining two sums: one for digits at even indices and another for digits at odd indices. By the end of the iteration, compare the two sums to determine if the string is balanced.
In this solution, we use the strlen function to get the length of the string. We iterate over each character of the string, converting it to an integer by subtracting '0', and update either evenSum or oddSum based on whether the index is even or odd. Finally, we return whether these sums are equal.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the string, as we iterate over the string once.
Space Complexity: O(1), since we only use a fixed amount of extra space for the sums.
Instead of calculating sums in a single pass, we can briefly check each character's index. This involves conditional logic within a loop to segregate digits to their corresponding index-based sums.
Here, the calculation of evenSum and oddSum is divided by checking if the index is even or odd. This function relies on the loop running until the null character, ensuring we don't run out of bounds.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), with n as the length of the string.
Space Complexity: O(1), used space is invariant to input size.
| Approach | Complexity |
|---|---|
| Simple Iterative Sum Calculation | Time Complexity: O(n), where n is the length of the string, as we iterate over the string once. |
| Index Check and Conditional Sum | Time Complexity: O(n), with n as the length of the string. |
Valid Parentheses - Stack - Leetcode 20 - Python • NeetCode • 475,216 views views
Watch 9 more video solutions →Practice Check Balanced String with our built-in code editor and test cases.
Practice on FleetCode