DIY: 3Sum Closest

Solve the interview question "3Sum Closest" in this lesson.

Problem statement

You are given an integer array nums and an integer variable target as inputs. Your task is to find the three numbers in the given array that sum closest to the value target. You must return the sum of these three numbers.

Constraints

  • 3 <= nums.length <= 1000
  • -1000 <= nums[i] <= 1000
  • -10410^4 <= target <= 10410^4

Input

The inputs of the function are an integer array and an integer variable. The following is an example input:

nums = [-2, 3, 2, -4]
target = 2

Output

The following is the output for the above input:

1

Coding exercise

Implement the threeSumClosest(nums, target) function, where the nums is an integer array and target is the integer variable and returns the interger number.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.