We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Smallest Index With Equal Value

Number: 2181

Difficulty: Easy

Paid? No

Companies: Google


Problem Description

Given a 0-indexed integer array nums, find and return the smallest index i such that i mod 10 equals nums[i]. If no such index exists, return -1.


Key Insights

  • Use a simple loop to iterate over the array.
  • For each index, compute i mod 10 and compare it to the element at that index.
  • Return early on finding a matching index to ensure minimal comparisons.
  • Since nums[i] is constrained to be between 0 and 9, the mod operation aligns naturally with the values.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the array. Space Complexity: O(1), as only a constant amount of extra space is used.


Solution

We iterate over the array, checking if the condition i mod 10 == nums[i] holds true at any index. We use a simple loop with a modulus operation at each iteration. If a match is found, we immediately return the index. If the loop completes without finding a match, we return -1. This approach leverages the simplicity of the modulo operation and the small constraint on the array's length.


Code Solutions

# Function to find the smallest index where i mod 10 equals nums[i]
def smallest_index(nums):
    # Iterate over each index and its corresponding value
    for i, value in enumerate(nums):
        # Check if the current index modulo 10 equals the value at that index
        if i % 10 == value:
            # If the condition is met, return the index immediately
            return i
    # If no index satisfies the condition, return -1
    return -1

# Example usage:
print(smallest_index([0, 1, 2]))  # Output: 0
print(smallest_index([4, 3, 2, 1]))  # Output: 2
print(smallest_index([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]))  # Output: -1
← Back to All Questions