Minimum Consecutive Cards to Pick Up — HashMap Last-Seen (LC 2260)

Sanjeev SharmaSanjeev Sharma
5 min read

Advertisement

Problem Statement

LeetCode 2260 — Minimum Consecutive Cards to Pick Up (Medium)

You are given an integer array cards where cards[i] represents the value of the i-th card. Find the minimum number of consecutive cards you have to pick up to have a pair of matching cards. Return -1 if impossible.

Constraints:

  • 1 <= cards.length <= 10^5
  • 0 <= cards[i] <= 10^6
Input:  cards = [3, 4, 2, 3, 4, 7]
Output: 4
Explanation: [3,4,2,3] contains the pair (3,3). Length = 4.
Input:  cards = [1, 0, 5, 3]
Output: -1

Why This Problem Matters

This problem is a clean application of the last-seen index technique. Instead of maintaining a sliding window with a frequency map and shrinking logic, you track only the most recent position of each card value. When you see a value you have seen before, the window from that previous position to the current position is the shortest subarray containing that matching pair.

The key insight is that for any value, the shortest window containing two of it is always formed by its two most recent consecutive occurrences. Any earlier occurrence produces a longer window. This makes the last-seen map optimal — you need only one stored index per value.

This problem teaches candidates to select minimal state: when you only need the "nearest previous occurrence," a last-seen map suffices; when you need counts or all positions, you need richer state.

The Core Insight

Maintain last[value] = index — the most recent index where this value appeared.

When processing index i:

  • If cards[i] is in last: window length = i - last[cards[i]] + 1. Update the minimum.
  • Always update last[cards[i]] = i.

Why only the last occurrence? If value v appeared at positions p1 < p2 < i, the window using p2 has length i - p2 + 1 < i - p1 + 1. The most recent previous occurrence always gives the shortest window.

Visual Dry Run

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

icards[i]last mapwindow if matchmin ans
03{3:0}inf
14{3:0, 4:1}inf
22{3:0, 4:1, 2:2}inf
333-0+1=4; update 3:344
444-1+1=4; update 4:444
57{7:5}4

Answer: 4

Solution (Optimal)

def minimumCardPickup(cards: list[int]) -> int:
    last = {}
    ans = float('inf')
 
    for i, c in enumerate(cards):
        if c in last:
            ans = min(ans, i - last[c] + 1)
        last[c] = i
 
    return -1 if ans == float('inf') else ans
var minimumCardPickup = function(cards) {
    const last = new Map();
    let ans = Infinity;
 
    for (let i = 0; i < cards.length; i++) {
        if (last.has(cards[i])) {
            ans = Math.min(ans, i - last.get(cards[i]) + 1);
        }
        last.set(cards[i], i);
    }
 
    return ans === Infinity ? -1 : ans;
};

Time: O(n) — single pass; hash map operations are O(1) amortized Space: O(n) — at most n distinct card values in the map

Common Mistakes

  • Using a full sliding window with frequency map — more code, same complexity; last-seen map is simpler and sufficient
  • Not updating last[c] after computing the window — must store the latest index so the next occurrence computes a shorter window
  • Returning ans without converting infinity to -1 — if no duplicate exists, infinity remains
  • Initialising ans = 0 — 0 would be returned even when no match was found
  • Off-by-one: window from index p to index i has length i - p + 1 (inclusive)

Interview Tips

  • Explain why only the last occurrence matters: "Any earlier occurrence produces a longer window; only the most recent previous occurrence can give the shortest window"
  • State space is O(n) for the map — distinct card values can be up to n; mention this explicitly
  • If asked for the actual subarray: record (last[c], i) when the minimum is updated

Follow-up Questions

  • Find all matching pairs and their shortest windows: for each value, track all occurrences; scan adjacent pairs for minimum gap
  • Pairs of k matching cards (k > 2): track the last k-1 occurrences for each value; window length is i - occurrences[-(k-1)] + 1
  • Count all windows with a matching pair: use a sliding window with frequency map; count valid windows at each step

Key Takeaways

  • Track last[value] = most recent index for each card value — only one stored index per value is needed
  • When a duplicate is found at index i, window length = i - last[value] + 1; always update last[value] = i afterward
  • The minimum window is always formed by two consecutive occurrences of the same value in the array
  • Return -1 if ans remains infinity — no duplicate values in the array
  • Time O(n), space O(n) — single pass; simpler than a full sliding window approach

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro

Related reading