Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- 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.
- In this example, the result is 3.
- Pair, Sum, Index
- (1,2), 3, 0
- (1,4), 5, 1
- (3,2), 5, 2
- (3,4), 7, 3 <- result
- (5,2), 7, 4
- (5,4), 9, 5
- """
- def binary_search(nums, target):
- """
- Find the largest index strictly smaller than a given number.
- Time complexity: O(log n)
- Space complexity: O(1)
- """
- start, end = 0, len(nums) - 1
- while start <= end:
- mid = start + (end - start) // 2
- if nums[mid] >= target:
- end = mid - 1
- else:
- start = mid + 1
- return end
- def find_index(nums1, nums2, target):
- """
- Find the smallest index of pair sum equal to target from two sorted arrays.
- Time complexity: O(n log m), where n = len(nums1) and m = len(nums2)
- Space complexity: O(1) excluding input sorting
- """
- # Sort input arrays
- nums1.sort()
- nums2.sort()
- res = 0
- has_res = False
- # Iterate through nums1
- for num1 in nums1:
- # Find the largest index in nums2 where sum < target
- lb = binary_search(nums2, target - num1) + 1
- # Check if we found a pair sum equal to target
- if lb < len(nums2) and nums2[lb] == target - num1:
- has_res = True
- # Accumulate the index
- res += lb
- return res if has_res else -1
- # Example usage
- nums1 = [1, 3, 5]
- nums2 = [2, 4]
- target = 7
- result = find_index(nums1, nums2, target)
- print(f"Result: {result}") # Expected output: 3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement