Working through data structure and algorithm problems it’s important to come up with solutions that are efficient and continue to work efficiently even as the data set gets larger. This means having a good Big O time complexity, and for certain problems sets one way to do this is with Hash Maps.

A hash map stores key-value pairs in JavaScript a hash map can be a Javascript object or JavaScript’s built-in Map object. Other languages have their own versions of this too, for example in Python it’s a dictionary or in Ruby, it’s a hash, the main idea is the same though using key-value pairs. So, how can this help improve our Big O? For most cases, search, insertion, and deletion of a hash map are Big O(1) constant time (which is the best possible runtime). It also must be said while not common worst case for a hash map is Big O(n) linear time (which isn’t terrible).

Where to use a hash map? While working through coding algorithms if you notice that in the problem there is to store key-value pairs that you can pull from or search through to help come up with an answer. Then maybe it is worth trying to utilize a hash map. To use a practical example, the first question on Leetcode.com is ‘Two Sum’ the problem gives you an array of integers and a target integer. From this array, by adding two of the integers we can need the target number and return the index of the two numbers and each input only has one solution.

#big-o #algorithms #javascript

Hash Maps to Improve Time Complexity
1.35 GEEK