00:00

Problem Statement

Input/Output Examples

Visual Explanation

Tracking the lowest non-empty count in a variable means eviction never has to search for it.

Approaches

Both approaches give identical results on 5,000 random test runs. The first does every operation in constant time; the second is shorter but logarithmic.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

The bucket version does a constant number of map and set operations per call. The tree version pays O(log n) to reorder an entry on each use.

Interview Tips and Recommended Approach

  • Clarify the tie rule before coding; most versions evict the least recently used among the least frequent.
  • Reset the minimum to 1 on every new key; that is the step candidates most often miss.
  • Handle capacity 0; a put must not try to evict from an empty cache.
  • Compare with LRU: LFU resists one-off scans but can keep keys that were popular long ago.

Recommended Approach: Frequency Buckets

Why: it meets the usual O(1) requirement, and each map has one clear job, which makes the code easy to explain line by line.