Array ( [0] => [1] => questions [2] => Arrays [3] => Triplet-sum---- ) Arrays | Triplet sum | THE INQUISITIVE





Triplet sum

LEVEL:Beginner

Description

Given an array of integers and value X. Find 3 numbers such that sum of three numbers is equal to X. If it is not found print null.

Input Format

First line contains the size of the first array. Next line contains the m integers separated by the spaces. Next line contains the X value.

Output Format

Print 3 numbers


Example 1:

Input
5
9 2 7 1 3
13
Output
1 3 9
Example 2:

Input
8
1 9 8 2 3 2 0 7
24
Output
7 8 9
Example 3:

Input
4
4 2 1 9
12
Output
1 2 9

oops

Login to see Discussion




Approach

Approach1: Brute Force

Step-i) Using 3 for loops and checking for every element with every 2 other elements.
Step-ii) If the sum of I,j,k elements in three for loops, then return the triplet.

Time Complexity: O(n^3)
Space Complexity: O(n)

Approach2:

Step-i) Initialize variables i to 0 and j to length - 1.
Step-ii) Take the first element fixed ,second element(i) and last element(j)
Step-iii) Find the sum if the sum is greater we will increment
Step-iv) else we decrement j to j-1 and check equality.
Step-v) Then if it’s equal, return the indexes.

Time Complexity: O(n^2)
Space Complexity: O(n)


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution