DEV Community

Mohammed Azim J
Mohammed Azim J

Posted on

Two Sum (Unsorted Array)

Two Sum (Unsorted Array)
Problem

Given an unsorted array and a target, find two numbers whose sum equals target and return their indices.

Example
nums = [2,7,11,15]
target = 9
Output: [0,1]

Because 2 + 7 = 9.

Best Approach – Hash Map

We use a dictionary to store numbers and their indices.

Idea

For each number:

complement = target - number

If complement already exists → we found the answer.

Algorithm Steps
Create empty dictionary
Loop through array
For each element:
Find complement = target - nums[i]
If complement in dictionary → return indices
Else store nums[i] in dictionary

Python Code
def twoSum(nums, target):
hashmap = {}

for i in range(len(nums)):
    complement = target - nums[i]

    if complement in hashmap:
        return [hashmap[complement], i]

    hashmap[nums[i]] = i
Enter fullscreen mode Exit fullscreen mode

Complexity
Type Complexity
Time O(n)
Space O(n)

Important Concept

This problem teaches:

Hashing
Complement search
Single pass array

This is a very important interview problem.

Top comments (0)