Medium
LABMinimum Consecutive Cards to Pick Up
Return the length of the shortest contiguous subarray containing a repeated card value, or -1 if none exists.
EXAMPLES
Example 1
Input
{
"cards": [
3,
4,
2,
3,
4,
7
]
}
Output
4FUNCTION SHAPE
cards: intArray→intSOLUTION NOTE
Straightforward min template. We are valid once we have a repeating card (freq == 2).
Reveal reference solution +
pythonREFERENCE
def minimumCardPickup(self, cards: List[int]) -> int:
n, l, freq, res = len(cards), 0, Counter(), float('inf')
for r in range(n):
freq[cards[r]] += 1
while freq[cards[r]] == 2:
res = min(res, r - l + 1)
freq[cards[l]] -= 1
l += 1
return res if res != float('inf') else -1Time
O(n)Space
O(n)