#3550
Easy Algorithms Smallest index with digit sum equal to index
Array Math
80.1% acceptance
Feb 25, 2026
68
3
You are given an integer array nums.
Return the smallest index i such that the sum of the digits of nums[i] is equal to i.
If no such index exists, return -1.
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn smallest_index(nums: Vec<i32>) -> i32 {
fn digit_sum(mut x: i32) -> i32 {
let mut s = 0;
while x > 0 { s += x % 10; x /= 10; }
s
}
for (i, &v) in nums.iter().enumerate() {
if digit_sum(v) == i as i32 { return i as i32; }
}
-1
}
}