N-Way Set Associative Cache
MediumCaching · TheTradeDesk
A set associative cache is split into sets independent sets, and each set can hold at most ways keys. Every key is assigned to exactly one set, and it can only ever be stored in that set.
To find a key's set, compute this hash over its characters and take h % sets:
text
h = 0
for each character ch in key:
h = (h * 31 + ord(ch)) % 1000000007
set_index = h % setsProcess accesses in order. For each key:
- If the key is already in its set, the access is a hit, and the key becomes the most recently used key of that set.
- Otherwise it is a miss. If the set already holds
wayskeys, first evict the least recently used key of that set (other sets are never affected). Then store the key as the most recently used.
Return a list with one boolean per access: True for a hit, False for a miss.
Example 1
- Input:
- sets = 2, ways = 2, accesses = ["a", "c", "a", "e", "c", "b"]
- Output:
- [False, False, True, False, False, False]
- Explanation
"a"(97),"c"(99) and"e"(101) all hash to set 1, while"b"(98) goes to set 0. The second"a"hits and becomes most recent, so when"e"arrives the full set evicts"c"; the next"c"then misses and evicts"a"."b"misses in the empty set 0.
Example 2
- Input:
- sets = 1, ways = 3, accesses = ["x", "y", "x", "z", "w", "x", "y"]
- Output:
- [False, False, True, False, False, True, False]
- Explanation
- With one set this is a plain LRU cache of size 3. The repeat of
"x"hits;"w"evicts"y"(the least recently used), so the later"x"hits and"y"misses.
Example 3
- Input:
- sets = 4, ways = 1, accesses = ["ab", "af", "ab", "af"]
- Output:
- [False, False, False, False]
- Explanation
"ab"hashes to 97 * 31 + 98 = 3105 and"af"to 3109, and both are 1 modulo 4. With only one way per set they keep evicting each other, so every access misses.
Constraints
1 <= sets <= 10001 <= ways <= 10000 <= accesses.length <= 10^51 <= accesses[i].length <= 20; keys are ASCII letters and digits and are case-sensitive