EasyLeetCode #1

Two Sum

Find two numbers that add up to a target and learn how to recognize when a hash map can turn repeated searching into constant-time lookup.

ArraysHash Map

Problem

Two Sum

The Problem

You are given an array of integers nums and an integer target.

Find two different elements in the array whose values add up to target, and return their indices.

You may assume that exactly one valid answer exists.

Example 1

Input:
4 9
2 7 11 15

Output:
0 1

Because:

2 + 7 = 9

Example 2

Input:
3 6
3 2 4

Output:
1 2

Because:

2 + 4 = 6

Example 3

Input:
2 6
3 3

Output:
0 1

Before You Look at the Hints

Try this problem yourself first.

Don't immediately search for the optimal solution.

Start with the simplest approach you can think of.

Write the code. Run it.

Then ask yourself:

What makes my solution slow?

That question is more important than getting the answer quickly.


Examples

Example 1

Input

4 9
2 7 11 15

Output

0 1
Example 2

Input

3 6
3 2 4

Output

1 2
Example 3

Input

2 6
3 3

Output

0 1

YOUR SOLUTION

Try it yourself

Run against the examples first. Submit when you're confident.

solution.cpp
CPP

Ready to run

TEST CASES

Check your thinking

Example 1Test Case

Input

4 9
2 7 11 15

Expected Output

0 1
Example 2Test Case

Input

3 6
3 2 4

Expected Output

1 2
Example 3Test Case

Input

2 6
3 3

Expected Output

0 1

Elvoret Approach

Stuck? Use a hint.

Try the problem yourself first. If you get stuck, reveal the hints one at a time. After all three hints, you can reveal the complete answer.