I recently had an interview where the interviewer asked me to create a HashMap
that has a maximum of 7 key/value pairs. If an 8th key/value pair is added, the first key/value pair should be removed and the eighth inserted to replace it, etc.
What's a good strategy for solving this problem?
Make a data structure using LinkedHashMap and override removeEldestEntry i.e. something like this:
import java.util.LinkedHashMap;
class CustomHashMap extends LinkedHashMap<Integer, Integer> {
private int capacity;
public CustomHashMap(int capacity) {
super(capacity, 0.75F, true);
this.capacity = capacity;
}
public int get(int key) {
return super.getOrDefault(key, -1);
}
public void put(int key, int value) {
super.put(key, value);
}
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
}
Alternatively, if you are not allowed to use standard libraries or you are using a language that does not have an ordered dictionary structure like Java/Python you can use a Hashtable
+ and a DoubleEndedLinkedList
that you can define yourself and achieve the same thing or use a Deque
:
- Time complexity:
O(1)
for both put and get. - Space complexity:
O(capacity)
.
Although you have to write a lot more code.
Generic version as per @Holger's request:
import java.util.LinkedHashMap;
import java.util.Map;
class CustomHashMap<K, V> extends LinkedHashMap<K, V> {
private int capacity;
public CustomHashMap(int capacity) {
super(capacity, 0.75F, true);
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
}
Example Usage:
class Main {
public static void main(String[] args) {
CustomHashMap map = new CustomHashMap(3);
map.put(1, null);
map.put(2, null);
map.put(3, null);
map.put(4, null);
System.out.println(map.keySet());
}
}
Output:
[2, 3, 4]