{x}
blog image

Minimum Consecutive Cards to Pick Up

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 <= 105
  • 0 <= cards[i] <= 106

Minimum Consecutive Cards to Pick Up

This problem asks us to find the minimum number of consecutive cards needed to pick up to find a pair of matching cards (cards with the same value).

Approach: Sliding Window (Optimal)

While a hash table approach works, a sliding window provides a more efficient solution with the same time complexity but potentially lower constant factors. The hash table approach is described below.

Sliding Window Explanation:

  1. Initialization: We initialize a min_length variable to infinity (or a very large number) to store the minimum length of consecutive cards found so far. We also use a map (or dictionary) to track the last seen index of each card.

  2. Sliding Window: We iterate through the cards array using a sliding window approach. The window's size dynamically expands.

  3. Window Expansion: As we add a card to the window (iterate), we check if it's already in the map.

    • Match Found: If a match is found, it means we have a pair within the current window. We calculate the length of the current window (current index - last seen index of the matched card + 1) and update min_length if the current window's length is shorter.
    • Match Not Found: If no match is found, we update the last seen index of the card in the map.
  4. Result: After iterating through the entire array, if min_length remains unchanged (infinity), it means no matching pair was found, so we return -1. Otherwise, we return min_length.

Time Complexity: O(N), where N is the number of cards. We iterate through the array once. Space Complexity: O(K), where K is the number of unique cards. This is due to the space used by the map. In the worst case (all cards are unique), K can be N.

Approach: Hash Table

This approach uses a hash table (dictionary in Python) to efficiently store and retrieve the last seen index of each card.

Algorithm:

  1. Initialize: Create a hash table (last_seen) to store the last seen index of each card value. Initialize min_length to infinity (or a large number).

  2. Iterate: Iterate through the cards array. For each card:

    • Check if the card's value is already in last_seen.
      • If yes, it means we've seen this card before. Calculate the length of the consecutive subarray containing the current card and its previous occurrence (current_index - last_seen[card_value] + 1). Update min_length if this length is smaller than the current min_length.
      • If no, add the card's value and its index to last_seen.
  3. Return: If min_length is still infinity after iterating through all cards, return -1 (no matching pair found). Otherwise, return min_length.

Time Complexity: O(N), where N is the number of cards. We iterate through the array once. Space Complexity: O(K), where K is the number of unique cards. This is the space used by the hash table.

Code (Python) - Hash Table Approach

from collections import defaultdict
 
def minimumCardPickup(cards):
    last_seen = defaultdict(int)  # Use defaultdict for easier handling of missing keys
    min_length = float('inf')
    for i, card in enumerate(cards):
        if card in last_seen:
            length = i - last_seen[card] + 1
            min_length = min(min_length, length)
        last_seen[card] = i
    return min_length if min_length != float('inf') else -1
 

Code (Python) - Sliding Window Approach

from collections import defaultdict
 
def minimumCardPickup(cards):
    last_seen = defaultdict(int)
    min_length = float('inf')
    left = 0
    for right, card in enumerate(cards):
        if card in last_seen:
            length = right - last_seen[card] + 1
            min_length = min(min_length, length)
        last_seen[card] = right
 
    return min_length if min_length != float('inf') else -1
 

The code in other languages (Java, C++, Go, TypeScript) would follow a similar structure using their respective hash table or map implementations. The sliding window method would be very similar as well, just using the appropriate language's syntax and data structures.