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 Up INPUT cards array: 3 i=0 4 i=1 2 i=2 3 i=3 1 i=4 Matching pair: value 3 cards = [3,4,2,3,1] length = 5 Find min window with match Goal: Find minimum consecutive cards with a matching pair Return -1 if impossible ALGORITHM STEPS 1 Initialize HashMap to track last index minLen = infinity 2 Iterate Array For each card at index i Check if value seen before 3 Update Min If found: distance = i - lastIdx + 1 minLen = min(minLen, distance) 4 Store Position map[cards[i]] = i HashMap State: i=0: map[3]=0 i=3: map[3] exists! dist = 3-0+1 = 4 FINAL RESULT Minimum window found: 3 4 2 3 4 consecutive cards from index 0 to 3 OUTPUT 4 [OK] Verified Cards 3,4,2,3 contain matching pair (3,3) Key Insight: Use a HashMap to store the last seen index of each card value. When we encounter a card we've seen before, the window size is (current_index - last_index + 1). Track the minimum window across all matches. Time: O(n), Space: O(n) for the HashMap. TutorialsPoint - Minimum Consecutive Cards to Pick Up | Hash Map - Track Last Positions
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