Minimum Consecutive Cards to Pick Up - Problem

Imagine you're a magician performing a card trick where you need to find matching pairs in the quickest way possible! ๐ŸŽฉโœจ

You are given an integer array cards where cards[i] represents the value of the i-th card. A pair of cards are matching if they have the same value.

Your challenge is to return the minimum number of consecutive cards you have to pick up to guarantee you have a pair of matching cards among the picked cards. If it's impossible to have matching cards (all cards are unique), return -1.

Example: If you have cards [3,4,2,3,4,7], you could pick up cards from index 0 to 3 (that's 4 consecutive cards: [3,4,2,3]) to get a matching pair of 3's. But there's a better way - pick up from index 1 to 4 (that's 4 consecutive cards: [4,2,3,4]) to get matching 4's. The minimum is 4 consecutive cards.

Input & Output

example_1.py โ€” Basic Case
$ Input: [3,4,2,3,4,7]
โ€บ Output: 4
๐Ÿ’ก Note: We can pick cards from index 0 to 3: [3,4,2,3] (length 4) or from index 1 to 4: [4,2,3,4] (length 4). Both contain matching pairs. The minimum consecutive cards needed is 4.
example_2.py โ€” No Matches
$ Input: [1,2,3,4]
โ€บ Output: -1
๐Ÿ’ก Note: All cards are unique, so there are no matching pairs. It's impossible to find consecutive cards with duplicates, hence return -1.
example_3.py โ€” Adjacent Duplicates
$ Input: [1,2,2,3]
โ€บ Output: 2
๐Ÿ’ก Note: We have adjacent matching cards at indices 1 and 2 (both are 2). The minimum consecutive cards to pick up is just these 2 cards.

Constraints

  • 1 โ‰ค cards.length โ‰ค 105
  • 0 โ‰ค cards[i] โ‰ค 106
  • At least one duplicate must exist for a valid answer

Visualization

Tap to expand
๐ŸŽฉ The Magician's Card Memory TrickCards Being Dealt3Position 04Position 12Position 23Position 34Position 47Position 5๐Ÿง  Magician's MemoryCard 3: Last seen at 0Card 4: Last seen at 1Card 2: Last seen at 2โœจ Found duplicate 3!Distance: 3 - 0 + 1 = 4Matching Pair!4 consecutive cards๐ŸŽฏ The trick: Remember the last position of each card value!When you see a duplicate, you've found a consecutive sequence with matching cards.
Understanding the Visualization
1
Deal First Card (3)
Remember: Card 3 was at position 0
2
Deal Cards 4, 2
Remember: Card 4 at position 1, Card 2 at position 2
3
Deal Second Card 3
Aha! Seen card 3 before at position 0. Distance = 3-0+1 = 4 cards
4
Continue Dealing
Keep tracking minimum distance for any duplicate pairs found
Key Takeaway
๐ŸŽฏ Key Insight: Use a hash map to remember the last position of each card. When you encounter a duplicate, the distance between positions gives you a valid consecutive subarray length!
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 28
41.2K Views
Medium Frequency
~15 min Avg. Time
1.8K 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