Smallest Index With Equal Value — Problem & Solution
Smallest Index With Equal Value solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Smallest Index With Equal Value is an easy coding problem on arrays and math, asked in Amazon and Google interviews.
- Difficulty: Easy
- Topics: Arrays, Math
- Asked at: Amazon, Google
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
nums is a 0-indexed array of digits. Return the smallest index i such that i mod 10 == nums[i], or -1 if there is no such index.
Example 1
Input: nums = [7,1,5]
Output: 1
Explanation: Index 0: 0 ≠ 7. Index 1: 1 mod 10 = 1 = nums[1].
Example 2
Input: nums = [3,0,1]
Output: -1
Example 3
Input: nums = [1,2,3,4,5,6,7,8,9,0,4,1]
Output: 11
Explanation: No index below 10 matches; 10 mod 10 = 0 ≠ 4, and 11 mod 10 = 1 = nums[11].
Constraints
1 <= nums.length <= 1000 <= nums[i] <= 9
Hints for Smallest Index With Equal Value
Hint 1
Check the indices in increasing order — the first match is the answer.
Hint 2
Compare
nums[i]withi % 10, not withi: from index 10 onwards the index has two digits.Hint 3
If the loop finishes without a match, return -1.
How to solve Smallest Index With Equal Value
Scanning indices from 0 upward and stopping at the first i with i % 10 == nums[i] returns the smallest such index by construction.
Approach
- For
ifrom 0 ton - 1: ifi % 10 == nums[i], returni. - Return -1.
Why it works
Every index is tested in increasing order, so the first one that passes is the smallest that passes; if none passes, -1 is correct.
Complexity
- Time —
O(n) - Space —
O(1)
Pitfalls
- Comparing with
iinstead ofi % 10misses every match at index 10 or above. - Return the index, not the value.
- Stop at the first match — later matches are larger.
Reference solution
Python
from typing import List
def smallestEqual(nums: List[int]) -> int:
for i, x in enumerate(nums):
if i % 10 == x:
return i
return -1Java
public static int smallestEqual(int[] nums) {
for (int i = 0; i < nums.length; i++) {
if (i % 10 == nums[i]) return i;
}
return -1;
}C++
int smallestEqual(vector<int>& nums) {
for (int i = 0; i < (int)nums.size(); i++) {
if (i % 10 == nums[i]) return i;
}
return -1;
}JavaScript
var smallestEqual = function(nums) {
for (var i = 0; i < nums.length; i++) {
if (i % 10 === nums[i]) return i;
}
return -1;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 1199 arrays problems · the whole catalogue
Learn the technique: Arrays