Find Kth Element of Two Sorted Arrays in JavaScript
Last Updated : 26 Aug, 2024
Given two sorted arrays, our task is to find the Kth element in the combined array made by merging the two input arrays in JavaScript.
Example:
Input: Arr1: [1, 2, 5] , Arr2:[2, 4, 6, 8], K = 4
Output: Kth element is 4.
Explanation:
The final Array would be: [1, 2, 2, 4, 5, 6, 8]
The 4th element of this array is 4.
Approach
- Initialize 2 pointers for both arrays where we will mark the beginning and end of both arrays.
- After making 2 pointers each for both arrays, we will perform a binary search on the combined array to find the Kth element.
- At each step, we will compare the middle elements of both arrays.
- Adjust the pointers based on the comparison.
- Repeat the process until the Kth element is found.
Example: The example below shows a JavaScript program for the Kth element of two sorted arrays using Binary Search.
JavaScript function findKthElement(nums1, nums2, k) { let left1 = 0, left2 = 0; while (true) { if (left1 === nums1.length) return nums2[left2 + k - 1]; if (left2 === nums2.length) return nums1[left1 + k - 1]; // If k is 1, return the minimum of the first elements if (k === 1) return Math.min(nums1[left1], nums2[left2]); // Choose the next smallest element let mid = Math.floor(k / 2), index1 = Math.min(left1 + mid, nums1.length) - 1, index2 = Math.min(left2 + mid, nums2.length) - 1, p1 = nums1[index1], p2 = nums2[index2]; if (p1 <= p2) { k -= index1 - left1 + 1; left1 = index1 + 1; } else { k -= index2 - left2 + 1; left2 = index2 + 1; } } } const nums1 = [1, 2, 5]; const nums2 = [2, 4, 6, 8]; // To find 4th element const k = 4; console.log("Kth Element:", findKthElement(nums1, nums2, k));
Time Complexity: O(log(min(n, m))), where n and m are the lengths of the two input arrays.
Space Complexity: O(1).
Approach : Merging Two Arrays (Iterative)
This approach involves merging both arrays until we find the Kth element. The idea is to traverse both arrays simultaneously, comparing elements from both arrays and counting how many elements we've traversed until we reach the Kth element.
Steps:
- Initialize two pointers for both arrays.
- Traverse both arrays, comparing elements at each pointer.
- Move the pointer of the array with the smaller element and increment a counter.
- Stop once the counter reaches K, and return the current element.
Example:
JavaScript function findKthElementByMerging(nums1, nums2, k) { let i = 0, j = 0, count = 0; while (i < nums1.length && j < nums2.length) { if (nums1[i] <= nums2[j]) { count++; if (count === k) return nums1[i]; i++; } else { count++; if (count === k) return nums2[j]; j++; } } // If we've exhausted one array, continue with the other while (i < nums1.length) { count++; if (count === k) return nums1[i]; i++; } while (j < nums2.length) { count++; if (count === k) return nums2[j]; j++; } // In case K is out of bounds (shouldn't happen if K is valid) return -1; } const nums1 = [1, 2, 5]; const nums2 = [2, 4, 6, 8]; // To find 4th element const k = 4; console.log("Kth Element:", findKthElementByMerging(nums1, nums2, k));
Time Complexity: O(K) - Since we are iterating up to the Kth element.
Space Complexity: O(1) - No additional space is used besides the input arrays.
Similar Reads
JavaScript Program to Find Largest Element in an Array In this article, we are going to learn about the largest element in an array in JavaScript. The largest element in an array refers to the value that holds the greatest numerical or lexicographic (string) order among all elements present in the array. Example: Input : [10, 15, 38, 20, 13];Output: 38H
3 min read
Find Common Elements In Three Sorted Arrays using JavaScript JavaScript can be used to find the common elements in given three sorted arrays. We are given three different sorted arrays, we have to return common elements of three arrays. Example:Input array1 = [1 , 2 , 3 , 4 ,5 ] array2 = [3 , 4, 5 , 6 ,7 ]array3 = [ 3 , 4 , 7 , 8 , 9] Output [3 , 4]Below are
4 min read
JavaScript Program to Find kth Largest/Smallest Element in an Array JavaScript allows us to find kth largest/smallest element in an array. We are given an array containing some elements, we have to find kth smallest/largest element from the array where k is a number greater than zero and less than equal to the total number of elements present in the array. There are
5 min read
How to Sort an Array Based on the Length of Each Element in JavaScript? Imagine you have a list of words or groups of items, and you want to arrange them in order from shortest to longest. This is a pretty common task in JavaScript, especially when working with text or collections of things. By sorting your list in this way, you can make sense of your data and make it e
3 min read
Javascript Program to Check Majority Element in a sorted array Question: Write a function to find if a given integer x appears more than n/2 times in a sorted array of n integers. Basically, we need to write a function say isMajority() that takes an array (arr[] ), arrayâs size (n) and a number to be searched (x) as parameters and returns true if x is a majorit
3 min read