Skip to content
loading...

re: Breaking Down DSAs: Two Sum VIEW POST

FULL DISCUSSION
 

Hi Claire! I am new to coding and recently learning Javascript and I wanted to get practicing on algorithm questions asap, so I started with the supposedly easy challenge "Two Sum". I am struggling with understanding why my brute force solution isn't producing the expected result and wondering if you could provide some guidance for me? I want to enhance the solution once I understand why my first solution isn't working. Here's my code snippet:

function twoSum(targetSum, array) {
var indicesTracker = [];
var sum;

            for (var i=0; i < array.length; i++) {

                for(var j=1; j < array.length; j++) {

                    sum = array[i] + array[j];

                        if(sum == targetSum) {

                        indicesTracker.push([i,j]);

                        }
                }
            }

            return indicesTracker;
        }

I put this code on an editor and ran it through the browser and when I called the function, I showed up correctly on the console but I can't get it to work on LeetCode. Been struggling since yesterday and still can't figure out why...

The above code gives an output of [], but I've added the indices to my indicesTracker array though, so I don't understand what's causing the wrong answer.

Your help would be greatly appreciated!
Lily

 

Hey! Great work, just a few things:

  1. There's a small but important error in your second for loop: j is set to 1, it should be i+1. This way you're always comparing i with the element that follows. The way it is now, every time i increases, j is set back to 1.

  2. Once your function finds a match (sum == targetSum), you're pushing an array into the indicesTracker array, so your function is returning a nested array: [[i, j]]. You can simply push the elements themselves.

  3. Your function also keeps going even after it finds a match. As it is now, given targetSum = 9, and array = [1, 7, 3, 2, 6], your function will return [1, 3, 2, 4].

Let me know if this helped or you have any other questions! I also highly recommend this site for visualizing what's going on in your functions, it's helped me a ton: pythontutor.com/javascript.html#mo...

 

Thank you so much for the clear explanation Claire! Really really appreciate it! It all makes more sense now! I've also started using the link you suggested and is trying to understand how it works ! :D

code of conduct - report abuse