Smallest Index With Digit Sum Equal to Index
EasyUpdated: Aug 2, 2025
Practice on:
Problem
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.
Examples
Example 1
Input: nums = [1,3,2]
Output: 2
Explanation:
* For `nums[2] = 2`, the sum of digits is 2, which is equal to index `i = 2`. Thus, the output is 2.
Example 2
Input: nums = [1,10,11]
Output: 1
Explanation:
* For `nums[1] = 10`, the sum of digits is `1 + 0 = 1`, which is equal to index `i = 1`.
* For `nums[2] = 11`, the sum of digits is `1 + 1 = 2`, which is equal to index `i = 2`.
* Since index 1 is the smallest, the output is 1.
Example 3
Input: nums = [1,2,3]
Output: -1
Explanation:
* Since no index satisfies the condition, the output is -1.
Constraints
1 <= nums.length <= 1000 <= nums[i] <= 1000
Solution
Method 1 – Linear Scan with Digit Sum Helper
Intuition
For each index, compute the sum of digits of nums[i] and compare to i. Return the first such index, or -1 if none exists.
Approach
- Loop through the array.
- For each index i, compute the sum of digits of nums[i].
- If it equals i, return i. If no such index, return -1.
Code
C++
#include <vector>
using namespace std;
class Solution {
public:
int smallestIndex(vector<int>& nums) {
for (int i = 0; i < nums.size(); ++i) {
int x = nums[i], s = 0;
while (x) { s += x % 10; x /= 10; }
if (s == i) return i;
}
return -1;
}
};
Java
class Solution {
public int smallestIndex(int[] nums) {
for (int i = 0; i < nums.length; ++i) {
int x = nums[i], s = 0;
while (x > 0) { s += x % 10; x /= 10; }
if (s == i) return i;
}
return -1;
}
}
Python
class Solution:
def smallestIndex(self, nums):
for i, x in enumerate(nums):
if sum(map(int, str(x))) == i:
return i
return -1
Complexity
- ⏰ Time complexity:
O(n * d), where n = len(nums), d = max number of digits (at most 4). - 🧺 Space complexity:
O(1)— No extra space used.