Minimum Consecutive Cards to Pick Up Problem
Description
LeetCode Problem 2260.
You are given an integer array cards where cards[i] represents the value of the i^th 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 <= 10^50 <= cards[i] <= 10^6
Solution
Approach: Hash Table
A shortest run containing a matching pair always starts at one card and ends at the next card with the same value. So scan the cards and store, for each value, the index where it was last seen. When the current card x has been seen before, the run from last[x] to i has i - last[x] + 1 cards, so update the minimum. If no pair was ever found, return -1.
Complexity: O(n) time and O(n) space.
from math import inf
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