Skip to the editor
JSGroundwork
JSGroundwork handwritten · web dev
←Back to Design problems

Ready to read

JSJavaScript⑂Git◎Interview prepΣDSA in JSSDSystem Design
More topics15›
</>HTML{ }CSS⚛ReactNNext.jsNeNest.jsTSTypeScriptNoNode.js🐳DockerDBSQL & Databases✓Testing🔒Web Security☁Cloud & DevOps◈GraphQL◆Redis☸Kubernetes
☰‹›
Description
All topics›JavaScript›Design problems

Insert Delete GetRandom O(1)

advancedlayer A9 · Design problems5 tests

Design a set supporting insert, remove and 'give me a uniformly chosen member', all in average O(1).

  • insert(value) — returns true if the value was not already there, otherwise false and nothing changes
  • remove(value) — returns true if the value was there, otherwise false
  • getRandom() — returns one of the current members
  • Testability: the constructor takes an optional pick function (n) => index that chooses an index in 0..n-1. When it is omitted, default to a uniform random choice
  • You may not scan the collection in remove or getRandom

Stuck?

All exercisesPlayground
1234567891011121314
loading the editor…

Nothing yet — hit Run and whatever you log shows up here.

Submit to see how you did.

⌘/Ctrl + Enter run⌘/Ctrl + S save⌘/Ctrl + / comment⌘/Ctrl + F find/replace⌘/Ctrl + D select next matchAlt + click multi-cursorTab indent · ⇧Tab outdentEsc leave fullscreen