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

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Beautiful Towers II - Monotonic Increasing Stack [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]

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

Sum of Prefix Scores of Strings - Trie [JS]