Two Sum
Try to solve the Two Sum problem.
We'll cover the following
Statement#
For the given array of integers arr and a target t, you have to identify the two indices that add up to generate the target t. Moreover, you can’t use the same index twice, and there will be only one solution.
Note: We will assume that the array is zero-indexed and the output order doesn’t matter.
Constraints:
-
arr.length -
arr[i] -
t - Only one valid answer exists.
Examples#
1 of 3
2 of 3
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:
Two Sum
What is the output for the following input?
arr = [3, 9, 11, 12, 17, 21]
t = 26
[0, 5]
[1, 4]
[2, 3]
[3, 5]
Try it yourself#
Implement your solution in main.py in the following coding playground.
The optimal solution to this problem runs in O(n) time and takes O(n) space.
You might want to go over the Knowing What To Track pattern again.
Solution: Ransom Note
Solution: Two Sum