Leetcode Link: https://leetcode.com/problems/two-sum/
1. Problem Statement (Simple Explanation)
You are given:
An array of integers nums
An integer target
You need to return the indices of two numbers in the array such that:
Conditions:
Each input has exactly one solution.
You cannot use the same element twice.
You can return the answer in any order.
2. Examples
Example 1
Input:
nums = [2, 7, 11, 15], target = 9
Output:
[0, 1]
Explanation:
nums[0]+nums[1]=2+7=9
So we return [0, 1].
Example 2
Input:
nums = [3, 2, 4], target = 6
Output:
[1, 2]
Explanation:
nums[1]+nums[2]=2+4=6
Example 3
Input:
nums = [3, 3], target = 6
Output:
[0, 1]
Explanation:
3+3=6
3. Approach 1 – Brute Force (Basic)
Intuition
Try all possible pairs of elements and check if their sum equals the target.
This is the most straightforward solution: two nested loops.
Algorithm (Step-by-Step)
Loop i from 0 to n - 1.
For each i, loop j from i + 1 to n - 1.
For each pair (i, j):
If nums[i] + nums[j] == target, return [i, j].
Since the problem guarantees exactly one solution,
Pseudo-code (Brute Force)
Time and Space Complexity
Time: O(n*n)
because we check all pairs.
Space: O(1)
extra space (ignoring output).
Code – Brute Force
Java code:
C code:
C++ code:
Python code:
JavaScript code:
4. Approach 2 – Optimized Using Hash Map (O(n))
Intuition
Instead of checking all pairs, we use a hash map(dictionary) to store numbers we’ve already seen and their
indices.
For each number nums[i], we check if the complement exists:
complement=target-nums[i]
If we have already seen complement, we found the pair.
Otherwise, we store nums[i] with index i in the map.
This reduces the complexity from O(n*n) to O(n).
Algorithm (Step-by-Step)
Create an empty hash map valueToIndex.
Loop i from 0 to n - 1:
Let current = nums[i].
Compute complement = target - current.
If complement is in valueToIndex:
return [valueToIndex[complement], i].
Otherwise, store valueToIndex[current] = i.
Because we are guaranteed exactly one solution, the
Pseudo-code (Optimized)
Time and Space Complexity
Time: O(n)
because we traverse the array once, and each hash map
operation is O(1) on average.
Space: O(n)
to store at most n elements in the map.
Code – Optimized (Hash Map)
Java code:
C code:
C++ code:
Python code:
JavaScript code:
.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)
Comments
Post a Comment