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 = 4Output: 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.ApproachInitialize 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)); OutputKth 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: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)); OutputKth 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. Comment More infoAdvertise with us Next Article Find Kth Element of Two Sorted Arrays in JavaScript S shreyasnaphad Follow Improve Article Tags : JavaScript Web Technologies JavaScript-DSA Similar Reads Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co 11 min read JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav 11 min read Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De 5 min read Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance 10 min read Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact 12 min read React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications 15+ min read Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We 9 min read JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as 15+ min read React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon 8 min read Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and 9 min read Like