← Home

706. Design HashMap

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
data structure designC++Markdown
706

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 706. Design HashMap, the solution in this repository is mainly a data structure design solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: data structure design.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are put, get, remove.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02Design a HashMap without using any built-in hash table libraries.
03
04To be specific, your design should include these functions:
05
06put(key, value) : Insert a (key, value) pair into the HashMap. If the value already exists in the HashMap, update the value.
07get(key): Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
08remove(key) : Remove the mapping for the value key if this map contains the mapping for the key.
09
10Example:
11
12MyHashMap hashMap = new MyHashMap();
13hashMap.put(1, 1);          
14hashMap.put(2, 2);         
15hashMap.get(1);            // returns 1
16hashMap.get(3);            // returns -1 (not found)
17hashMap.put(2, 1);          // update the existing value
18hashMap.get(2);            // returns 1 
19hashMap.remove(2);          // remove the mapping for 2
20hashMap.get(2);            // returns -1 (not found) 
21
22Note:
23
24All keys and values will be in the range of [0, 1000000].
25The number of operations will be in the range of [1, 10000].
26Please do not use the built-in HashMap library.
27**/
28
29//Runtime: 216 ms, faster than 23.40% of C++ online submissions for Design HashMap.
30//Memory Usage: 41.2 MB, less than 96.95% of C++ online submissions for Design HashMap.
31
32class MyHashMap {
33public:
34    vector<int> keys;
35    vector<int> values;
36    
37    /** Initialize your data structure here. */
38    MyHashMap() {
39    }
40    
41    /** value will always be non-negative. */
42    void put(int key, int value) {
43        vector<int>::iterator it = find(keys.begin(), keys.end(), key);
44        if(it!=keys.end()){
45            values[(it - keys.begin())] = value;
46        }else{
47            keys.push_back(key);
48            values.push_back(value);
49        }
50        
51    }
52    
53    /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
54    int get(int key) {
55        vector<int>::iterator it = find(keys.begin(), keys.end(), key);
56        if(it==keys.end()){
57            return -1;
58        }else{
59            return values[it-keys.begin()];
60        }
61    }
62    
63    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
64    void remove(int key) {
65        vector<int>::iterator it = find(keys.begin(), keys.end(), key);
66        if(it!=keys.end()){
67            keys.erase(it);
68            values.erase(values.begin() + (it - keys.begin()));
69        }
70    }
71};
72
73/**
74 * Your MyHashMap object will be instantiated and called as such:
75 * MyHashMap obj = new MyHashMap();
76 * obj.put(key,value);
77 * int param_2 = obj.get(key);
78 * obj.remove(key);
79 */

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.