Skip to main content
Back to problems
#3340
Easy Algorithms

Check balanced string

String
82.5% acceptance
Feb 23, 2026
139
2
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn is_balanced(num: String) -> bool {
    let (even_sum, odd_sum) = num.bytes().enumerate().fold((0i32, 0i32), |(e, o), (i, b)| {
      let d = (b - b'0') as i32;
      if i % 2 == 0 { (e + d, o) } else { (e, o + d) }
    });
    even_sum == odd_sum
  }
}