Minimum Consecutive Cards to Pick Up

Given an array of integers cards, return the minimum number of consecutive cards you have to pick up to have a pair of matching cards. If it is impossible, return -1.

Example 1
Input: [3,4,2,3,4,7] → Output: 4
Example 2
Input: [1,0,5,3] → Output: -1

Solution Approach

Use a HashMap to track the last seen index of each card value. For each card, if seen before, the window size is current_index - last_index + 1. Track the minimum.

  • Maintain lastSeen HashMap.
  • For each index i: if lastSeen contains cards[i], compute window = i - lastSeen[cards[i]] + 1, update min.
  • Update lastSeen[cards[i]] = i.
  • Return min or -1 if no pair found.
Java
import java.util.*;

class Solution {
    public int minimumCardPickup(int[] cards) {
        Map<Integer, Integer> lastSeen = new HashMap<>();
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < cards.length; i++) {
            if (lastSeen.containsKey(cards[i]))
                min = Math.min(min, i - lastSeen.get(cards[i]) + 1);
            lastSeen.put(cards[i], i);
        }
        return min == Integer.MAX_VALUE ? -1 : min;
    }
}
  • Time Complexity: O(N)
  • Space Complexity: O(N)