Hackerrank challenge (Counting Valleys)
The job search quest has been a bit difficult, but fun! I now get the opportunity to focus on algorithms, data structures, sending messages to recruiters, and my favorite, CODE CHALLENGES!
I worked on a code challenge today, that was considered easy on Hackerrank. It’s part of the interview preparation course. I wasn’t sure how to initially solve the question on counting valleys, however I began to write down a given input and expected outputs for the solution. This test challenged my approach to solving algorithms using JavaScript.
Initially it takes in a number of steps (Lets say 8), and your path is either (Up or Down) which will affect elevation. When you enter and leave a valley, you increment the amount of valleys entered in a given amount of steps. You want to return the total amount of valleys. I knew I had to track elevation, because if elevation is one below valley and my next path is Up, I knew that I would be leaving a valley, and therefore increment the total valleys. It was fairly simple writing down my approach, but wasn’t as easy to translate it into code.
function countingValleys(steps, path) {
//focus on sealevellet valleys = 0; let elevation = 0;for (let i = 0; i < steps; i++){if(path[i] == “D”) {elevation - - ;}else {if (elevation == -1){valleys++;}elevation++}}return valleys}
It took about 25 minutes, and might not be the most efficient way to solve it, however it passed the requirements!! I’ll get better at decreasing the runtime of my algorithms in the future.