3340. Check Balanced String LeetCode Solution

In this guide, you will get 3340. Check Balanced String LeetCode Solution with the best time and space complexity. The solution to Check Balanced String problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Check Balanced String solution in C++
  4. Check Balanced String solution in Java
  5. Check Balanced String solution in Python
  6. Additional Resources
3340. Check Balanced String LeetCode Solution image

Problem Statement of Check Balanced String

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

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

3340. Check Balanced String LeetCode Solution in C++

class Solution {
 public:
  bool isBalanced(string num) {
    int balance = 0;
    int sign = 1;

    for (const char c : num) {
      balance += sign * (c - '0');
      sign *= -1;
    }

    return balance == 0;
  }
};
/* code provided by PROGIEZ */

3340. Check Balanced String LeetCode Solution in Java

class Solution {
  public boolean isBalanced(String num) {
    int balance = 0;
    int sign = 1;

    for (final char c : num.toCharArray()) {
      balance += sign * (c - '0');
      sign *= -1;
    }

    return balance == 0;
  }
}
// code provided by PROGIEZ

3340. Check Balanced String LeetCode Solution in Python

class Solution:
  def isBalanced(self, num: str) -> bool:
    nums = list(map(int, num))
    return sum(nums[::2]) == sum(nums[1::2])
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.