Problem Description
Given a string num consisting only of digits, determine if the string is balanced. A string is described as balanced if the sum of digits at even indices equals the sum of digits at odd indices.
Key Insights
- The problem only requires processing each digit once.
- Use two accumulators to keep track of the sum at even indices and the sum at odd indices.
- Convert each character to its corresponding integer value.
- Finally, compare the two sums to decide if the string is balanced.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string because we iterate over the string once. Space Complexity: O(1), as only constant extra space is used for the accumulators.
Solution
The solution involves iterating over the string and maintaining two sums: one for digits at even indices and another for digits at odd indices. By checking the modulo condition (index % 2), we decide which accumulator to update. At the end of the iteration, if both sums are equal, the string is balanced. The approach is clear and efficient as it only traverses the string a single time.