GeeksforGeeks Medium

Kth Element of Two Sorted Arrays

Kth Element of Two Sorted Arrays is a GFG problem (Medium). You get two arrays a and b, each sorted in ascending order, and a number k. Return the value that would sit at position k (counting from 1) if both arrays were merged into one sorted array.

  • Values can repeat, inside one array and across both.
  • Each array can hold up to 10⁶ values, and the expected time is logarithmic, so you should not build the merged array.
Constraints
  • 1 <= a.size(), b.size() <= 10⁶
  • 0 <= a[i], b[i] <= 10⁸
  • 1 <= k <= a.size() + b.size()
  • Both arrays are sorted ascending; values may repeat
binary-searcharray
Open on GeeksforGeeks ↗
02

Intuition

The k smallest values of the merged array are always a prefix of a plus a prefix of b: some i values from a and the other k - i from b. So the only unknown is one number, i.

A guess for i draws a cut through each array. The guess is right when nothing to the left of either cut is bigger than something to the right of the other cut. Only the four values beside the cuts matter.

If the last value taken from a is too big, taking even more from a only makes it worse, so i must shrink. That one-way rule is what lets you binary search i instead of merging, and the k-th value is the larger of the two values just left of the cuts.

How to spot this pattern

Two sorted inputs and a question about a rank in their union (the k-th value, the median) point to searching a split point rather than a value. Once a guess can be judged too far left or too far right, binary search applies.

03

Approach

Try it first

Before reading on, merge [2,3,6,7,9] and [1,4,8,10] by hand and stop at the 5th value. Then ask: how many of those 5 came from each array, and could you have guessed that count directly?

1

Search the shorter array

If a is longer than b, swap them so a is the shorter one. The binary search runs over how many values to take from a, so this keeps the number of probes at O(log min(n, m)).

2

Limit the range of i

Search i between max(0, k - m) and min(k, n). You cannot take more than n values from a, and j = k - i must not exceed m, the length of b. Every probe in this range is a legal pair of cuts.

3

Read the four values beside the cuts

For a guess i, set j = k - i. Read a[i-1] and a[i], the values on either side of the cut in a, and b[j-1] and b[j] in b. A side with nothing there counts as −∞ on the left and +∞ on the right, so empty prefixes need no special code.

4

Move the cut or stop

If a[i-1] <= b[j] and b[j-1] <= a[i], the cut is right. If a[i-1] > b[j], too much was taken from a, so search lower. Otherwise too little was taken from a, so search higher.

5

Why the answer is the larger left value

With a correct cut, the left sides hold exactly the k smallest values. The largest of them is the k-th, and it must be a[i-1] or b[j-1], because each array is sorted. So return max(a[i-1], b[j-1]).

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def kthElement(self, a, b, k):
▶3 if len(a) > len(b):
▶4 return self.kthElement(b, a, k)
▶5 n, m = len(a), len(b)
▶6 lo, hi = max(0, k - m), min(k, n)
▶7 while lo <= hi:
▶8 i = (lo + hi) // 2
▶9 j = k - i
▶10 a_left = a[i - 1] if i > 0 else float("-inf")
▶11 a_right = a[i] if i < n else float("inf")
▶12 b_left = b[j - 1] if j > 0 else float("-inf")
▶13 b_right = b[j] if j < m else float("inf")
▶14 if a_left <= b_right and b_left <= a_right:
▶15 return max(a_left, b_left)
▶16 if a_left > b_right:
▶17 hi = i - 1
▶18 else:
▶19 lo = i + 1
▶20 return -1
a, shorter14810b23679checks at the cuta left ≤ b rightb left ≤ a rightfirst array is longer → swap them
a[1, 4, 8, 10]searched
b[2, 3, 6, 7, 9]
k5
The first array has more values, so the two swap roles. The search guesses how many of the k smallest values come from a. Doing that on the shorter array keeps the number of guesses small.
a, shorter14810b23679checks at the cuta left ≤ b rightb left ≤ a righttake between 0 and 4 values from a
lo0max(0, k − m)
hi4min(k, n)
From a you can take at most 4 values, and at most k = 5. You must also take at least 0, since b alone could cover all k. Every guess in this range gives two legal cuts.
a, shorter · take 214810b · take 323679checks at the cut4≤7a leftb right6≤8b lefta rightguess: 2 from a, 3 from b
i2middle of 0…4
j3k − i
Try the middle of the range: take 2 from a and 3 from b, 5 in all. Only the four values beside the cuts decide whether this split is right.
a, shorter · take 214810b · take 323679checks at the cut4≤7a leftb rightholds6≤8b lefta rightholdsboth checks hold → answer 6
answer6max(a left, b left)
Nothing on a left side is bigger than anything on a right side, so the left sides hold exactly the 5 smallest values. The largest of them, 6, is the k-th.
05

Common pitfalls

Searching i from 0 to n

✗ Wrong
lo, hi = 0, len(a)
✓ Right
lo, hi = max(0, k - m), min(k, n)

Small guesses for i make j = k - i larger than b. With a = [3], b = [1, 2] and k = 3, the first probe is i = 0, so j = 3 and b[j - 1] reads past the end of b.

Strict comparisons at the cut

✗ Wrong
if a_left < b_right and b_left < a_right:
✓ Right
if a_left <= b_right and b_left <= a_right:

Equal values on both sides of a cut are allowed. With a = [1, 1], b = [1, 1] and k = 2, no cut passes the strict test, the loop runs out, and the function returns -1 instead of 1.

Reading k as a 0-based index

✗ Wrong
return merged[k]
✓ Right
return merged[k - 1]

Position k counts from 1. In the merge version this returns the value one place too far, and for k = n + m it reads past the end.

06

Edge cases

Every value of one array comes first, e.g. a = [1, 2, 3], b = [4, 5, 6], k = 4

The cut takes all of a (i = 3) and one value of b. The right side of a is empty, so it counts as +∞ and the check passes; the answer is 4.

k = 1 or k = n + m

The range for i is still valid at both ends. For k = 1 one side takes nothing and its left value is −∞, so the answer is the smaller first value.

07

Complexity

Time
O(log min(n, m))
Space
O(1)
Each probe halves the range of i, which has at most min(n, m) + 1 values. A probe reads four values and does two comparisons. Only a few numbers are stored, and the swap is a recursive call that happens at most once.
08

Kth Element of Two Sorted Arrays FAQ

How is this related to Median of Two Sorted Arrays?

The median is this problem with k fixed at the middle of the merged length (and the two middle values averaged when the length is even). The same cut search solves both. See Median of Two Sorted Arrays for that version.

Is a two-pointer merge good enough?

It is correct and simple: walk both arrays like the merge step of merge sort and stop after k picks. That costs O(k), up to 2·10⁶ steps here, which usually passes but does not meet the expected logarithmic time.

Why can the answer not be a value right of the cut?

Take a = [2, 3, 6, 7, 9], b = [1, 4, 8, 10], k = 5. The correct cut takes [1, 4] from b and [2, 3, 6] from a. Everything right of the cuts (7, 9, 8, 10) is at least 6, and there are exactly 5 values on the left, so 6, the largest left value, is 5th.