Two Sum Less Than
Given two int arrays A
and B
, and an int c
, return the total number of pairs (a, b)
where a
is from A
and b
is from B
, and a + b <= c
.
The Idea: We can brute force all computational pairs between a and b that are less than or equal to c in N^2 time. We can maintain a set of unique computational pairs to avoid duplicates. Another approach would be to sort both A and B, and for then find the largest point where a <= c - b in the target array. Do with for both arrays.
Complexity: O(|A|log|A| + |B|log|B| + |A|log|B| + |B|log|A| + |A| + |B|) and O(|A| + |B|) space. For the time complexity, sorting both arrays, then iterating through A calling binary search, then the reverse, and in the end, converting the solution set into a list.
Last updated