Problem Statement:

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.

Example 1:

Input: cards = [3,4,2,3,4,7] Output: 4 Explanation: We can pick up the cards [3,4,2,3] which contain a matching pair of cards with value 3. Note that picking up the cards [4,2,3,4] is also optimal.

Example 2:

Input: cards = [1,0,5,3] Output: -1 Explanation: There is no way to pick up a set of consecutive cards that contain a pair of matching cards.

Constraints:

  • 1 <= cards.length <= 10^5
  • 0 <= cards[i] <= 10^6

Solution:

import java.util.HashSet;
 
public class Solution {
    public int minimumCardPickup(int[] cards) {
        if (cards.length == 1) {
            return -1; // If there is only one card, it's not possible to pick up a pair, hence return -1
        }
 
        int start = 0;
        int end = 1;
        int minLength = Integer.MAX_VALUE; // Initialize to maximum possible value
        HashSet<Integer> set = new HashSet<>(); // HashSet to track unique cards in the current window
 
        while (end < cards.length) {
            // Case 1: Cards at start and end are the same
            if (cards[start] == cards[end]) {
                int windowSize = end - start + 1; // Calculate window size
                minLength = Math.min(minLength, windowSize); // Update minLength if current window is smaller
 
                set.remove(cards[start]); // Remove the card at 'start' from set
                start++; // Move 'start' pointer to the right to shrink the window
            }
 
            // Case 2: Set already contains the card at 'end'
            if (set.contains(cards[end])) {
                // Slide 'start' pointer to the right until cards[start] equals cards[end]
                while (cards[start] != cards[end]) {
                    set.remove(cards[start]); // Remove cards[start] from set
                    start++; // Move 'start' pointer to the right
                }
                int windowSize = end - start + 1; // Calculate window size
                minLength = Math.min(minLength, windowSize); // Update minLength if current window is smaller
            }
 
            // Add the current card at 'end' to the set
            set.add(cards[end]);
            end++; // Move 'end' pointer to the right to expand the window
        }
 
        // Return minLength if it was updated; otherwise, return -1 indicating no valid window was found
        return minLength == Integer.MAX_VALUE ? -1 : minLength;
    }
}