TCS · Question 9 · Arrays
Median of Two Sorted Arrays
Problem
Find the median of two sorted arrays.
Approach
Merge both arrays in order, then read the middle element(s). Interview follow-up: the expected optimal solution binary-searches the partition point for O(log(min(n, m))) time and O(1) space — mention it even when you code the merge.
Time O(n+m)Space O(n+m)
How it works
- 1Merge both sorted arrays.
- 2Read the middle (or average the two middles).
Sample input / output
Input: nums1 = [1, 3], nums2 = [2] Output: 2
Constraints
Non-empty arrays; total length >= 1.
Solution — read it, then walk it
Time O(n+m)Space O(n+m)Loops 3Branches 3Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/20
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits