As a continuation of my dive into algorithms I was fortunate enough to work on an easy LeetCode question with a partner. The prompt is as follows:
Before I do any coding I try my best to analyze what the question is asking and what kind of output that is expected. The examples provided by LeetCode are extremely helpful.
The first steps I took was to set up my function and console logging helps with knowing what data you are working with. These are the next steps I took to solve this problem:
- I created a constant “numObject” and set it to equal and empty object.
- I knew had to iterate through the given array so I used a simple for loop.
- I set a conditional to return the index of the element where if the target minus the current number being iterated is greater than or equal to 0. Otherwise return the current number being iterated and set it equal to the index.
- The answer below with the given nums array returns an answer of [2,3]. That is, the two indexes where the numbers added together return the target number 9 !
This was a fun problem to work through and it definitely set the tone for me learning how to think in terms of problem solving. Algorithms can sometimes be fun!
I’ll be adding another problem this upcoming week!