Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close

Design And Implement An LFU Cache Problem

Design And Implement An LFU Cache Problem Statement

Least Frequently Used (LFU) is one of the cache algorithms (also called cache replacement algorithms or policies). When the cache is full and a new element needs to be added, this algorithm evicts/purges the least frequently used element to free up room for adding the new one.

Cache has two operations:

  • put(key, value) does not return anything. It inserts or updates (if one already present) the value for the given key in the cache. If the cache is at capacity and a key-value pair needs to be inserted, the least frequently used key-value gets evicted before adding a new one. If there are multiple LFU keys, the least recently used one of them gets evicted.

  • get(key) returns the value currently associated with the given key in the cache. If there is no value for that key, it returns -1.

Calling any one of these operations for a key increments that key's usage count by one.

Once a key-value pair is evicted from the cache, the key's usage count is reset/forgotten as if it was never in the cache.

Given a capacity and a set of operations to perform on a LFU cache, return results of those operations.

Each operation will be given as either two or three numbers:

  • [0, key, value] means put(key, value), and
  • [1, key] means get(key).

Example

{
"capacity": 2,
"operations": [
[0, 1, 2],
[0, 3, 6],
[1, 1],
[0, 4, 8],
[1, 3],
[1, 4],
[1, 1]
]
}

Output:

[2, -1, 8, 2]

Output contains results of all get operations, in order:

  • 2 was the value in the cache corresponding to key 1 at the time when get(1) was called for the first time,
  • -1 was returned because by the time get(3) was called, the cache did not contain a value for key 3 (it was evicted, as the least frequently used one, while processing put(4, 8)),
  • 8 was the value for key 4, and
  • 2 was the value for key 1.

Notes

  • It is a good idea to implement the cache as a class (or object or struct - depending on the language you use). In function implement_lfu_cache you would then create one instance of that class/object/struct and call its methods/functions to process the operations.
  • Structure of the class may look like this: \`\`\` class LFUCache { LFUCache(int capacity) { // This is a constructor. // Initialize the data structures of the cache. }

    int get(int key) { // ... }

    void put(int key, int value) { // ... } }

Constraints

  • 0 <= cache capacity <= 104
  • 0 <= a key in the cache <= 105
  • 0 <= a value in the cache <= 109
  • 1 <= number of operations <= 105

Code For Design And Implement An Lfu Cache Solution: Optimal

/*
Asymptotic complexity in terms of number of operations \`q\`, complexity of \`get\` operation \`n1\`, complexity of \`put\` operation \`n2\`,
cache capacity \`c\`, key in the cache \`n\`:
* Time: O(q * (n1 + n2)), where O(n1) = O(1) and O(n2) = O(1).
* Auxiliary space: O(n + c).
* Total space: O(n + c).
*/

class LFUCache {
public:
    const static int N = 1e5 + 5;

    int cache_value[N];

    int use_counter[N];

    list<int>::iterator position[N]; // This will store the position of a key in the deque.

    list<int> cache_deque[N]; // This will store all the key in least frequently order for each use_counter value.

    int min_use_count = 1, cache_size = 0;

    int capacity;

    LFUCache(int capacity_) {
        capacity = capacity_;
        memset(cache_value, -1, sizeof(cache_value));
    }

    int get(int key) {
        if (!capacity || cache_value[key] == -1) {
            return -1;
        }

        adjust(key);

        return cache_value[key];
    }

    /* This function will update the use_counter corresponding to the passed \`key\` and will
    also make the necessary updates in \`cache_deque\`.
    */
    void adjust(int key) {
        if (use_counter[key]) {
            cache_deque[use_counter[key]].erase(position[key]);

            if (cache_deque[min_use_count].empty()) {
                min_use_count++;
            }
        }

        use_counter[key]++;

        if (use_counter[key] == 1) {
            min_use_count = 1;
        }

        cache_deque[use_counter[key]].push_back(key);
        position[key] = cache_deque[use_counter[key]].end();
        position[key]--;
    }

    void put(int key, int value) {
        if (capacity == 0) {
            return;
        }

        if (cache_size == capacity && use_counter[key] == 0) {
            // Cache is full and this is a new key.
            invalidate();
        }

        cache_value[key] = value;

        adjust(key);

        if (use_counter[key] == 1) {
            // This key is inserted for the first time.
            cache_size++;
        }
    }

    /*
    This function will purge the Least Frequently Used key from the cache.
    */
    void invalidate() {
        int key = cache_deque[min_use_count].front();

        use_counter[key] = 0;
        cache_value[key] = -1;

        cache_deque[min_use_count].pop_front();

        cache_size--;
    }
};

vector<int> implement_lfu_cache(int capacity, vector<vector<int>> operations) {
    LFUCache lfu(capacity);

    vector<int> result;

    for (auto operation : operations) {
        if (operation[0] == 0) { // put
            int key = operation[1];
            int value = operation[2];
            lfu.put(key, value);
        } else { // get
            int key = operation[1];
            result.push_back(lfu.get(key));
        }
    }

    return result;
}

We hope that these solutions to the 4 sum problem have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.

If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart’s FREE webinar to understand the best way to prepare.

Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.

We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:

‍To learn more, register for the FREE webinar.

Try yourself in the Editor

Note: Input and Output will already be taken care of.

Design And Implement An LFU Cache Problem

Design And Implement An LFU Cache Problem Statement

Least Frequently Used (LFU) is one of the cache algorithms (also called cache replacement algorithms or policies). When the cache is full and a new element needs to be added, this algorithm evicts/purges the least frequently used element to free up room for adding the new one.

Cache has two operations:

  • put(key, value) does not return anything. It inserts or updates (if one already present) the value for the given key in the cache. If the cache is at capacity and a key-value pair needs to be inserted, the least frequently used key-value gets evicted before adding a new one. If there are multiple LFU keys, the least recently used one of them gets evicted.

  • get(key) returns the value currently associated with the given key in the cache. If there is no value for that key, it returns -1.

Calling any one of these operations for a key increments that key's usage count by one.

Once a key-value pair is evicted from the cache, the key's usage count is reset/forgotten as if it was never in the cache.

Given a capacity and a set of operations to perform on a LFU cache, return results of those operations.

Each operation will be given as either two or three numbers:

  • [0, key, value] means put(key, value), and
  • [1, key] means get(key).

Example

{
"capacity": 2,
"operations": [
[0, 1, 2],
[0, 3, 6],
[1, 1],
[0, 4, 8],
[1, 3],
[1, 4],
[1, 1]
]
}

Output:

[2, -1, 8, 2]

Output contains results of all get operations, in order:

  • 2 was the value in the cache corresponding to key 1 at the time when get(1) was called for the first time,
  • -1 was returned because by the time get(3) was called, the cache did not contain a value for key 3 (it was evicted, as the least frequently used one, while processing put(4, 8)),
  • 8 was the value for key 4, and
  • 2 was the value for key 1.

Notes

  • It is a good idea to implement the cache as a class (or object or struct - depending on the language you use). In function implement_lfu_cache you would then create one instance of that class/object/struct and call its methods/functions to process the operations.
  • Structure of the class may look like this: \`\`\` class LFUCache { LFUCache(int capacity) { // This is a constructor. // Initialize the data structures of the cache. }

    int get(int key) { // ... }

    void put(int key, int value) { // ... } }

Constraints

  • 0 <= cache capacity <= 104
  • 0 <= a key in the cache <= 105
  • 0 <= a value in the cache <= 109
  • 1 <= number of operations <= 105

Code For Design And Implement An Lfu Cache Solution: Optimal

/*
Asymptotic complexity in terms of number of operations \`q\`, complexity of \`get\` operation \`n1\`, complexity of \`put\` operation \`n2\`,
cache capacity \`c\`, key in the cache \`n\`:
* Time: O(q * (n1 + n2)), where O(n1) = O(1) and O(n2) = O(1).
* Auxiliary space: O(n + c).
* Total space: O(n + c).
*/

class LFUCache {
public:
    const static int N = 1e5 + 5;

    int cache_value[N];

    int use_counter[N];

    list<int>::iterator position[N]; // This will store the position of a key in the deque.

    list<int> cache_deque[N]; // This will store all the key in least frequently order for each use_counter value.

    int min_use_count = 1, cache_size = 0;

    int capacity;

    LFUCache(int capacity_) {
        capacity = capacity_;
        memset(cache_value, -1, sizeof(cache_value));
    }

    int get(int key) {
        if (!capacity || cache_value[key] == -1) {
            return -1;
        }

        adjust(key);

        return cache_value[key];
    }

    /* This function will update the use_counter corresponding to the passed \`key\` and will
    also make the necessary updates in \`cache_deque\`.
    */
    void adjust(int key) {
        if (use_counter[key]) {
            cache_deque[use_counter[key]].erase(position[key]);

            if (cache_deque[min_use_count].empty()) {
                min_use_count++;
            }
        }

        use_counter[key]++;

        if (use_counter[key] == 1) {
            min_use_count = 1;
        }

        cache_deque[use_counter[key]].push_back(key);
        position[key] = cache_deque[use_counter[key]].end();
        position[key]--;
    }

    void put(int key, int value) {
        if (capacity == 0) {
            return;
        }

        if (cache_size == capacity && use_counter[key] == 0) {
            // Cache is full and this is a new key.
            invalidate();
        }

        cache_value[key] = value;

        adjust(key);

        if (use_counter[key] == 1) {
            // This key is inserted for the first time.
            cache_size++;
        }
    }

    /*
    This function will purge the Least Frequently Used key from the cache.
    */
    void invalidate() {
        int key = cache_deque[min_use_count].front();

        use_counter[key] = 0;
        cache_value[key] = -1;

        cache_deque[min_use_count].pop_front();

        cache_size--;
    }
};

vector<int> implement_lfu_cache(int capacity, vector<vector<int>> operations) {
    LFUCache lfu(capacity);

    vector<int> result;

    for (auto operation : operations) {
        if (operation[0] == 0) { // put
            int key = operation[1];
            int value = operation[2];
            lfu.put(key, value);
        } else { // get
            int key = operation[1];
            result.push_back(lfu.get(key));
        }
    }

    return result;
}

We hope that these solutions to the 4 sum problem have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.

If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart’s FREE webinar to understand the best way to prepare.

Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.

We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:

‍To learn more, register for the FREE webinar.

Worried About Failing Tech Interviews?

Attend our free webinar to amp up your career and get the salary you deserve.

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Accelerate your Interview prep with Tier-1 tech instructors
blue tick
360° courses that have helped 14,000+ tech professionals
blue tick
100% money-back guarantee*
Register for Webinar

Recommended Posts

All Posts