Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Find Kth Element of Two Sorted Arrays in JavaScript
Next article icon

Find Kth Element of Two Sorted Arrays in JavaScript

Last Updated : 26 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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)); 

Output
Kth Element: 4 

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:

  1. Initialize two pointers for both arrays.
  2. Traverse both arrays, comparing elements at each pointer.
  3. Move the pointer of the array with the smaller element and increment a counter.
  4. 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)); 

Output
Kth Element: 4 

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.


Next Article
Find Kth Element of Two Sorted Arrays in JavaScript

S

shreyasnaphad
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-DSA

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences