In a desperate effort to write more, I'm going to be publishing a series of posts about my solutions to some LeetCode practice problems. If you have input about my solutions, especially about ways to optimize, feel free to let me know in the comments!
We'll start with the first problem of the whole 2500+ problem set: Two Sum. The directives are as follows.
Given an array of integers
nums
and an integertarget
, 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.
This seems like a simple problem from the outset, and in reality it's pretty straightforward. The idea behind my algorithm is that by rotating through the nums
array twice, we can check each value in the array with every other one and see if they sum to target
.
Let's set up a basic structure for what our algorithm will look like.
loop through array (iterator 1)
loop through array (iterator 2)
if i1 is equal to i2 then skip the below instructions
if nums[i1] plus nums[i2] is equal to target then return [i1, i2]
That's the basic idea that I took to this problem; you might have a different way of tackling it. As of right now, I'm still pondering how to remove the need for the for
loops and coming up short. It's because of their functionality that I can check the state so easily though, so I think I'll keep them for now.
How do we implement this into JavaScript? The loops are easy enough.
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < nums.length; j++) {
}
}
Now then, let's add some code inside of the loops. We're checking for two things: if i
is equal to j
then we continue without checking the following conditional, and if nums[i] === nums[j]
then we know that's the solution and we return i
and j
as an array, like the problem requests.
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < nums.length; j++) {
if (i === j) continue;
if (nums[i] + nums[j] === target) return [i, j];
}
}
And there you have it. Wrap it up in the requested function and you're done.
As always, all code is available in the GitHub repository.
Happy coding!
Top comments (1)
Good article, a good approach to solving one of the most famous problems.