Minimum Consecutive Cards to Pick Up - Hashmap [JS]
- Get link
- X
- Other Apps
By
Anna An
on
Solution: Hashmap
Use a hashmap to keep track of the last occurance of each card.
Find the minimum gap between two equal cards by comparing the current index with the last index.
Time Complexity: O(n)
355ms
Space Complexity:O(n)
76.3MB
var minimumCardPickup = function(cards) {
// get smallest distance between two equal cards
let lastIndex = {}, ans = Infinity;
for (let i = 0; i < cards.length; i++) {
if (lastIndex[cards[i]] !== undefined) {
ans = Math.min(ans, i - lastIndex[cards[i]] + 1);
}
lastIndex[cards[i]] = i;
}
return ans === Infinity ? -1 : ans;
};
javascript
- Get link
- X
- Other Apps
Comments
Post a Comment