Difficulty: Easy | Acceptance: 73.20% | Paid: No Topics: Array
Given a 0-indexed integer array nums, return the smallest index i such that i % 10 == nums[i]. If there is no such index, return -1.
- Examples
- Constraints
- Linear Scan
- Functional / Stream Approach
Examples
Input: nums = [0,2,3,4,0,1,5]
Output: 0
Explanation: 0 % 10 == 0 == nums[0].
Input: nums = [4,3,2,1]
Output: 2
Explanation: 2 % 10 == 2 == nums[2].
Input: nums = [1,2,3,4,5,6,7,8,9,0]
Output: -1
Explanation: There is no index i that satisfies i % 10 == nums[i].
Constraints
1 <= nums.length <= 100
0 <= nums[i] <= 1000
Linear Scan
Intuition Since we are looking for the smallest index, we can iterate through the array from left to right. The first index that satisfies the condition is the answer.
Steps
- Iterate through the array using a loop from index 0 to n-1.
- For each index i, check if i % 10 equals nums[i].
- If the condition is met, return i immediately.
- If the loop finishes without finding a match, return -1.
python
from typing import List
class Solution:
def smallestEqual(self, nums: List[int]) -> int:
for i in range(len(nums)):
if i % 10 == nums[i]:
return i
return -1Complexity
- Time: O(n)
- Space: O(1)
- Notes: This is the most optimal approach as we must check every element in the worst case.
Functional / Stream Approach
Intuition Utilize built-in functional programming features like streams, generators, or higher-order functions to find the index declaratively.
Steps
- Use the languageās specific functional utility to iterate and filter.
- Python: Use a generator expression with enumerate and next().
- Java: Use IntStream to generate indices and filter.
- JavaScript/TypeScript: use findIndex which accepts a predicate.
- C++: Use std::find_if with a lambda.
python
from typing import List
class Solution:
def smallestEqual(self, nums: List[int]) -> int:
return next((i for i, n in enumerate(nums) if i % 10 == n), -1)Complexity
- Time: O(n)
- Space: O(1)
- Notes: While syntactically different, the underlying complexity remains linear. Some functional implementations may have slight constant-time overhead compared to a raw loop.