#2260
Minimum Consecutive Cards to Pick Up
MediumArrayHash TableSliding WindowHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a HashMap to track the last index of each card value. This allows us to efficiently find the distance between matching cards in a single pass through the array.
⚙️
Algorithm
6 steps- 1Step 1: Initialize a HashMap to store the last occurrence of each card value.
- 2Step 2: Initialize a variable to store the minimum length found, set to infinity.
- 3Step 3: Iterate through the cards array, for each card, check if it exists in the HashMap.
- 4Step 4: If it exists, calculate the distance from the last occurrence to the current index and update the minimum length.
- 5Step 5: Update the HashMap with the current index of the card.
- 6Step 6: After the loop, return the minimum length found or -1 if no pairs exist.
solution.py8 lines
1def minimumCardPickup(cards):
2 last_index = {}
3 min_length = float('inf')
4 for i, card in enumerate(cards):
5 if card in last_index:
6 min_length = min(min_length, i - last_index[card] + 1)
7 last_index[card] = i
8 return min_length if min_length != float('inf') else -1ℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the cards array. The space complexity is O(n) due to the HashMap storing the last indices of card values.
- 1Using a HashMap allows for efficient lookups and updates, reducing the need for nested loops.
- 2The problem can be solved in a single pass, making it more efficient than checking all pairs.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.