← TCS bank

TCS · Question 9 · Arrays

Median of Two Sorted Arrays

ArraysC++code⏱ O(n+m)💾 O(n+m)
Service-based

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

  1. 1Merge both sorted arrays.
  2. 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.
↻ repeatSTARTinclude <iostream>include <vector>using namespace stdDEFINEfindMedianSortedArrays(vector<int>&a, vector<int>& b)vector<int> mergedsize_t i = 0, j = 0while (i < a.size() &&j < b.size())if (a[i] < b[j])merged.push_back(a[i++])ELSEwhile (i < a.size())merged.push_back(a[i++])while (j < b.size())merged.push_back(b[j++])size_t n = merged.size()if (n % 2 == 1) returnmerged[n / 2]RETURN (merged[n / 2 - 1] +merged[n / 2]) / 2.0DEFINE main()vector<int> a = {1, 3}vector<int> b = {2}cout <<findMedianSortedArrays(a,b) << endlRETURN 0END
  • 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