Talentd
FleetCode
Make and follow sheets.Sign in

Check Balanced String solution and explanation

EasyString5 min read82.3% acceptanceUpdated 9 Apr 2026
Check Balanced String | Leetcode 3340Technosage · 7:03 · 2K viewsWatch on YouTube
9 more videos on this problem
  1. Check Balanced String | Leetcode 3340Technosage · 7:03 · 2K views
  2. 3340. Check Balanced String (Leetcode Easy)Programming Live with Larry · 2:52 · 249 views
  3. 3340. Check Balanced String || C++ solution || LeetCodeCodeQuest · 3:31 · 185 views
  4. 3340. Check Balanced String | Leetcode Problem Solving CPPNishit · 4:15 · 65 views
  5. Leetcode 3340 Check Balanced String - In Hindi ExplanationAlgorithmicIQ · 6:14 · 36 views
  6. LeetCode 3340 | Check Balanced String | Easy C++ SolutionProjectForge · 3:59 · 10 views
  7. LeetCode 3340 - Check Balanced String | Prefix Sum Logic | C++ Full SolutionJALAK PALAN · 5:02 · 8 views
  8. LeetCode #3340 | Check Balanced String | String Traversal Approach in C++Code with Vishv Patel · 4:45 · 4 views
  9. LeetCode 3340: Check Balanced String Explained in C++ | Step-by-StepJonty Patel · 7:46 · 2 views
  10. Leetcode 3340 Balanced String Check | C++ SolutionJon · 2:05 · 2 views

The problem

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

Approach overview

Problem Overview: You are given a numeric string. A string is considered balanced when the sum of digits at even indices equals the sum of digits at odd indices. The task is to compute both sums and return whether they are equal.

Approach 1: Simple Iterative Sum Calculation (O(n) time, O(1) space)

The most direct approach is to scan the string once and maintain two running totals: one for even indices and one for odd indices. For every character s[i], convert it to its numeric value using s[i] - '0' (or equivalent in your language). If i % 2 == 0, add the digit to the even sum; otherwise add it to the odd sum. After processing the entire string, compare the two totals. If they match, the string is balanced.

This approach works because the problem only requires a parity-based partition of indices. There is no need for additional data structures or preprocessing. The algorithm performs a single pass through the string, making the time complexity O(n) and the extra space usage O(1). This is the simplest and most readable implementation, which makes it ideal for interviews and production code where clarity matters.

Approach 2: Index Check and Conditional Sum (O(n) time, O(1) space)

This variation keeps the same single-pass idea but focuses on the index parity check as the core operation. Iterate through the string and use a conditional branch based on the index: if the index is even, accumulate into one variable; otherwise accumulate into another. The digit extraction and accumulation happen in the same loop, so the entire computation remains linear.

The key insight is that the position of each character determines which group it contributes to. No sorting, extra arrays, or prefix structures are needed. This keeps memory usage constant while maintaining a straightforward implementation. The algorithm again runs in O(n) time with O(1) auxiliary space.

This style is sometimes preferred when writing tight loops or implementing quick checks in competitive programming, because the logic stays compact and predictable. It is essentially a lightweight simulation of the rule that defines a balanced string.

Recommended for interviews: The single-pass iterative approach is exactly what interviewers expect. A brute-force alternative doesn't really exist here because the optimal strategy is already straightforward. Showing a clean loop over the string, careful digit conversion, and correct index parity handling demonstrates solid fundamentals and attention to detail.

Approach 1: Simple Iterative Sum Calculation

This approach involves iterating over the string and maintaining two sums: one for digits at even indices and another for digits at odd indices. By the end of the iteration, compare the two sums to determine if the string is balanced.

def is_balanced(num: str) -> bool:
    even_sum = 0
    odd_sum = 0
    for i, digit in enumerate(num):
        if i % 2 == 0:
            even_sum += int(digit)
        else:
            odd_sum += int(digit)
    return even_sum == odd_sum
public boolean isBalanced(String num) {
    int evenSum = 0, oddSum = 0;
    for (int i = 0; i < num.length(); i++) {
        if (i % 2 == 0) {
            evenSum += Character.getNumericValue(num.charAt(i));
        } else {
            oddSum += Character.getNumericValue(num.charAt(i));
        }
    }
    return evenSum == oddSum;
}
#include <string>

bool isBalanced(const std::string& num) {
    int evenSum = 0, oddSum = 0;
    for (size_t i = 0; i < num.size(); ++i) {
        if (i % 2 == 0) {
            evenSum += num[i] - '0';
        } else {
            oddSum += num[i] - '0';
        }
    }
    return evenSum == oddSum;
}
function isBalanced(num) {
    let evenSum = 0, oddSum = 0;
    for (let i = 0; i < num.length; i++) {
        let digit = parseInt(num[i], 10);
        if (i % 2 === 0) {
            evenSum += digit;
        } else {
            oddSum += digit;
        }
    }
    return evenSum === oddSum;
}
#include <stdbool.h>
#include <string.h>

bool isBalanced(const char* num) {
    int evenSum = 0, oddSum = 0;
    int len = strlen(num);
    for (int i = 0; i < len; ++i) {
        if (i % 2 == 0) {
            evenSum += num[i] - '0';
        } else {
            oddSum += num[i] - '0';
        }
    }
    return evenSum == oddSum;
}
public bool IsBalanced(string num) {
    int evenSum = 0, oddSum = 0;
    for (int i = 0; i < num.Length; i++) {
        int digit = num[i] - '0';
        if (i % 2 == 0) {
            evenSum += digit;
        } else {
            oddSum += digit;
        }
    }
    return evenSum == oddSum;
}

In Python, we iterate over the string using enumerate for index tracking. Convert each character to an integer and update even_sum or odd_sum as appropriate by index parity. The result is determined by comparing these sums.

Complexity

Time Complexity: O(n), single pass through the string.
Space Complexity: O(1), fixed space is used for sum variables.

Try this approach in the editor

Approach 2: Index Check and Conditional Sum

Instead of calculating sums in a single pass, we can briefly check each character's index. This involves conditional logic within a loop to segregate digits to their corresponding index-based sums.

def is_balanced_v2(num: str) -> bool:
    even_sum = 0
    odd_sum = 0
    for i, digit in enumerate(num):
        digit = int(digit)
        if i % 2 == 0:
            even_sum += digit
        else:
            odd_sum += digit
    return even_sum == odd_sum
public boolean isBalancedV2(String num) {
    int evenSum = 0, oddSum = 0;
    for (int i = 0; i < num.length(); i++) {
        if (i % 2 == 0)
            evenSum += Character.getNumericValue(num.charAt(i));
        else
            oddSum += Character.getNumericValue(num.charAt(i));
    }
    return evenSum == oddSum;
}
#include <string>

bool isBalancedV2(const std::string& num) {
    int evenSum = 0, oddSum = 0;
    for (size_t i = 0; i < num.size(); ++i) {
        int value = num[i] - '0';
        if (i % 2 == 0) evenSum += value;
        else oddSum += value;
    }
    return evenSum == oddSum;
}
function isBalancedV2(num) {
    let evenSum = 0;
    let oddSum = 0;
    for (let i = 0; i < num.length; i++) {
        let digitValue = parseInt(num[i], 10);
        if (i % 2 === 0) {
            evenSum += digitValue;
        } else {
            oddSum += digitValue;
        }
    }
    return evenSum === oddSum;
}
#include <stdbool.h>
#include <string.h>

bool isBalanced(const char* num) {
    int evenSum = 0, oddSum = 0;
    for (int i = 0; num[i] != '\0'; i++) {
        if (i % 2) {
            oddSum += num[i] - '0';
        } else {
            evenSum += num[i] - '0';
        }
    }
    return evenSum == oddSum;
}
public bool IsBalancedV2(string num) {
    int evenSum = 0, oddSum = 0;
    for (int i = 0; i < num.Length; i++) {
        int digit = num[i] - '0';
        if (i % 2 == 0) evenSum += digit;
        else oddSum += digit;
    }
    return evenSum == oddSum;
}

This Python implementation relies on comprehensively checking and updating sums based on index parity through quick inline checks for odd/even index and executing summation accordingly.

Complexity

Time Complexity: O(n), iterating once for string processing.
Space Complexity: O(1), only a stable amount of space for storage and logic is needed.

Try this approach in the editor

Approach 3: 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 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 nums. The space complexity is O(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];
}
func isBalanced(num string) bool {
	f := [2]int{}
	for i, c := range num {
		f[i&1] += int(c - '0')
	}
	return f[0] == f[1]
}
impl Solution {
    pub fn is_balanced(num: String) -> bool {
        let mut f = [0; 2];
        for (i, x) in num.as_bytes().iter().enumerate() {
            f[i & 1] += (x - b'0') as i32;
        }
        f[0] == f[1]
    }
}
class Solution {
    /**
     * @param String $num
     * @return Boolean
     */
    function isBalanced($num) {
        $f = [0, 0];
        foreach (str_split($num) as $i => $ch) {
            $f[$i & 1] += ord($ch) - 48;
        }
        return $f[0] == $f[1];
    }
}
object Solution {
    def isBalanced(num: String): Boolean = {
        val f = Array(0, 0)
        for (i <- num.indices) {
            f(i & 1) += num(i) - '0'
        }
        f(0) == f(1)
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Simple Iterative Sum Calculation

Time Complexity: O(n), single pass through the string.
Space Complexity: O(1), fixed space is used for sum variables.

Index Check and Conditional Sum

Time Complexity: O(n), iterating once for string processing.
Space Complexity: O(1), only a stable amount of space for storage and logic is needed.

Simulation–

Complexity analysis

ApproachTimeSpaceWhen to Use
Simple Iterative Sum CalculationO(n)O(1)Best general solution. Clean and readable single-pass logic.
Index Check and Conditional SumO(n)O(1)Useful when implementing compact loops or competitive programming solutions.

Frequently asked questions

Is Check Balanced String easy or hard?

Check Balanced String is categorized as an Easy problem. The solution only requires basic string traversal, digit conversion, and conditional checks based on index parity.

Check Balanced String Python/Java solution

Both Python and Java implementations use the same logic: loop through the string, convert characters to digits, and update the correct sum based on index parity. The algorithm remains O(n) time and O(1) space across all languages including C++, JavaScript, and C#.

How to solve Check Balanced String in O(n)?

Iterate through the string from index 0 to n-1. Convert each character to its numeric value and add it to either the even-index sum or odd-index sum depending on i % 2. After the loop finishes, compare the two sums to determine whether the string is balanced.

What is the best approach for Check Balanced String?

The best approach is a single-pass iteration through the string while maintaining two sums for even and odd indices. Convert each character to a digit and update the correct sum based on index parity. This method runs in O(n) time and uses O(1) extra space.

Is Check Balanced String asked at Google/Amazon/Meta?

This problem reflects common string iteration and index-parity logic often seen in screening rounds. While the exact problem ID may not appear frequently, similar parity-sum and string traversal questions are common in interviews at large tech companies.

What data structure is used in Check Balanced String?

No additional data structure is required. The solution operates directly on the input string and uses two integer variables to track the running sums for even and odd indices.

What is the time complexity of Check Balanced String?

The time complexity is O(n) because the algorithm scans the string exactly once. Each character is processed with constant-time operations such as digit conversion and addition. Space complexity remains O(1) since only two counters are stored.

Comments

Now write it yourselfClose this page and solve Check Balanced String in the editor, without looking.
Practise Check Balanced String