#2057

Smallest Index With Equal Value

Easy
ArrayArrayModulo operation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The brute force approach is already efficient for this problem, but we can still optimize by breaking out of the loop early if we find the first match.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a variable to store the smallest index found, starting with -1.
  2. 2Step 2: Loop through each index i of the array nums.
  3. 3Step 3: For each index, check if i mod 10 is equal to nums[i].
  4. 4Step 4: If the condition is true, return the current index immediately.
solution.py7 lines
1# Full working Python code
2
3def smallest_index(nums):
4    for i in range(len(nums)):
5        if i % 10 == nums[i]:
6            return i
7    return -1

Complexity note: The time complexity remains O(n) as we traverse the array once, but we may exit early if we find a match. Space complexity is O(1) since we use a constant amount of space.

  • 1The problem requires checking a simple condition for each index, making it straightforward.
  • 2Finding the first valid index allows for an immediate return, optimizing performance.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.