Open In App

K-th Element of Two Sorted Arrays

Improve
Improve
Like Article
Like
Save
Share
Report

Given two sorted arrays of size m and n respectively, you are tasked with finding the element that would be at the k’th position of the final sorted array.

Examples: 

Input : Array 1 - 2 3 6 7 9
        Array 2 - 1 4 8 10
        k = 5
Output : 6
Explanation: The final sorted array would be -
1, 2, 3, 4, 6, 7, 8, 9, 10
The 5th element of this array is 6.
Input : Array 1 - 100 112 256 349 770
        Array 2 - 72 86 113 119 265 445 892
        k = 7
Output : 256
Explanation: Final sorted array is -
72, 86, 100, 112, 113, 119, 256, 265, 349, 445, 770, 892
7th element of this array is 256.

Basic Approach 
Since we are given two sorted arrays, we can use the merging technique to get the final merged array. From this, we simply go to the k’th index. 

C++

#include <iostream>
using namespace std;

int kth(int arr1[], int arr2[], int n, int m, int k)
{
    // array to store the merged sorted array
    int sorted1[m + n];
    int i = 0, j = 0, d = 0;
    while (i < n && j < m) {
        // If the element of arr1 is smaller, insert the
        // element to the sorted array
        if (arr1[i] < arr2[j])
            sorted1[d++] = arr1[i++];
        else
            // If the element of arr2 is smaller, insert the
            // element to the sorted array
            sorted1[d++] = arr2[j++];
    }
    // Push the remaining elements of arr1
    while (i < n)
        sorted1[d++] = arr1[i++];
    // Push the remaining elements of arr2
    while (j < m)
        sorted1[d++] = arr2[j++];
    // Return the element at kth position in the merged
    // sorted array
    return sorted1[k - 1];
}

// Driver Code
int main()
{
    int arr1[5] = { 2, 3, 6, 7, 9 };
    int arr2[4] = { 1, 4, 8, 10 };
    int k = 5;
    cout << kth(arr1, arr2, 5, 4, k);
    return 0;
}

Java

class Main {
    static int kth(int arr1[], int arr2[], int n, int m,
                   int k)
    {
        // array to store the merged sorted array
        int[] sorted1 = new int[m + n];
        int i = 0, j = 0, d = 0;
        while (i < n && j < m) {
            // If the element of arr1 is smaller, insert the
            // element to the sorted array
            if (arr1[i] < arr2[j])
                sorted1[d++] = arr1[i++];
            else
                // If the element of arr2 is smaller, insert
                // the element to the sorted array
                sorted1[d++] = arr2[j++];
        }
        // Push the remaining elements of arr1
        while (i < n)
            sorted1[d++] = arr1[i++];
        // Push the remaining elements of arr2
        while (j < m)
            sorted1[d++] = arr2[j++];
        // Return the element at kth position in the merged
        // sorted array
        return sorted1[k - 1];
    }

    // Driver Code
    public static void main(String[] args)
    {
        int arr1[] = { 2, 3, 6, 7, 9 };
        int arr2[] = { 1, 4, 8, 10 };
        int k = 5;
        System.out.print(kth(arr1, arr2, 5, 4, k));
    }
}

/* This code is contributed by Harsh Agarwal */

C#

// C# Program to find kth element
// from two sorted arrays
class GFG {
    static int kth(int[] arr1, int[] arr2, int n, int m,
                   int k)
    {
        // array to store the merged sorted array
        int[] sorted1 = new int[m + n];
        int i = 0, j = 0, d = 0;
        while (i < n && j < m) {
            // If the element of arr1 is smaller, insert the
            // element to the sorted array
            if (arr1[i] < arr2[j])
                sorted1[d++] = arr1[i++];
            else
                // If the element of arr2 is smaller, insert
                // the element to the sorted array
                sorted1[d++] = arr2[j++];
        }
        // Push the remaining elements of arr1
        while (i < n)
            sorted1[d++] = arr1[i++];
        // Push the remaining elements of arr2
        while (j < m)
            sorted1[d++] = arr2[j++];
        // Return the element at kth position in the merged
        // sorted array
        return sorted1[k - 1];
    }

    // Driver Code
    static void Main()
    {
        int[] arr1 = { 2, 3, 6, 7, 9 };
        int[] arr2 = { 1, 4, 8, 10 };
        int k = 5;
        System.Console.WriteLine(kth(arr1, arr2, 5, 4, k));
    }
}

// This code is contributed by mits

Javascript

// JavaScript Program to find kth element 
// from two sorted arrays

    function kth(arr1 , arr2 , n , m , k) {
        // array to store the merged sorted array
        var sorted1 = Array(m + n).fill(0);
        var i = 0, j = 0, d = 0;
        while (i < n && j < m) {
            // If the element of arr1 is smaller, insert the element to the sorted array
            if (arr1[i] < arr2[j])
                sorted1[d++] = arr1[i++];
            else
            // If the element of arr2 is smaller, insert the element to the sorted array
                sorted1[d++] = arr2[j++];
        }
        // Push the remaining elements of arr1
        while (i < n)
            sorted1[d++] = arr1[i++];
        // Push the remaining elements of arr2
        while (j < m)
            sorted1[d++] = arr2[j++];
        // Return the element at kth position in the merged sorted array
        return sorted1[k - 1];
    }
    
var arr1 = [ 2, 3, 6, 7, 9 ];
var arr2 = [ 1, 4, 8, 10 ];
var k = 5;
console.log(kth(arr1, arr2, 5, 4, k));

PHP


<?php 

function kth($arr1, $arr2,
             $m, $n, $k)
{
      // array to store the merged sorted array
    $sorted1[$m + $n] = 0;
    $i = 0;
    $j = 0;
    $d = 0;
    while ($i < $m && $j < $n)
    {
          // If the element of arr1 is smaller, insert the element to the sorted array
        if ($arr1[$i] < $arr2[$j])
            $sorted1[$d++] = $arr1[$i++];
        else
        // If the element of arr2 is smaller, insert the element to the sorted array
            $sorted1[$d++] = $arr2[$j++];
    }
      // Push the remaining elements of arr1
    while ($i < $m)
        $sorted1[$d++] = $arr1[$i++];
      // Push the remaining elements of arr2
    while ($j < $n)
        $sorted1[$d++] = $arr2[$j++];
      // Return the element at kth position in the merged sorted array
    return $sorted1[$k - 1];
}

// Driver Code
$arr1 = array(2, 3, 6, 7, 9);
$arr2 = array(1, 4, 8, 10);
$k = 5;
echo kth($arr1, $arr2, 5, 4, $k);
?>

Python3

def kth(arr1, arr2, n, m, k):
    # array to store the merged sorted array
    sorted1 = [0] * (m + n)
    i = 0
    j = 0
    d = 0
    while (i < n and j < m):
        # If the element of arr1 is smaller, insert the element to the sorted array
        if (arr1[i] < arr2[j]):
            sorted1[d] = arr1[i]
            i += 1
        else:
            # If the element of arr2 is smaller, insert the element to the sorted array
            sorted1[d] = arr2[j]
            j += 1
        d += 1
    # Push the remaining elements of arr1
    while (i < n):
        sorted1[d] = arr1[i]
        d += 1
        i += 1
    # Push the remaining elements of arr2
    while (j < m):
        sorted1[d] = arr2[j]
        d += 1
        j += 1
    # Return the element at kth position in the merged sorted array
    return sorted1[k - 1]


# Driver code
arr1 = [2, 3, 6, 7, 9]
arr2 = [1, 4, 8, 10]
k = 5
print(kth(arr1, arr2, 5, 4, k))
Output

6

Time Complexity: O(n) 
Auxiliary Space : O(m + n) 

Space Optimized Version of above approach: We can avoid the use of extra array.

C++


// C++ program to find kth element 
// from two sorted arrays
#include <bits/stdc++.h>
using namespace std;

int find(int arr1[], int arr2[], int m, 
         int n, int k) 
{
    int d = 0, i = 0, j = 0;

    // Keep taking smaller of the current
    // elements of two sorted arrays and
    // keep incrementing k
    while(i < m && j < n)
    {
        if(A[i] < B[j]) 
        {
            d++;
            if(d == k)
                return A[i];
            i++;
        } 
        else
        {
            d++;
            if(d == k)
                return B[j];
            j++;
        }
    }

    // If array B[] is completely traversed
    while(i < m) 
    {
        k++;
        if(d == k)
            return A[i];
        i++;
    }

    // If array A[] is completely traversed
    while(j < n) 
    {
        d++;
        if(d == k)
            return B[j];
        j++;
    }
} 

// Driver Code
int main()
{
    int A[5] = { 2, 3, 6, 7, 9 };
    int B[4] = { 1, 4, 8, 10 };
    int k = 5;
    
    cout << find(A, B, 5, 4, k);
    
    return 0;
} 

// This code is contributed by Sreejith S 

Java

import java.io.*;

class GFG {
    public static int find(int A[], int B[], int m, int n,
                           int k_req)
    {
        int k = 0, i = 0, j = 0;

        // Keep taking smaller of the current
        // elements of two sorted arrays and
        // keep incrementing k
        while (i < m && j < n) {
            if (A[i] < B[j]) {
                k++;
                if (k == k_req)
                    return A[i];
                i++;
            }
            else {
                k++;
                if (k == k_req)
                    return B[j];
                j++;
            }
        }

        // If array B[] is completely traversed
        while (i < m) {
            k++;
            if (k == k_req)
                return A[i];
            i++;
        }

        // If array A[] is completely traversed
        while (j < n) {
            k++;
            if (k == k_req)
                return B[j];
            j++;
        }
        return -1;
    }

    // Driver Code
    public static void main(String[] args)
    {
        int[] A = { 2, 3, 6, 7, 9 };
        int[] B = { 1, 4, 8, 10 };
        int k = 5;

        System.out.println(find(A, B, 5, 4, k));
    }
}

C#

// C# program to find kth element 
// from two sorted arrays
using System;
public class GFG
{

  public static int find(int[] A, int[] B,
                         int m, int n,int k_req)
  {
    int k = 0, i = 0, j = 0;

    // Keep taking smaller of the current
    // elements of two sorted arrays and
    // keep incrementing k
    while (i < m && j < n) {
      if (A[i] < B[j]) {
        k++;
        if (k == k_req)
          return A[i];
        i++;
      }
      else {
        k++;
        if (k == k_req)
          return B[j];
        j++;
      }
    }

    // If array B[] is completely traversed
    while (i < m)
    {
      k++;
      if (k == k_req)
        return A[i];
      i++;
    }

    // If array A[] is completely traversed
    while (j < n)
    {
      k++;
      if (k == k_req)
        return B[j];
      j++;
    }
    return -1;
  }

  // Driver Code
  static public void Main (){
    int[] A = { 2, 3, 6, 7, 9 };
    int[] B = { 1, 4, 8, 10 };
    int k = 5;
    Console.WriteLine(find(A, B, 5, 4, k));
  }
}

// This code is contributed by rag2127

Javascript

<script>
    
    function find(A, B, m, n, k_req)
    {
        let k = 0, i = 0, j = 0;

        // Keep taking smaller of the current
        // elements of two sorted arrays and
        // keep incrementing k
        while (i < m && j < n) {
            if (A[i] < B[j]) {
                k++;
                if (k == k_req)
                    return A[i];
                i++;
            }
            else {
                k++;
                if (k == k_req)
                    return B[j];
                j++;
            }
        }

        // If array B[] is completely traversed
        while (i < m) {
            k++;
            if (k == k_req)
                return A[i];
            i++;
        }

        // If array A[] is completely traversed
        while (j < n) {
            k++;
            if (k == k_req)
                return B[j];
            j++;
        }
        return -1;
    }

    // Driver Code
    let A = [ 2, 3, 6, 7, 9 ];
    let B = [ 1, 4, 8, 10 ];
    let k = 5;
    
    document.write(find(A, B, 5, 4, k));
    
    // This code is contributed by Dharanendra L V.
    
</script>

Python3


# Python3 Program to find kth element 
# from two sorted arrays

def find(A, B, m, n, k_req):    
    i, j, k = 0, 0, 0

    # Keep taking smaller of the current
    # elements of two sorted arrays and
    # keep incrementing k
    while i < len(A) and j < len(B):
        if A[i] < B[j]:
            k += 1
            if k == k_req:
                return A[i]
            i += 1
        else:
            k += 1
            if k == k_req:
                return B[j]        
            j += 1

    # If array B[] is completely traversed
    while i < len(A):
        k += 1
        if k == k_req:
                return A[i]
        i += 1


    # If array A[] is completely traversed
    while j < len(B):
        k += 1
        if k == k_req:
                return B[j]
        j += 1

# driver code
A = [2, 3, 6, 7, 9]
B = [1, 4, 8, 10]
k = 5;
print(find(A, B, 5, 4, k))
# time complexity of O(k)
Output

6

Time Complexity: O(k) 
Auxiliary Space: O(1)

K-th Element of Two Sorted Arrays using Binary Search:

We know that the Kth element will lie either in arr1[] or in arr2[], so we can maintain 2 search spaces: [arr1, arr1 + n] and [arr2, arr2 + m] to find the kth element. Find the midpoints of both the search spaces, say mid1 and mid2. mid1 tells that the kth element can lie in the range [arr1, arr1 + mid1] and mid2 tells that kth element can lie in the range [arr2, arr2 + mid2]. Now, we can have 2 cases:

Case 1: (mid1 + mid2 < k), this means that we have taken less than k elements in our search space and we need to include more elements.
If (arr1[mid1] > arr2[mid2]), means that there are larger elements in arr1[] so we should include more elements from arr2[].
If (arr1[mid1] <= arr2[mid2]), means that there are larger elements in arr2[] so we should include more elements from arr1[].

Case 2: (mid1 + mid2 >= k), this means that we have taken more than or equal to k elements in our search space and we might need to remove extra elements.
If (arr1[mid1] > arr2[mid2]), means that there are larger elements in arr1[] so we should remove the extra elements from arr1[].
If (arr1[mid1] <= arr2[mid2]), means that there are larger elements in arr2[] so we should remove the extra elements from arr2[].

We keep on reducing the search space till we reach the kth element of the merge sorted array.

In this way, define a new subproblem with half the size of one of the arrays.

C++

#include <iostream>
using namespace std;

// Recursive function to find the kth element in two sorted
// arrays
int kth(int* arr1, int* arr2, int* end1, int* end2, int k)
{
    // If the first array is exhausted, return the k-th
    // element from the second array
    if (arr1 == end1)
        return arr2[k];
    // If the second array is exhausted, return the k-th
    // element from the first array
    if (arr2 == end2)
        return arr1[k];

    // Calculate midpoints for both arrays
    int mid1 = (end1 - arr1) / 2;
    int mid2 = (end2 - arr2) / 2;
    if (mid1 + mid2 < k) {
        // If the value at mid1 in the first array is
        // greater, discard the left part of the second
        // array
        if (arr1[mid1] > arr2[mid2])
            return kth(arr1, arr2 + mid2 + 1, end1, end2,
                       k - mid2 - 1);
        // Otherwise, discard the left part of the first
        // array
        else
            return kth(arr1 + mid1 + 1, arr2, end1, end2,
                       k - mid1 - 1);
    }
    else {
        // If the value at mid1 in the first array is
        // greater, discard the right part of the first
        // array
        if (arr1[mid1] > arr2[mid2])
            return kth(arr1, arr2, arr1 + mid1, end2, k);
        // Otherwise, discard the right part of the second
        // array
        else
            return kth(arr1, arr2, end1, arr2 + mid2, k);
    }
}

// Function to find the k-th element in two sorted arrays
int kthElement(int arr1[], int arr2[], int n, int m, int k)
{
    return kth(arr1, arr2, arr1 + n, arr2 + m, k - 1);
}

int main()
{
    // Sample Input
    int n = 5, m = 4;
    int arr1[] = { 2, 3, 6, 7, 9 };
    int arr2[] = { 1, 4, 8, 10 };
    int k = 5;

    cout << kthElement(arr1, arr2, n, m, k);
    return 0;
}

Javascript

function kth(arr1, start1, end1, arr2, start2, end2, k) {
    if (start1 === end1) {
        return arr2[start2 + k];
    }
    if (start2 === end2) {
        return arr1[start1 + k];
    }
    let mid1 = Math.floor((start1 + end1) / 2);
    let mid2 = Math.floor((start2 + end2) / 2);
    if (mid1 - start1 + mid2 - start2 < k) {
        if (arr1[mid1] > arr2[mid2]) {
            return kth(arr1, start1, end1, arr2, mid2 + 1, end2, k - (mid2 - start2) - 1);
        } else {
            return kth(arr1, mid1 + 1, end1, arr2, start2, end2, k - (mid1 - start1) - 1);
        }
    } else {
        if (arr1[mid1] > arr2[mid2]) {
            return kth(arr1, start1, mid1, arr2, start2, end2, k);
        } else {
            return kth(arr1, start1, end1, arr2, start2, mid2, k);
        }
    }
}

let arr1 = [2, 3, 6, 7, 9];
let arr2 = [1, 4, 8, 10];
let k = 5;
console.log(kth(arr1, 0, arr1.length, arr2, 0, arr2.length, k - 1));
Output

6

Time Complexity: O(log n + log m)
Auxiliary Space: O(logn + logm)



Last Updated : 07 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads