Hello! Today I will explain how to solve the Two Sum problem. I believe most developers have seen this problem before—either when they first started practicing coding or when preparing for job interviews.
For those in the software industry who haven’t solved this problem yet, I’ll show you how to approach it step by step.
Let’s get started.
Question
Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.
You may assume that each input has exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example
Input: nums = [2,11,15,7], target = 9
Output: [0,3]
Explanation: Because nums[0] + nums[3] == 9, we return [0, 3].
Solution
function twoSum(nums, target) {
for (let i = 0; i < nums.length ; i++) {
for (let j = i + 1; j < nums.length ; j++) {
if (nums[i] + nums[j] === target) {
return [i, j]
}
}
}
return []
};
const nums = [2, 11, 15, 7]
const target = 9
console.log(twoSum(nums, target)) // Answer: [0, 3]
Explain the solution
- Create a function that takes two parameters:
numsandtarget. - Use two loops to find two numbers in the array whose sum equals the target:
- The outer loop iterates through each element in the array.
- The inner loop checks the elements after the current outer loop index.
- For example, with
[2, 11, 15, 7]: when the outer loop is at2, the inner loop checks11,15, and7.
- For example, with
- Inside the inner loop, check whether the sum of the two numbers equals the target.
- If it does, return their indices.
- If no pair is found after checking all possibilities, return an empty array.
- That’s it!
Performance consideration
This solution is easy to understand and works correctly, but it is not efficient. It uses a time complexity of O(n²) because it checks every possible pair.
In the next article, I will show you a more efficient solution that reduces the time complexity—this will be useful for interviews and real-world applications.
Thanks for reading, and keep learning!
Top comments (0)