Free beta: free to use with daily limits while we build. Join the waitlist for founding-member pricing at launch. Join the waitlist

Sign up free

Affirm interview question

Design a dictionary with constant-time get, put and random value selection

Company:
Affirm
Round:
Onsite
Type:
Coding
Difficulty:
Medium
Reported:
October 19, 2026

Problem

Implement a dictionary class that maps keys to values and supports the following operations, each in average O(1) time:

  • put(key, value): insert the key with the value, or replace the value if the key is already present.
  • get(key): return the value stored for the key.
  • random_value(): return the value of a stored key chosen uniformly at random, so every key currently in the dictionary is equally likely. A value stored under two keys is therefore returned twice as often as a value stored under one key.

How get reports a missing key and what random_value does on an empty dictionary are not specified; any consistent choice, such as returning None or raising an error, is accepted.

Example 1

Input: put("a", 1); put("b", 2); get("a"); put("a", 5); get("a"); get("b")
Output: 1, 5, 2

The second put on "a" replaces its value, and "b" keeps its own.

Example 2

Input: put("x", 7); put("y", 9); random_value()
Output: 7 or 9, each with probability 1/2

Two keys are stored, so each of their values is returned half of the time.

Constraints

  • Keys are hashable; values can be any object.
  • put, get and random_value must each run in average O(1) time, independent of the number of stored keys.
  • random_value must not scan or copy the stored keys.

Reported by candidates or drawn from publicly available sources, and rewritten in our own words. Pathwise Prep does not publish confidential assessment content. Report a concern