Algorithm
nth largest number
arrays
data structures
programming

An algorithm to find the nth largest number in two arrays of size n

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

Finding the nth largest number in two sorted arrays, each of size n, is a classic problem that blends binary search with the divide-and-conquer rule. In this article, we delve into a step-by-step approach to solving this problem efficiently. We'll provide both technical explanations and an illustrative example to capture its essence.

Problem Definition

Suppose you have two sorted arrays, A and B , each of size n . The objective is to determine the nth largest element in the union of these two arrays using an efficient algorithm with a time complexity less than the brute force method.

Brute Force Approach

A trivial approach would be to merge both arrays into a single array, sort it, and then directly retrieve the nth largest number. However, this involves a time complexity of O(nlog⁡n)O(n \log n) due to the sorting, which can be inefficient for larger datasets.

Optimized Algorithm

Our optimal approach leverages binary search principles to achieve a logarithmic time complexity, O(log⁡n)O(\log n) . The key is to eliminate half of the search space at each step, similar to techniques used in finding the median of two sorted arrays.

Approach Details

  1. Define Search on A: Initially, focus the search on array A . For each potential position i (representing the nth largest in A ), define j as n - i in B . This helps ensure that we potentially get the nth largest across both arrays.
  2. Binary Search: Use binary search to optimize the index i in A :
    • Calculate j as n - i .
    • Check the conditions necessary for i and j :
      • If A[i-1] is greater than B[j] , it indicates that i is too large, and you need to reduce it, shifting the binary search's right boundary.
      • If B[j-1] is greater than A[i] , it suggests that i is too small, and you need to increase it, shifting the binary search's left boundary.
    • Once the optimal i is found, compute the desired nth largest from the possible candidates.
  3. Boundary Cases:
    • If i equals 0 , consider the nth largest entirely within B .
    • If j equals 0 , concentrate on A .
  4. Calculating the nth Largest: Once the optimal i and j are confirmed:
    • The nth largest element is the maximum of the elements at A[i-1] and B[j-1] .

Example

Consider arrays A = [1, 3, 5, 7] and B = [2, 4, 6, 8] . Let's find the 3rd largest element in the union of A and B .

Step-by-Step Execution:

  1. Start with binary search on A :
    • Define initial boundaries: low = 0, high = 4.
  2. Binary search iteration:
    • Midpoint calculation: i = (0 + 4) / 2 = 2 , thus j = 4 - 2 = 2 .
    • Compare: Check A[1] (3) with B[2] (6) , and B[1] (4) with A[2] (5) .
    • Since A[1] < B[2] and B[1] < A[2] , these indices give valid boundary conditions.
  3. Calculate the nth largest:
    • Max of A[1] and B[1] yields max(3, 4) = 4 .

Therefore, the 3rd largest element in the union of A and B is 4 .

Summary Table

StepDetails
InitializeStart binary search on A
. Define low and high indices for boundary control.
IterateAdjust boundaries based on comparisons between elements of A
and B
.
Boundary ChecksEnsure proper lower and upper boundaries. Handle cases where i = 0
or j = 0
.
Final DecisionDetermine the nth largest using the maximum of generative elements at derived indices.

Complexity Analysis

The algorithm primarily employs binary search, maintaining a complexity of O(\log n) , thanks to its sub-linear property, making it significantly more efficient for larger data sets than the naive approach. This solution effectively handles input sizes or constraints, which are otherwise cumbersome with quadratic or even linear complexities.

Conclusion

Finding the nth largest number in two sorted arrays is a quintessential algorithmic challenge that showcases the practical application of the divide-and-conquer approach. By leveraging binary search principles, we transform a seemingly complex problem into an elegant and efficient solution, adaptable to a wide range of input sizes and conditions.


Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms