Iam_Sandeep

kth smallest of two sorted arrays

Feb 10th, 2022 (edited)
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.35 KB | None | 0 0
  1. https://practice.geeksforgeeks.org/problems/k-th-element-of-two-sorted-array1317/1
  2. #User function Template for python3
  3.  
  4. class Solution:
  5.     def kthElement(self,  A, B, n, m, k):
  6.         if n>m:
  7.             A,B=B,A
  8.             n,m=m,n
  9.         l,r=max(0,k-m),min(n-1,k)
  10.        
  11.         while True:
  12.             i=(l+r)//2
  13.             j=k-i-2
  14.             #print(i,j)
  15.             aleft=A[i]    if i>=0  else float('-inf')
  16.             bleft=B[j]    if j>=0  else float('-inf')
  17.             aright=A[i+1] if i+1<n else float('inf')
  18.             bright=B[j+1] if j+1<m else float('inf')
  19.            
  20.             #print(i,j,aleft,bleft,aright,bright)
  21.            
  22.             if aleft<=bright and bleft<=aright:
  23.                 return max(aleft,bleft)
  24.             elif aleft>bright:
  25.                 r=i-1
  26.             else:
  27.                 l=i+1
  28.        
  29.        
  30.        
  31.        
  32.  
  33. #{
  34. #  Driver Code Starts
  35. #Initial Template for Python 3
  36.  
  37. def main():
  38.  
  39.     T = int(input())
  40.  
  41.     while(T > 0):
  42.         sz = [int(x) for x in input().strip().split()]
  43.         n, m, k = sz[0], sz[1], sz[2]
  44.         a = [int(x) for x in input().strip().split()]
  45.         b = [int(x) for x in input().strip().split()]
  46.         ob = Solution()
  47.         print(ob.kthElement( a, b, n, m, k))
  48.  
  49.         T -= 1
  50.  
  51.  
  52. if __name__ == "__main__":
  53.     main()
  54.  
  55. # } Driver Code Ends
Add Comment
Please, Sign In to add comment