Minimum Consecutive Cards to Pick Up - Problem
You are given an integer array cards where cards[i] represents the value of the ith card. A pair of cards are matching if the cards have the same value.
Return the minimum number of consecutive cards you have to pick up to have a pair of matching cards among the picked cards. If it is impossible to have matching cards, return -1.
Input & Output
Example 1 — Basic Case
$
Input:
cards = [3,4,2,3,1]
›
Output:
4
💡 Note:
The minimum consecutive cards to pick up is [3,4,2,3] which has length 4. Cards at index 0 and 3 match.
Example 2 — No Matching Cards
$
Input:
cards = [1,2,3,4]
›
Output:
-1
💡 Note:
No matching cards exist, so we cannot find any pair.
Example 3 — Adjacent Matching Cards
$
Input:
cards = [1,1]
›
Output:
2
💡 Note:
The minimum consecutive cards is [1,1] with length 2. Adjacent cards match.
Constraints
- 1 ≤ cards.length ≤ 105
- 0 ≤ cards[i] ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array of card values [3,4,2,3,1]
2
Find Duplicates
Track positions and find matching cards
3
Calculate Window
Minimum window size is 4
Key Takeaway
🎯 Key Insight: Track the last position of each card value - when we see a duplicate, the window size is current_position - last_position + 1
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code