DEV Community

Doug Jones
Doug Jones

Posted on

Algo Step 👣👣👣

Crawl before you code?

We have all heard the term at some point in our lives you have to "Crawl before you walk".

Well in the case of learning algorithms it almost seems like we are going from walking to running. 🤔🤔🤔

1) When we crawl we start learning the basic of coding.. variables, function, data types...etc

2) We start walking when we learn to put them together by building projects or start with some basic problem solving.

3) In my case now. I feel like we are starting running a little bit maybe a light jog. As we start to diving deeper into understanding problem solving using algorithms and data structures.

Lets Jog Together

Let's look at a problems and go though it step by step.

Step 1 - Understanding the problem

Given an Array, find the first duplicate value that occurs. If there are no duplicates, return -1.

This seems pretty simple to understand but to reinforce this rewrite the question in your own words.

Take the given array and find the first matching pair. If there are no matches return -1.

The Array: [1, 5, 3, 10, 2, 5]

Step 2 - Pseudocode a path or solution to how your going to solve the problem.

Pseudocode is just a step by step outline of your code in plain text.

1)Iterate through the array
2)Check the value of the first index and compare it to the rest of the array for a match.
3)If there is a match output the match.
4)If no match move on to the next index and compare it to the rest of the array.
5)Keep going until all values in the array have been checked.
If not match is found return -1.

Step 3 - Code

Code out the solution to the problem and if needed don't be afraid to write out your own test to check if you are getting the results you are looking for.

function findFirstDuplicate(arr) {
  let elementSet = new Set()
  for (let i = 0; i < arr.length; i++) {
    if (elementSet.has(arr[i])) return arr[i];
    elementSet.add(arr[i]);
  }
  return -1
}
Enter fullscreen mode Exit fullscreen mode

As with anything there is more than one way to do things but as I have started these are the steps I have started taking.

Hopefully you have found this helpful and as always.

Happy Coding 👨🏿‍💻👨🏻‍💻🧑🏾‍💻👩‍💻

Top comments (0)