Ruby three sum challenge solved but too slow

I tried to solve this problem for the past three hours using ruby, and I was impressed by how much I improved it: because it was too slow it pushed me too improve the code and I came with a good solution but too slow for exemple 315/318 (that array is massive)... anyway, I'm open to any suggestions!

# @param {Integer[]} nums
# @return {Integer[][]}
def three_sum(nums)
  answers = []
  return answers if nums.length < 3
  if nums.length == 3
    answers << nums if nums.inject(:+) == 0
    return answers
  end
  nums.sort!
  nums.each_with_index do |first_num, i|
    break if first_num > 0
    next if first_num == nums[i - 1] && i != 0
    nums[i + 1...nums.length - 1].each.with_index do |second_num, j|
      next if j != 0 && second_num == nums[i + 1...nums.length - 1][j - 1]
      break if second_num > first_num / -2 && second_num != 0
      third_num = nums[i + j + 2...nums.length].find{ |num| num + second_num + first_num == 0 }
      next unless third_num
      curr_answer = [first_num, second_num, third_num]
      answers << curr_answer
    end
  end
  answers
end
Comments (0)