1
votes

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..

2
In problem statement, there is no requirement that the numbers are sorted, so binary search would not be aplicable in this scenario - Rene Hernandez
I'm sorting the input so that I can get an O(n^2 logn) time complexity - segue_segway
Well I just ran your example using your code and I got 59 as response - Rene Hernandez
Yes-- I had written the correct output / my output backwards. fixed. - segue_segway

2 Answers

1
votes

Silly question: given that 200 test cases pass but one fails, are you sure that the test output given is correct?


Looking at this another way: my interpretation of this algorithm (and apologies if I've misunderstood!) is that you want to find the total number of triplets that produce a sum of less than the target. The triplet cannot reuse the same number, but otherwise can be in any order.

As it happens, Ruby makes it super easy for generate combinations of length n from an array, with combination (see https://ruby-doc.org/core-2.2.0/Array.html#method-i-combination)

Using this, we can generate all unique triplets. Then it's trivial to sum each one, and see if it matches the criteria.

So an alternative solution that goes along these lines might look like:

def solve(array, target)
  array.combination(3).map { |p| p.reduce(&:+) }.select { |t| t < target }.count
end

With the inputs that you've given, this supports your answer of 48:

# array: [-2, 0, 1, 3]
# target: 2
# => 2

# array: [-3, 4, -4, 1, -1, -2, -1, -1, -5]
# target: -3
# => 48
1
votes

The problem is with the equality check before adding the range to triplet_count. You need to check for >= instead of == as follows:

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)
      (nums[k] >= val) ? triplet_count += ((j + 1)...k).size : triplet_count += ((j + 1)..k).size
      j += 1
    end
    i += 1
  end

  triplet_count
end

When your check for equality you are missing the fact that the number at position k could be larger than val so it won't represent a valid triplet.

Anyway, the solution can be lowered to O(N^2) if we use the following idea:

We can fix an index (idx) and then use two pointer (start and finish) to iteratively search the subarray from idx + 1 to nums.length - 1 to find valid ranges in order to complete the triplets. The code is shown below:

def three_sum_smaller_without_search(nums, target)
  nums.sort!
  triplet_count = 0
  nums.each_with_index do |val, idx|
    start = idx + 1
    finish = nums.length - 1

    while start < finish
      if val + nums[start] + nums[finish] >= target
        finish -= 1
      elsif val + nums[start] + nums[finish] < target
        triplet_count += finish - start
        start += 1
      end
    end
  end

  triplet_count
end