Talentd
FleetCode
Make and follow sheets.Sign in

Minimum Consecutive Cards to Pick Up solution and explanation

MediumArrayHash TableSliding Window6 min read54.2% acceptanceUpdated 9 Apr 2026
Minimum Consecutive Cards to Pick Up | Leetcode 2260 | Maps | Contest 291 🔥🔥Coding Decoded · 7:59 · 2K viewsWatch on YouTube
9 more videos on this problem
  1. Minimum Consecutive Cards to Pick Up | Leetcode 2260 | Maps | Contest 291 🔥🔥Coding Decoded · 7:59 · 2K views
  2. LeetCode 2260 Solution in Hindi ( Minimum Consecutive Cards to Pick Up Solution in Hindi )Engineering Digest · 7:15 · 2K views
  3. 2260. Minimum Consecutive Cards to Pick Up (Leetcode Medium)Programming Live with Larry · 5:06 · 799 views
  4. 1.13 Minimum Consecutive Cards to Pick Up | Leetcode 2260 | | Easy template seriesCoding Samurai's · 14:19 · 772 views
  5. Leetcode Weekly Contest 291 | PROBLEM 2259 , 2260 , 2261code Explainer · 13:33 · 664 views
  6. 2260 Minimum Consecutive Cards to Pick Up Leetcode| Leetcode Weekly Contest 291 | Leetcode 2260Ashutosh sharma · 7:36 · 418 views
  7. Leetcode Weekly-contest-291 - Minimum Consecutive Cards to Pick UpPrakhar Agrawal · 9:12 · 363 views
  8. Minimum Consecutive Cards to Pick Up | LeetCode 2260 | Interview Questions | HashMapLeet Corner · 8:09 · 268 views
  9. LeetCode | 2260. Minimum Consecutive Cards to Pick Up | Sliding Window | Variable SizedCompl3x · 12:05 · 254 views
  10. Leetcode 2260 Minimum Consecutive Cards to Pick Up (Java) - Leetcode Contest 291TheAnalyticGuy · 4:29 · 224 views

The problem

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

Approach overview

Problem Overview: You are given an integer array cards where each value represents a card number. The goal is to find the smallest length of a consecutive subarray that contains two cards with the same value. If no such pair exists, return -1. The key challenge is efficiently detecting duplicate values while minimizing the window length.

Approach 1: Hash Map (Dictionary) Tracking Last Index (O(n) time, O(n) space)

Store the last index where each card value appeared using a hash map. Iterate through the array once. When you encounter a card value that already exists in the map, compute the window length i - lastIndex + 1. Update the minimum answer if this window is smaller. Then update the stored index to the current position. The hash lookup gives constant-time duplicate detection, making the entire scan linear. This approach works well because the shortest valid window must occur between two closest duplicate occurrences. The data structure used is a hash table for O(1) lookups while iterating the array.

Approach 2: Sliding Window Technique (O(n) time, O(n) space)

Maintain a sliding window using two pointers and a frequency map. Expand the right pointer while tracking card counts inside the window. When a card frequency becomes greater than 1, a duplicate exists in the window. Update the answer using the current window length. Then shrink the window from the left until the duplicate condition disappears. This ensures the window always moves toward the smallest valid segment containing duplicate cards. Each element enters and leaves the window at most once, so the total runtime stays linear. This method demonstrates a classic sliding window pattern used for subarray optimization problems.

Recommended for interviews: The hash map index-tracking solution is usually what interviewers expect. It directly captures the key insight: the smallest valid segment occurs between two nearest equal cards. The sliding window approach also runs in O(n) time and shows strong understanding of window-based subarray optimization, but the hash map solution is simpler and easier to implement under time pressure.

Approach 1: Approach 1: Use a Hash Map (Dictionary)

In this approach, we'll use a hash map to keep track of the last index of each card value encountered as we iterate through the array. The hash map will store the card value as the key and its last occurrence index as the value. As we scan through the cards, if a card has been seen before, compute the distance from its last occurrence. This distance will be the number of consecutive cards needed to include these two matching cards. We'll update our minimum distance whenever we find a smaller value. This approach is efficient and runs in O(n) time complexity.

def minimum_card_pickup(cards):
    last_seen = {}
    min_length = float('inf')
    for i, card in enumerate(cards):
        if card in last_seen:
            min_length = min(min_length, i - last_seen[card] + 1)
        last_seen[card] = i
    return min_length if min_length != float('inf') else -1
import java.util.HashMap;

public class Solution {
    public int minimumCardPickup(int[] cards) {
        HashMap<Integer, Integer> lastSeen = new HashMap<>();
        int minLength = Integer.MAX_VALUE;
        for (int i = 0; i < cards.length; i++) {
            if (lastSeen.containsKey(cards[i])) {
                minLength = Math.min(minLength, i - lastSeen.get(cards[i]) + 1);
            }
            lastSeen.put(cards[i], i);
        }
        return minLength == Integer.MAX_VALUE ? -1 : minLength;
    }
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] cards = {3, 4, 2, 3, 4, 7};
        System.out.println(solution.minimumCardPickup(cards));  // Output: 4
     }
}
#include <iostream>
#include <unordered_map>
#include <vector>
#include <climits>
using namespace std;

int minimumCardPickup(vector<int>& cards) {
    unordered_map<int, int> last_seen;
    int min_length = INT_MAX;
    for (int i = 0; i < cards.size(); ++i) {
        if (last_seen.find(cards[i]) != last_seen.end()) {
            min_length = min(min_length, i - last_seen[cards[i]] + 1);
        }
        last_seen[cards[i]] = i;
    }
    return min_length == INT_MAX ? -1 : min_length;
}

int main() {
    vector<int> cards = {3, 4, 2, 3, 4, 7};
    cout << minimumCardPickup(cards) << endl;  // Output: 4
    return 0;
}
function minimumCardPickup(cards) {
    const lastSeen = new Map();
    let minLength = Infinity;
    for (let i = 0; i < cards.length; i++) {
        if (lastSeen.has(cards[i])) {
            minLength = Math.min(minLength, i - lastSeen.get(cards[i]) + 1);
        }
        lastSeen.set(cards[i], i);
    }
    return minLength === Infinity ? -1 : minLength;
}

console.log(minimumCardPickup([3, 4, 2, 3, 4, 7]));  // Output: 4
#include <stdio.h>
#include <limits.h>
#define MAX_VALUE 1000001

int minimumCardPickup(int* cards, int cardsSize) {
    int last_seen[MAX_VALUE];
    for (int i = 0; i < MAX_VALUE; i++)
        last_seen[i] = -1;
    int min_length = INT_MAX;
    for (int i = 0; i < cardsSize; i++) {
        if (last_seen[cards[i]] != -1) {
            int length = i - last_seen[cards[i]] + 1;
            if (length < min_length)
                min_length = length;
        }
        last_seen[cards[i]] = i;
    }
    return min_length == INT_MAX ? -1 : min_length;
}

int main() {
    int cards[] = {3, 4, 2, 3, 4, 7};
    int size = sizeof(cards) / sizeof(cards[0]);
    printf("%d\n", minimumCardPickup(cards, size));  // Output: 4
    return 0;
}
using System;
using System.Collections.Generic;

public class Solution {
    public int MinimumCardPickup(int[] cards) {
        Dictionary<int, int> lastSeen = new Dictionary<int, int>();
        int minLength = int.MaxValue;
        for (int i = 0; i < cards.Length; i++) {
            if (lastSeen.ContainsKey(cards[i])) {
                minLength = Math.Min(minLength, i - lastSeen[cards[i]] + 1);
            }
            lastSeen[cards[i]] = i;
        }
        return minLength == int.MaxValue ? -1 : minLength;
    }
    static void Main(string[] args) {
        Solution solution = new Solution();
        int[] cards = {3, 4, 2, 3, 4, 7};
        Console.WriteLine(solution.MinimumCardPickup(cards));  // Output: 4
    }
}

The function iterates over the cards using a for-loop. It maintains a dictionary last_seen to store the last index where each card value was observed. If the card has been seen before, it calculates the current sequence length needed to include these two, by taking the difference between the current index and the last seen index. If this length is smaller than the previously recorded minimum, it updates the min_length. Finally, if no pair is found, it returns -1.

Complexity

Time Complexity: O(n) because we only make a single pass through the cards. Space Complexity: O(u) where u is the number of unique card values.

Try this approach in the editor

Approach 2: Approach 2: Sliding Window Technique

In this method, we leverage a sliding window combined with a hash map (or dictionary) to track the last seen position of each card value. The sliding window allows us to efficiently find the shortest subarray with a pair by adjusting the window as needed. This approach optimally processes the input while maintaining minimal space usage and constant time checks for duplicates within the current window range.

def minimum_card_pickup(cards):
    card_map = {}
    left = 0
    min_length = float('inf')
    for right, card in enumerate(cards):
        if card in card_map and card_map[card] >= left:
            min_length = min(min_length, right - card_map[card] + 1)
            left = card_map[card] + 1
        card_map[card] = right
    return min_length if min_length != float('inf') else -1
import java.util.HashMap;

public class Solution {
    public int minimumCardPickup(int[] cards) {
        HashMap<Integer, Integer> cardMap = new HashMap<>();
        int minLength = Integer.MAX_VALUE;
        int left = 0;
        for (int right = 0; right < cards.length; right++) {
            if (cardMap.containsKey(cards[right]) && cardMap.get(cards[right]) >= left) {
                minLength = Math.min(minLength, right - cardMap.get(cards[right]) + 1);
                left = cardMap.get(cards[right]) + 1;
            }
            cardMap.put(cards[right], right);
        }
        return minLength == Integer.MAX_VALUE ? -1 : minLength;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] cards = {3, 4, 2, 3, 4, 7};
        System.out.println(solution.minimumCardPickup(cards));  // Output: 4
    }
}
#include <iostream>
#include <unordered_map>
#include <vector>
#include <climits>
using namespace std;

int minimumCardPickup(vector<int>& cards) {
    unordered_map<int, int> cardMap;
    int minLength = INT_MAX;
    int left = 0;
    for (int right = 0; right < cards.size(); ++right) {
        if (cardMap.find(cards[right]) != cardMap.end() && cardMap[cards[right]] >= left) {
            minLength = min(minLength, right - cardMap[cards[right]] + 1);
            left = cardMap[cards[right]] + 1;  
        }
        cardMap[cards[right]] = right;
    }
    return minLength == INT_MAX ? -1 : minLength;
}

int main() {
    vector<int> cards = {3, 4, 2, 3, 4, 7};
    cout << minimumCardPickup(cards) << endl;  // Output: 4
    return 0;
}
function minimumCardPickup(cards) {
    const lastSeen = new Map();
    let minLength = Infinity;
    let left = 0;
    for (let right = 0; right < cards.length; right++) {
        if (lastSeen.has(cards[right]) && lastSeen.get(cards[right]) >= left) {
            minLength = Math.min(minLength, right - lastSeen.get(cards[right]) + 1);
            left = lastSeen.get(cards[right]) + 1;
        }
        lastSeen.set(cards[right], right);
    }
    return minLength === Infinity ? -1 : minLength;
}

console.log(minimumCardPickup([3, 4, 2, 3, 4, 7]));  // Output: 4
#include <stdio.h>
#include <limits.h>
#define MAX_SIZE 1000001

int minimumCardPickup(int* cards, int cardsSize) {
    int cardMap[MAX_SIZE];
    for (int i = 0; i < MAX_SIZE; i++) cardMap[i] = -1;
    int min_length = INT_MAX, left = 0;
    for (int right = 0; right < cardsSize; right++) {
        if (cardMap[cards[right]] >= left) {
            min_length = (min_length > (right - cardMap[cards[right]] + 1)) ? (right - cardMap[cards[right]] + 1) : min_length;
            left = cardMap[cards[right]] + 1;
        }
        cardMap[cards[right]] = right;
    }
    return min_length == INT_MAX ? -1 : min_length;
}

int main() {
    int cards[] = {3, 4, 2, 3, 4, 7};
    int size = sizeof(cards) / sizeof(cards[0]);
    printf("%d\n", minimumCardPickup(cards, size));  // Output: 4
    return 0;
}
using System;
using System.Collections.Generic;

public class Solution {
    public int MinimumCardPickup(int[] cards) {
        Dictionary<int, int> lastSeen = new Dictionary<int, int>();
        int minLength = int.MaxValue;
        int left = 0;
        for (int right = 0; right < cards.Length; right++) {
            if (lastSeen.ContainsKey(cards[right]) && lastSeen[cards[right]] >= left) {
                minLength = Math.Min(minLength, right - lastSeen[cards[right]] + 1);
                left = lastSeen[cards[right]] + 1;
            }
            lastSeen[cards[right]] = right;
        }
        return minLength == int.MaxValue ? -1 : minLength;
    }

    static void Main(string[] args) {
        Solution solution = new Solution();
        int[] cards = {3, 4, 2, 3, 4, 7};
        Console.WriteLine(solution.MinimumCardPickup(cards));  // Output: 4
    }
}

This function uses a sliding window to keep track of the range of cards being considered. card_map records the most recent index of each card. If a card reappears within the current window (i.e., from the left to the current right index), we compute the window size and update the minimum length. The sliding window is adjusted by moving the left side to one index past the last duplicate.

Complexity

Time Complexity: O(n), Space Complexity: O(u).

Try this approach in the editor

Approach 3: Hash Table

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

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the array.

function minimumCardPickup(cards: number[]): number {
    const n = cards.length;
    const last = new Map<number, number>();
    let ans = n + 1;
    for (let i = 0; i < n; ++i) {
        if (last.has(cards[i])) {
            ans = Math.min(ans, i - last.get(cards[i]) + 1);
        }
        last.set(cards[i], i);
    }
    return ans > n ? -1 : ans;
}
func minimumCardPickup(cards []int) int {
	last := map[int]int{}
	n := len(cards)
	ans := n + 1
	for i, x := range cards {
		if j, ok := last[x]; ok && ans > i-j+1 {
			ans = i - j + 1
		}
		last[x] = i
	}
	if ans > n {
		return -1
	}
	return ans
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Use a Hash Map (Dictionary)

Time Complexity: O(n) because we only make a single pass through the cards. Space Complexity: O(u) where u is the number of unique card values.

Approach 2: Sliding Window Technique

Time Complexity: O(n), Space Complexity: O(u).

Hash Table–

Complexity analysis

ApproachTimeSpaceWhen to Use
Hash Map (Track Last Index)O(n)O(n)Best general solution. Quickly computes minimum distance between duplicate values.
Sliding Window with Frequency MapO(n)O(n)Useful when practicing sliding window patterns or when solving similar subarray problems with duplicates.

Frequently asked questions

Is Minimum Consecutive Cards to Pick Up easy or hard?

The problem is classified as Medium difficulty. The main challenge is recognizing that the smallest valid subarray occurs between two closest duplicate cards and implementing an efficient hash map or sliding window solution.

How to solve Minimum Consecutive Cards to Pick Up in O(n)?

Iterate through the array while storing the last index of each card value in a hash map. When the same value appears again, compute the window length using currentIndex - previousIndex + 1 and update the minimum result. This single-pass strategy ensures linear time complexity.

Minimum Consecutive Cards to Pick Up Python or Java solution?

Both Python and Java solutions typically use a dictionary or HashMap to store card indices. During iteration, compute the distance between the current index and the previous occurrence. This produces an O(n) time solution with simple implementation in either language.

What is the best approach for Minimum Consecutive Cards to Pick Up?

The hash map approach that tracks the last index of each card is the most efficient and simplest solution. As you iterate through the array, check if the card appeared before and compute the distance between the two indices. This produces the smallest consecutive segment containing duplicates in O(n) time and O(n) space.

What data structure is used in Minimum Consecutive Cards to Pick Up?

The primary data structure is a hash table (dictionary or map). It stores the most recent index of each card value so duplicates can be detected instantly during iteration.

What is the time complexity of Minimum Consecutive Cards to Pick Up?

The optimal solutions run in O(n) time because the array is scanned once. Hash map lookups and updates occur in constant time on average. Space complexity is O(n) in the worst case if all card values are unique and stored in the map.

Is Minimum Consecutive Cards to Pick Up asked at Google or Amazon interviews?

Array and hash map problems with duplicate detection frequently appear in interviews at companies like Amazon, Google, and Meta. While this exact problem may vary, the underlying concept of tracking previous indices with a hash table is a common interview pattern.

Comments

Now write it yourselfClose this page and solve Minimum Consecutive Cards to Pick Up in the editor, without looking.
Practise Minimum Consecutive Cards to Pick Up