Minimum Consecutive Cards to Pick Up - Hashmap [JS]

Description 

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

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]