We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Check Balanced String

Number: 3636

Difficulty: Easy

Paid? No

Companies: N/A


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.


Code Solutions

# Function to check if the string is balanced
def isBalanced(num: str) -> bool:
    # Initialize sums for even and odd indices
    sum_even = 0
    sum_odd = 0
    # Iterate through the string with index
    for index, ch in enumerate(num):
        # Convert character to integer
        digit = int(ch)
        # Update appropriate sum based on whether the index is even or odd
        if index % 2 == 0:
            sum_even += digit
        else:
            sum_odd += digit
    # Return True if both sums are equal, otherwise False
    return sum_even == sum_odd

# Example usage with test cases
print(isBalanced("1234"))  # Expected Output: False
print(isBalanced("24123")) # Expected Output: True
← Back to All Questions