07(Aug) K-th element of two Arrays
07. K-th element of two Arrays
The problem can be found at the following link: Question Link
Problem Description
Given two sorted arrays arr1 and arr2 and an integer k, find the element that would be at the k-th position in the combined sorted array of the two arrays.
Example:
Input:
k = 5
arr1 = [2, 3, 6, 7, 9]
arr2 = [1, 4, 8, 10]Output:
6Explanation: The final combined sorted array is [1, 2, 3, 4, 6, 7, 8, 9, 10]. The 5th element of this array is 6.
My Approach
Initialization:
Define a helper function
kthto find the k-th element in two sorted subarrays.The helper function takes arrays
arr1andarr2, start and end indices of the subarrays, and the valuek.
Base Cases:
If the starting index of
arr1exceeds its ending index, return the k-th element fromarr2.If the starting index of
arr2exceeds its ending index, return the k-th element fromarr1.
Recursive Case:
Calculate the midpoints of the subarrays.
Compare the sum of the midpoints with
k.Depending on the comparison:
Adjust the subarray bounds and
kfor the recursive call.
Return:
Call the helper function
kthwith the initial bounds andk-1.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(log(n) + log(m)), as the search space is halved in each recursive call.
Expected Auxiliary Space Complexity: O(log(n) + log(m)), due to the recursive stack space used for each subarray division.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated