LeetCode 3340: Check Balanced String Solution

Master LeetCode problem 3340 (Check Balanced String), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3340. Check Balanced String

Easy

Problem Explanation

Explanation:

To solve this problem, we need to iterate through the string and calculate the sums of digits at even and odd indices separately. If the two sums are equal, then the string is considered balanced. We can achieve this by iterating over the string and keeping track of the sums at even and odd indices.

  • Initialize two variables evenSum and oddSum to keep track of the sums at even and odd indices.
  • Iterate over the string, adding the digit to evenSum if the index is even and to oddSum if the index is odd.
  • After iterating through the entire string, compare the two sums. If they are equal, return true; otherwise, return false.

Time Complexity:

The time complexity of this solution is O(n), where n is the length of the input string.

Space Complexity:

The space complexity is O(1) as we are using only a constant amount of extra space.

:

Solution Code

class Solution {
    public boolean isBalancedString(String num) {
        int evenSum = 0, oddSum = 0;
        for (int i = 0; i < num.length(); i++) {
            int digit = num.charAt(i) - '0';
            if (i % 2 == 0) {
                evenSum += digit;
            } else {
                oddSum += digit;
            }
        }
        return evenSum == oddSum;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3340 (Check Balanced String)?

This page provides optimized solutions for LeetCode problem 3340 (Check Balanced String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3340 (Check Balanced String)?

The time complexity for LeetCode 3340 (Check Balanced String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3340 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3340 in Java, C++, or Python.

Back to LeetCode Solutions