Solving the Classic Two Sum Problem in JavaScript

It’s always best to write some pseudocode first in a coding interview so you can collect your thoughts and see if your potenti

Solving the Classic Two Sum Problem in JavaScript

Back again with a classic coding interview question.. Let’s chat about how you can solve the two sum problem for a coding interview!

Picture this: You're sitting at your desk in your remote interview, a steaming cup of coffee next to you, fingers poised over the keyboard…. You're feeling great! Ready to pass the coding interview and maybe go take your dog for a walk after.

You get the question and you freeze for some reason. You’ve got this usually but it’s not the best timing today! Maybe it’s because your coffee beans got slightly burnt. Or because your building’s fire alarm went off at 2am. Either way, you still have to solve the problem to get a new job!

Your mission? Find two numbers within that array to sum up to that target number.

And you need to write it efficiently too!

Imagine we have an array with numbers like [3, 1, 4, 2, 5] and our target sum is 6. We're looking for a pair of dance partners in this array, who when they team up, give us the magical number 6. Will it be 1 and 5? Or perhaps 4 and 2? How do you know?

Alright, why don't you give this problem a whirl yourself? I'll hang back for a bit. 

Done yet?

….

Okay how did it go? Need more time?

And we're back. How did you do? Did you find the pair that brings you to the target sum?

Let's walk through it together, step by step, with some pseudocode before we translate into JavaScript.

It’s always best to write some pseudocode first in a coding interview so you can collect your thoughts and see if your potential solution has any issues.

1. Create a map to keep a record of the numbers.

2. Loop through the array, looking for a match. 

    a. Is your current number's perfect partner (target - current number) in the map? 

    b. If yes, the number  is found - return their position!

    c. If not, we add the current number to the map and move on.

How did it go? Were you able to solve it yourself?

Randall Kanna

Engineer/Writer/Speaker

Senior Software Engineer at Trim with almost a decade of experience. Published O'Reilly Author. Ex Eventbrite, Pandora, Gumroad, Ticketfly.