Advertisement
hoangreal

Find smallest index sum of any pairs equal target

Oct 21st, 2024
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | None | 0 0
  1. """
  2. Given two arrays, (say [1,3,5] and [2,4]) and a number target (say 7), assume we sort by the sum of any pair of elements from each array, return the smallest index.
  3. In this example, the result is 3.
  4. Pair, Sum, Index
  5. (1,2), 3, 0
  6. (1,4), 5, 1
  7. (3,2), 5, 2
  8. (3,4), 7, 3 <- result
  9. (5,2), 7, 4
  10. (5,4), 9, 5
  11. """
  12.  
  13. def binary_search(nums, target):
  14.     """
  15.    Find the largest index strictly smaller than a given number.
  16.    
  17.    Time complexity: O(log n)
  18.    Space complexity: O(1)
  19.    """
  20.     start, end = 0, len(nums) - 1
  21.     while start <= end:
  22.         mid = start + (end - start) // 2
  23.         if nums[mid] >= target:
  24.             end = mid - 1
  25.         else:
  26.             start = mid + 1
  27.     return end
  28.  
  29. def find_index(nums1, nums2, target):
  30.     """
  31.    Find the smallest index of pair sum equal to target from two sorted arrays.
  32.    
  33.    Time complexity: O(n log m), where n = len(nums1) and m = len(nums2)
  34.    Space complexity: O(1) excluding input sorting
  35.    """
  36.     # Sort input arrays
  37.     nums1.sort()
  38.     nums2.sort()
  39.    
  40.     res = 0
  41.     has_res = False
  42.    
  43.     # Iterate through nums1
  44.     for num1 in nums1:
  45.         # Find the largest index in nums2 where sum < target
  46.         lb = binary_search(nums2, target - num1) + 1
  47.        
  48.         # Check if we found a pair sum equal to target
  49.         if lb < len(nums2) and nums2[lb] == target - num1:
  50.             has_res = True
  51.        
  52.         # Accumulate the index
  53.         res += lb
  54.    
  55.     return res if has_res else -1
  56.  
  57. # Example usage
  58. nums1 = [1, 3, 5]
  59. nums2 = [2, 4]
  60. target = 7
  61. result = find_index(nums1, nums2, target)
  62. print(f"Result: {result}")  # Expected output: 3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement