2260. Minimum Consecutive Cards to Pick Up
Description
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
Solutions
Solution 1: Hash Table
We initialize the answer as \(+\infty\). We traverse the array, and for each number \(x\), if \(\textit{last}[x]\) exists, it means \(x\) has a matching pair of cards. In this case, we update the answer to \(\textit{ans} = \min(\textit{ans}, i - \textit{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.
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
|