ArticlesHash maps
Hash maps
A key stored with a value so set and get are O(1) on average. The pattern is to remember what you have already seen.
A hash map associates a key with a value. On average, set and get are O(1). You spend memory so the next question does not scan the whole input. The pattern in the exercises is simple: remember what you have already seen.
Two Sum is the classic use. A nested loop checks every pair in quadratic time. A map checks, for each number, whether the complement that would reach the target is already stored, and then stores the index you just passed. The answer is positions, so store the index, not only the value.
In TypeScript, a Map keeps a numeric key as a number. A plain object turns that key into a string, which can still work and is easier to get wrong. Prefer Map when the key is not already a string. Then say the cost properly: O(n) time and O(n) extra memory.