LeetCode Problem Workspace

Minimum Consecutive Cards to Pick Up

Solve Minimum Consecutive Cards to Pick Up by tracking each card's last index and minimizing duplicate spans during one pass.

category

3

Topics

code_blocks

5

Code langs

hub

3

Related

Practice Focus

Medium · Array scanning plus hash lookup

bolt

Answer-first summary

Solve Minimum Consecutive Cards to Pick Up by tracking each card's last index and minimizing duplicate spans during one pass.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Array scanning plus hash lookup

Try AiBox Copilotarrow_forward

The fastest solution for Minimum Consecutive Cards to Pick Up is a single left-to-right scan with a hash map from card value to its most recent index. When you see a value again, the window from the previous index to the current index already gives a valid consecutive pickup length, so update the minimum immediately. This avoids testing full windows and turns the problem into repeated last-occurrence lookups.

Problem Statement

You receive an array called cards where each position stores the value written on that card. Your goal is to choose one consecutive block of cards such that the chosen block contains two cards with the same value, and you want that block to be as short as possible.

For cards = [3,4,2,3,4,7], the best answer is 4 because picking [3,4,2,3] or [4,2,3,4] gives a matching pair inside four consecutive cards. For cards = [1,0,5,3], no value repeats at all, so no consecutive pickup can contain a match and the result is -1.

Examples

Example 1

Input: cards = [3,4,2,3,4,7]

Output: 4

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

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

Solution Approach

Turn matching cards into distance between duplicate indices

A consecutive pickup that contains a pair of equal cards is fully determined once you know two equal values at indices i and j. The pickup length is j - i + 1, so the problem becomes finding the smallest such span across all duplicate values.

Scan once and store the last position of each card value

Use a hash table where lastSeen[value] stores the latest index where that value appeared. At each index i, if cards[i] was seen before at index prev, then prev to i is the shortest valid span ending at i for that value, because any earlier occurrence would only make the segment longer. Update the answer with i - prev + 1, then overwrite lastSeen[cards[i]] with i.

Return the best span or -1 if no duplicate ever appears

Initialize the answer to a large sentinel. After the scan, if the sentinel never changed, there was no repeated value, so return -1. Otherwise return the minimum span found. This matches the interview hint exactly: iterate through the cards and remember the last occurrence of each number.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

With the last-occurrence hash map, the array is scanned once, so the time complexity is O(n). The space complexity is O(k), where k is the number of distinct card values stored in the map, up to O(n) in the worst case. A true sliding window with frequency shrink logic is unnecessary here because the shortest valid segment is discovered the moment a duplicate is revisited.

What Interviewers Usually Probe

  • They want you to notice that every valid answer is bounded by two equal values, not by an arbitrary expandable window.
  • They expect the shortest segment for a repeated value to come from its most recent previous index, not from the first time it appeared.
  • They are testing whether you can replace window simulation with a direct last-seen hash lookup on an array scan.

Common Pitfalls or Variants

Common pitfalls

  • Using the first occurrence of a value instead of the most recent one, which misses shorter spans like the later 4-length window in [3,4,2,3,4,7].
  • Building a full sliding window with counts and shrink steps, which adds complexity without helping this exact duplicate-span problem.
  • Forgetting the +1 in j - i + 1, which undercounts the number of consecutive cards picked up.

Follow-up variants

  • Return the actual start and end indices of the shortest pickup instead of only its length.
  • Find the longest consecutive pickup that still contains at least one matching pair.
  • Process streaming card arrivals and report the current minimum duplicate span after each new card.

FAQ

What is the key idea for Minimum Consecutive Cards to Pick Up?

Track the last index of every card value in a hash map. When a value appears again, compute the consecutive pickup length from the previous index to the current one and keep the minimum.

Why is the most recent previous index the right one to use?

For a fixed current index, the nearest previous equal card creates the shortest possible segment ending there. Any older equal card would produce a longer consecutive pickup.

Is this really a sliding window problem?

It is often tagged with Sliding Window, but the clean solution is array scanning plus hash lookup. You do not need to grow and shrink a window because a duplicate immediately defines the only segment length that matters at that step.

Why does cards = [3,4,2,3,4,7] return 4?

The repeated 3 appears at indices 0 and 3, so that span has length 4. The repeated 4 at indices 1 and 4 also gives length 4, and no shorter duplicate span exists.

What should I return if no value repeats?

Return -1. If the scan finishes without finding any card value already in the hash map, no consecutive block can contain a matching pair.

terminal

Solution

Solution 1: Hash Table

We initialize the answer as $+\infty$. We traverse the array, and for each number $x$, if $\textit{last}[x]$ exists, it means $x$ has a matching pair of cards. In this case, we update the answer to $\textit{ans} = \min(\textit{ans}, i - \textit{last}[x] + 1)$. Finally, if the answer is $+\infty$, we return $-1$; otherwise, we return the answer.

1
2
3
4
5
6
7
8
9
class Solution:
    def minimumCardPickup(self, cards: List[int]) -> int:
        last = {}
        ans = inf
        for i, x in enumerate(cards):
            if x in last:
                ans = min(ans, i - last[x] + 1)
            last[x] = i
        return -1 if ans == inf else ans
Minimum Consecutive Cards to Pick Up Solution: Array scanning plus hash lookup | LeetCode #2260 Medium