#3550
Smallest Index With Digit Sum Equal to Index
EasyArrayMathHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Iterate through the array once, calculating the digit sum on-the-fly and checking against the index.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a loop to go through each index i in nums.
- 2Step 2: For each nums[i], calculate the digit sum directly.
- 3Step 3: If the digit sum equals i, return i; if no match after the loop, return -1.
solution.py5 lines
1def smallestIndex(nums):
2 for i in range(len(nums)):
3 if sum(int(d) for d in str(nums[i])) == i:
4 return i
5 return -1ℹ
Complexity note: We only traverse the array once, making it O(n) in time complexity, and we use constant space.
- 1Digit sum can be computed efficiently.
- 2The problem requires checking each index once.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.