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
Minimum Consecutive Cards to Pick Up3423101234Minimum Window [3,4,2,3]Matching cards at indices 0 and 3Find shortest consecutive sequence with duplicate cardsAnswer: 4
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
Asked in
Google 25 Amazon 18 Microsoft 15
32.0K Views
Medium Frequency
~15 min Avg. Time
987 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen