Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Check Balanced String

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "3340" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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: The sum of digits at even indices is 1 + 3 == 4, and the sum of digits at odd indices is 2 + 4 == 6. Since 4 is not equal to 6, num is not balanced. Example 2: Input: num = "24123" Output: true Explanation: The sum of digits at even indices is 2 + 1 + 3 == 6, and the sum of digits at odd indices is 4 + 2 == 6. Since both are equal the num is balanced. Constraints: 2 <= num.length <= 100 num consists of digits only

Explanation

Here's the breakdown of the solution:

  • Iterate and Accumulate: Iterate through the input string num, calculating the sum of digits at even indices and the sum of digits at odd indices separately.
  • Direct Comparison: After iterating through the entire string, directly compare the two sums. If they are equal, the string is balanced; otherwise, it's not.

  • Runtime Complexity: O(n), where n is the length of the string num. Storage Complexity: O(1).

Code

    def isBalanced(num: str) -> bool:
    """
    Checks if a string of digits is balanced, meaning the sum of digits at even
    indices equals the sum of digits at odd indices.

    Args:
        num: The string of digits.

    Returns:
        True if num is balanced, False otherwise.
    """
    even_sum = 0
    odd_sum = 0

    for i in range(len(num)):
        digit = int(num[i])
        if i % 2 == 0:
            even_sum += digit
        else:
            odd_sum += digit

    return even_sum == odd_sum

More from this blog

C

Chatmagic blog

2894 posts