LeetCode: Two Sum (Brute Force)
1 min readApr 23, 2021
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
Input: [2,7,11,15]
target=9
Output: [0,1]
Notes
There will always be a solution and we cannot use the same element twice (Ex: 11 can’t show up in the array twice)
Approach
- Create two for loops
- First loop will go over every element one at a time
- Second loop that’s nested inside, will iterate over every element after the element from the first loop
- Use an if-else statement to check if the number at first loop + number at second loop = target
- If the two element’s sum matches the target value, we will return an array of the indices
Code
for(let p1 = 0; p1<nums.length; p1++){
for(let p2 = p1+1; p2<nums.length; p2++){
if(nums[p1]+nums[p2] === target){
return [p1,p2];
}
}
}
Time Complexity
O(n²): Due to nested for loop iterating over the same array, it is O(n²)
Space Complexity
O(1): We don’t store any values into an array, set, map, etc.