10. Add Up Indices

The following problems comes directly from Leetcode.

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Define the Problem

The problem has been well defined by the interviewer, but let's further clarify.

Jonathan: Can I use JavaScript?

Interviewer: Sure.


Think

Jonathan thinks about the problem for a bit. This one is somewhat tricky, but he can already think of one way to solve. Here's his pseudocode:

// Create a function that will take in an array of numbers and the target number
// Use a for loop to go through each number
// Use a nested for loop to then check against each element
   /* Each element is checked against each iteration to see if there is a combination that matches the
   desired result */
   // return array of indices that matches the 2 numbers.

Write Code and Syntax

Now that the hard part is done, Jonathan just needs to write out the syntax to fill in the pseudocode. As Jonathan writes out the code, he explains the syntax.

// Create a function that will take in an array of numbers and the target number
function twoSum(nums, target) {
    // Use a for loop to go through each number
    for (var i = 0; i < nums.length; i++) {
        // Use a nested for loop to then check against each element
        for (var j = i + 1; j < nums.length; j++) {
            /* Each element is checked against each iteration to see if there is a combination that matches the
            desired result */
            if (nums[j] == target - nums[i]) {
                // return array of indices that matches the 2 numbers.
                return [i, j];
            }
        }
    }
}

Jonathan: I decided that the easiest thing to do would be to create a function that takes in the array of numbers and the target required. From there, I used a loop to go through each number in the passed array, and then I have a nested loop to go through each combination of subtraction to get the desired numerical result. Once the result was achieved, I returned the array of numbers.