3550. Smallest Index With Digit Sum Equal to Index LeetCode Solution
In this guide, you will get 3550. Smallest Index With Digit Sum Equal to Index LeetCode Solution with the best time and space complexity. The solution to Smallest Index With Digit Sum Equal to Index problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Smallest Index With Digit Sum Equal to Index solution in C++
- Smallest Index With Digit Sum Equal to Index solution in Java
- Smallest Index With Digit Sum Equal to Index solution in Python
- Additional Resources

Problem Statement of Smallest Index With Digit Sum Equal to Index
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.
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 <= 100
0 <= nums[i] <= 1000
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
3550. Smallest Index With Digit Sum Equal to Index LeetCode Solution in C++
class Solution {
public:
int smallestIndex(vector<int>& nums) {
for (int i = 0; i < nums.size(); ++i)
if (getDigitSum(nums[i]) == i)
return i;
return -1;
}
private:
int getDigitSum(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
return sum;
}
};
/* code provided by PROGIEZ */
3550. Smallest Index With Digit Sum Equal to Index LeetCode Solution in Java
class Solution {
public int smallestIndex(int[] nums) {
for (int i = 0; i < nums.length; ++i)
if (getDigitSum(nums[i]) == i)
return i;
return -1;
}
private int getDigitSum(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
return sum;
}
}
// code provided by PROGIEZ
3550. Smallest Index With Digit Sum Equal to Index LeetCode Solution in Python
class Solution:
def smallestIndex(self, nums: List[int]) -> int:
return next((i
for i, num in enumerate(nums)
if self._getDigitSum(num) == i), -1)
def _getDigitSum(self, num: int) -> int:
return sum(int(digit) for digit in str(num))
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.