Working on the following algorithm:
Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.
For example, given nums = [-2, 0, 1, 3], and target = 2.
Return 2. Because there are two triplets which sums are less than 2:
def three_sum_smaller(nums, target)
nums.sort!
i = 0
triplet_count = 0
while i < nums.length
j = i + 1
while j < nums.length
pair_sum = nums[i] + nums[j]
val = target - pair_sum
k = binary_search(nums, val) #if val in it, we want all indices between j and k. else all indices j and k including k.
(nums[k] == val) ? triplet_count += (j + 1...k).size : triplet_count += (j + 1..k).size #ensures k > j.
j += 1
end
i += 1
end
triplet_count
end
def binary_search(arr, val)
b_search(arr, val, 0, arr.length - 1)
end
def b_search(arr, val, low, high)
while low < high
mid = (low + high) / 2
if arr[mid] > val #left half
high = mid - 1
elsif arr[mid] < val
low = mid + 1
else
#go left until it's no longer k and return this.
until arr[mid] != val
mid -= 1
end
return mid
end
end
low
end
My code is off by 1 for the following test case:
arr = [-3,4,-4,1,-1,-2,-1,-1,-5]
target = -3
Correct output: 48
My output: 59
The approach works as follows. For every possible pair, execute a binary search looking for the value that makes the sum of the pair == target. If this value doesn't exist, return the index less than it. If it does, return the first occurrence of that value. Then, if the value was found, only take the indices between j and k (excl k) as triplet completions. If the value not found, take indices incl j as triplet completion.
This worked for 200 or so test cases and is failing afterward. I'm not sure what's wrong..