DEV Community

Cover image for Leetcode: Two Sum
Chris Kakos
Chris Kakos

Posted on

Leetcode: Two Sum

Instructions

Given an array of integers: num 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.

What is Being Asked?

Write a function that takes two arguments:

  1. an array of integers
  2. an integer

Within the block scope, you need a way to iterate over the values of nums and add the current index value with each of the remaining indices. If the sum of the current index value and the comparison index value are equivalent to the target number, the function should return an array containing the position of both indices. If no conditionals equate to the target number, the function should return false.

What Does That Look Like?

Two Sum Whiteboard

What Do I Need To Solve?

I chose a nested for loop in my solution to iterate over the input array: nums. The outer loop keeps track of the current index value and the inner loop compares the comparison index value(s). If the sum of the outer loop index value and the inner index value equal the target number, it then returns an array with both indices.

Solution

Two Sum Solution
Two Sum Console

Conclusion

Thank you for taking the time to read. It's with good intent that I share my approach in hopes that it adds a different perspective for anyone looking to get a better understanding of solving algorithmic challenges and building solutions with code.

If that's the case, let me know! Give it a like, drop a comment or feel free to connect with me on Twitter @ch2isk4kos. I'm all about connecting with the community!

Top comments (0)