Skip to main content
Back to problems
#2260
Medium Algorithms

Minimum consecutive cards to pick up

Array Hash Table Sliding Window
53.5% acceptance
Feb 25, 2026
1087
45
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_card_pickup(cards: Vec<i32>) -> i32 {
    use std::collections::HashMap;
    let mut last_seen: HashMap<i32, usize> = HashMap::new();
    let mut ans = i32::MAX;
    for (i, &card) in cards.iter().enumerate() {
      if let Some(&prev) = last_seen.get(&card) {
        let dist = (i - prev + 1) as i32;
        ans = ans.min(dist);
      }
      last_seen.insert(card, i);
    }
    if ans == i32::MAX { -1 } else { ans }
  }
}