codelearner
Two Sum
Abhinandan Mishra

Abhinandan Mishra

Feb 03, 2022

Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Example 2:

Example 3:

Constraints:

Approach 1: Brute Force

Algorithm

The brute force approach is simple. Loop through each element xx and find if there is another value that equals to target - xtargetx.

Implementation

Approach 2: Using Hashmap

Algorithm

We're maintaining a hashmap where we are storing the index of values of nums as we move forward in nums.

But for each iteration we're checking if there's any element = target-x is already present in the map and if yes then we simply return the (current_index,mp[element]).

Where mp[element] means the index of the element.

Implementation

Happy Learning !

Abhinandan Mishra

Abhinandan Mishra

Abhimanyu Bano

Leave a Reply

Related Posts

Categories