As reported: ServiceNow Senior Software Engineer (IC3) loop, round 2 (DSA), Nov 2026, with follow-ups on concurrency and locking. Also asked in round 1 of a ServiceNow Software Engineer (IC2) loop (Oct 2026) as design and implementation.
Implement LRUCache:
LRUCache(capacity)— a cache holding at mostcapacitykeys.get(key)— the value forkey, or-1if absent. A successfulgetmakes the key the most recently used.put(key, value)— insert or update the key, making it the most recently used. If the cache then holds more thancapacitykeys, evict the least recently used one.
Both operations must run in O(1) average time.
This is LeetCode 146 — LRU Cache.
Example
LRUCache(2); put(1,1); put(2,2); get(1) -> 1; put(3,3) (evicts 2); get(2) -> -1;
put(4,4) (evicts 1); get(1) -> -1; get(3) -> 3; get(4) -> 4
Constraints: 1 ≤ capacity ≤ 3000; 0 ≤ key ≤ 10^4; 0 ≤ value ≤ 10^5; at most 2 · 10^5 calls.
Code runner format: line 1 the operation names, line 2 their arguments (LeetCode's design format). The harness prints the list of return values (null for the constructor and put).
Follow-ups
- Make the cache safe to use from many threads. Which locks do you take, and where?