LeetCode 2260: Minimum Consecutive Cards to Pick Up
Problem Description
Explanation:
To solve this problem, we can use a sliding window approach. We iterate through the array and keep track of the frequencies of each card value we encounter. As we move the window, we update the frequencies accordingly. If we encounter a card value that already has a frequency greater than 1, it means we have found a matching pair and can calculate the minimum number of cards picked up.
Algorithm:
- Initialize a HashMap to store the frequency of each card value.
- Initialize variables to keep track of the start and end of the window, as well as the minimum number of cards picked up.
- Iterate through the array using a sliding window approach.
- Update the frequency of the current card value in the HashMap.
- If the frequency becomes greater than 1, update the minimum number of cards picked up.
- Move the window by incrementing the start index.
- Return the minimum number of cards picked up if a matching pair is found, otherwise return -1.
Time Complexity:
The time complexity of this solution is O(n) where n is the number of cards in the input array.
Space Complexity:
The space complexity is O(n) to store the frequency of each card value in the HashMap.
:
Solutions
class Solution {
public int minCards(int[] cards) {
Map<Integer, Integer> freqMap = new HashMap<>();
int minCards = Integer.MAX_VALUE;
int start = 0;
for (int end = 0; end < cards.length; end++) {
freqMap.put(cards[end], freqMap.getOrDefault(cards[end], 0) + 1);
while (freqMap.get(cards[end]) > 1) {
minCards = Math.min(minCards, end - start + 1);
freqMap.put(cards[start], freqMap.get(cards[start]) - 1);
start++;
}
}
return minCards == Integer.MAX_VALUE ? -1 : minCards;
}
}
Loading editor...