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

Median of Two Sorted Arrays

advancedlayer B6 · Binary search5 tests

Given two arrays a and b, each already sorted ascending, return the median of all their values combined. With an odd total count the median is the middle value; with an even total count it is the average of the two middle values.

  • Either array may be empty (but not both)
  • Merging is O(m + n); the target here is O(log(min(m, n)))
  • Binary search a partition point in the shorter array: cut both arrays so the left halves together hold exactly half the elements and every left value is at most every right value
  • Use -Infinity and Infinity for the missing neighbours when a cut lands at an array's edge

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