# 2260. Minimum Consecutive Cards to Pick Up

• Time: $O(n)$
• Space: $O(1)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution { public: int minimumCardPickup(vector& cards) { int ans = INT_MAX; unordered_map lastOccurrence; for (int i = 0; i < cards.size(); ++i) { if (lastOccurrence.count(cards[i])) ans = min(ans, i - lastOccurrence[cards[i]] + 1); lastOccurrence[cards[i]] = i; } return ans == INT_MAX ? -1 : ans; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Solution { public int minimumCardPickup(int[] cards) { int ans = Integer.MAX_VALUE; Map lastOccurrence = new HashMap<>(); for (int i = 0; i < cards.length; ++i) { if (lastOccurrence.containsKey(cards[i])) ans = Math.min(ans, i - lastOccurrence.get(cards[i]) + 1); lastOccurrence.put(cards[i], i); } return ans == Integer.MAX_VALUE ? -1 : ans; } } 
  1 2 3 4 5 6 7 8 9 10 11 class Solution: def minimumCardPickup(self, cards: List[int]) -> int: ans = math.inf lastOccurrence = {} for i, card in enumerate(cards): if card in lastOccurrence: ans = min(ans, i - lastOccurrence[card] + 1) lastOccurrence[card] = i return -1 if ans == math.inf else ans