- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 43 lines of Java from the credited upstream file 381.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class RandomizedCollection {2 public boolean insert(int val) {3 valToIndices.putIfAbsent(val, new ArrayList<>());4 valToIndices.get(val).add(items.size());5 items.add(new Item(val, valToIndices.get(val).size() - 1));6 return valToIndices.get(val).size() == 1;7 }8 9 public boolean remove(int val) {10 if (!valToIndices.containsKey(val))11 return false;12 13 final int index = lastIndex(valToIndices.get(val));14 valToIndices.get(last(items).val).set(last(items).indexInMap, index);15 final int indicesSize = valToIndices.get(val).size();16 valToIndices.get(val).remove(indicesSize - 1);17 if (valToIndices.get(val).isEmpty())18 valToIndices.remove(val);19 items.set(index, last(items));20 items.remove(items.size() - 1);21 return true;22 }23 24 public int getRandom() {25 final int index = rand.nextInt(items.size());26 return items.get(index).val;27 }28 29 private record Item(int val, int indexInMap) {}30 31 private Map<Integer, List<Integer>> valToIndices = new HashMap<>();32 private List<Item> items = new ArrayList<>();33 private Random rand = new Random();34 35 private int lastIndex(List<Integer> indices) {36 return indices.get(indices.size() - 1);37 }38 39 private Item last(List<Item> items) {40 return items.get(items.size() - 1);41 }42}43