imashutosh51

K-th element of two Arrays

Feb 10th, 2026
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.04 KB | None | 0 0
  1. '''
  2. Read the docs of find median of two sorted array.
  3. '''
  4.  
  5.  
  6. from math import inf
  7. class Solution:
  8.     def kthElement(self, a, b, k):
  9.         if len(a)>len(b):
  10.             a,b=b,a
  11.         n1=len(a)
  12.         n2=len(b)
  13.        
  14.         l = max(0, k - n2)   # we take elements from the array1 in such a way that to get k-cut1 elements should be there in the arr2, It should not be there k-cut1 is gonna exceed the arr2 length
  15.         r = min(k, n1)      
  16.         while l<=r:
  17.             cut1= (l+r)//2
  18.             cut2= k-cut1
  19.            
  20.             left_first= a[cut1-1] if cut1>0 else -inf
  21.             left_second=b[cut2-1] if cut2>0 else -inf
  22.             right_first=a[cut1] if cut1<n1 else inf
  23.             right_second=b[cut2] if cut2<n2 else inf
  24.            
  25.             if left_first<=right_second and left_second<=right_first:
  26.                 return max(left_first,left_second)
  27.            
  28.             elif left_first>right_second:
  29.                 r=cut1-1
  30.             else:
  31.                 l=cut1+1
  32.         return -1
  33.        
Advertisement
Add Comment
Please, Sign In to add comment