Sum of Three Values

Try to solve the Sum of Three Values problem.

Statement#

Given an array of integers, nums, and an integer value, target, determine if there are any three integers in nums whose sum is equal to the target, that is, nums[i] + nums[j] + nums[k] == target. Return TRUE if three such integers exist in the array. Otherwise, return FALSE.

Note: A valid triplet consists of elements with distinct indexes. This means, for the triplet nums[i], nums[j], and nums[k], i \not = j, i \not = k and j \not = k.

Constraints:

  • 33 \leq nums.length \leq 500500
  • 103-10^3 \leq nums[i] \leq 10310^3
  • 103-10^3 \leq target \leq 10310^3

Examples#

Created with Fabric.js 3.6.6 Input target 20 result True Output Sample example 1 nums 3 7 1 2 8 4 5

1 of 3

Created with Fabric.js 3.6.6 Output target 1 result False Input Sample example 2 nums -1 2 1 4

2 of 3

Created with Fabric.js 3.6.6 target 1 Input Output result True Sample example 3 nums -1 2 1 4 -2

3 of 3

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Sum of Three Values

1

What should be the output if the following set of inputs is provided?

nums = [2, 3, 1]

target = 6

A)

True

B)

False

Question 1 of 40 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Sort the input array in ascending order.

Iterate over the entire sorted array to find the triplet whose sum is equal to the target.

In each iteration, make a triplet by storing the current array element and the other two elements using two pointers (low and high), and calculate their sum.

Adjust the calculated sum value, until it becomes equal to the target value, by conditionally moving the pointers, low and high.

Return TRUE if the required sum is found. Otherwise, return FALSE.


Try it yourself#

Implement your solution in main.py in the following coding playground. We have provided a useful code template in the other file that you can use to solve this problem.

Python
main.py
two_pointers.py
Input #1
Input #2
%0 node_01 1 node_11 -1 node_21 0
Visualization for Input #1
Sum of Three Values

Solution: Sort Colors

Solution: Sum of Three Values