Skip to main content
All Questions

Find a triplet in an array with a given sum.

Medium

Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] such that:

  • i != j, i != k, and j != k
  • nums[i] + nums[j] + nums[k] == 0

The solution set must not contain duplicate triplets.

Examples

nums = [-1, 0, 1, 2, -1, -4] output: [[-1, -1, 2], [-1, 0, 1]] explanation: The triplets `[-1, -1, 2]` and `[-1, 0, 1]` are the only unique combinations that sum to zero. nums = [1, 2, -2, -1] output: [] explanation: There are no three numbers in the array that add up to zero. nums = [-2, 0, 1, 1, -2, -1, 0, 2, -1] output: [[-2, 0, 2], [-2, 1, 1], [-1, -1, 2], [-1, 0, 1]] explanation: The array contains four unique triplets that sum to zero.

Related courses

Course

Machine Learning Engineer Interview Prep

Land your dream machine learning role at Meta, Google, Amazon, Apple, Microsoft, Nvidia, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Explore ML system design, core concepts, coding, behavioral interviews, and more.

Course

Data Engineering Interview Prep

Land your dream data engineering role at Meta, Google, Amazon, Microsoft, Walmart, DoorDash, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Practice data modeling, pipeline design, SQL, coding, behavioral interviews, and more.