Solution using the in-built java LinkedHashMap usage for cache

  • 0

    I thought as it is not possible to complete all the code in such a limited time, using our own approach. I know the interviewer is expecting not use to library function and use our own logic. This implementation solves the problem.

    public class LFUCache{

    private int capacity;
    public LFUCache(int i) {
    LinkedHashMap hmap = new LinkedHashMap<Integer,Integer>(capacity+1,1.1f,true) {
    	public boolean removeEldestEntry(Map.Entry eldest) {
    		return size() > capacity;
    public int get(int key) {
    		return -1;
    	return (int) hmap.get(key);
    public void set(int key, int value) {
    	hmap.put(key, value);



    • Your LFUCache object will be instantiated and called as such:
    • LFUCache obj = new LFUCache(capacity);
    • int param_1 = obj.get(key);
    • obj.set(key,value);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.