Skip to the editor
JSGroundwork
JSGroundwork handwritten · web dev
←Back to Binary search

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›Binary search

Find the Duplicate Number

advancedlayer B6 · Binary search5 tests

An array nums holds n + 1 integers, every one of them in the range 1 .. n. By the pigeonhole principle at least one value repeats; you are told exactly one value is duplicated, though it may appear many times. Return that value.

  • You must not modify the array — no sorting, no marking entries negative
  • You may use only O(1) extra space — no Set, no frequency array
  • Read i -> nums[i] as a linked list: since every value is in 1 .. n, no jump ever leaves the array, and the duplicate creates a cycle whose entrance is the answer
  • Floyd's tortoise-and-hare finds that entrance in O(n) time and O(1) space

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