Welcome to Subscribe On Youtube

3340. Check Balanced String

Description

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

Solutions

Solution 1: Simulation

We can use an array $f$ of length $2$ to record the sum of numbers at even indices and odd indices. Then, we traverse the string $\textit{nums}$ and add the numbers to the corresponding positions based on the parity of the indices. Finally, we check whether $f[0]$ is equal to $f[1]$.

The time complexity is $O(n)$, where $n$ is the length of the string $\textit{nums}$. The space complexity is $O(1)$.

  • class Solution {
        public boolean isBalanced(String num) {
            int[] f = new int[2];
            for (int i = 0; i < num.length(); ++i) {
                f[i & 1] += num.charAt(i) - '0';
            }
            return f[0] == f[1];
        }
    }
    
    
  • class Solution {
    public:
        bool isBalanced(string num) {
            int f[2]{};
            for (int i = 0; i < num.size(); ++i) {
                f[i & 1] += num[i] - '0';
            }
            return f[0] == f[1];
        }
    };
    
    
  • class Solution:
        def isBalanced(self, num: str) -> bool:
            f = [0, 0]
            for i, x in enumerate(map(int, num)):
                f[i & 1] += x
            return f[0] == f[1]
    
    
  • func isBalanced(num string) bool {
    	f := [2]int{}
    	for i, c := range num {
    		f[i&1] += int(c - '0')
    	}
    	return f[0] == f[1]
    }
    
    
  • function isBalanced(num: string): boolean {
        const f = [0, 0];
        for (let i = 0; i < num.length; ++i) {
            f[i & 1] += +num[i];
        }
        return f[0] === f[1];
    }
    
    

All Problems

All Solutions