DEV Community

Linda Thompson
Linda Thompson

Posted on • Originally published at lindakat.com on

3 1

Coding Practice - Counting Valleys (Hacker Rank)

Counting Valleys Problem

This is an easy rated problem on Hacker Rank, but I solved it on my first try so I'm fairly excited! All those years of doing Advent of Code has paid off! :) So here's the breakdown of this problem, and my solution.

The Setup

We're supplied with the number of steps someone takes on their hike, and an array that lists if each step is up or down. Their hike always starts and ends at sea level, and we're tasked with figuring out how many valleys (how many times they go down below sea level, and then come back up to sea level) they encounter during the hike.

My solution

To me, the main part is tracking what the person's sea level value is. Then, we just need to count the number of times the sea level value goes from -1 to 0! This is the only time they're coming out of a valley and back to equal. So we can basically read through the array and update the sea level value for each step, and then when it goes from -1 to 0 (which will only happen on an up step), we increase the valley count! Then return the valley count when we finish going through the hike array.

/* we have a few provided values: 
n - total number of steps 
s - the array of directional steps 
U - an up step 
D - a down step 
*/
function countingValleys(n, s) { 
  let seaLevel = 0; 
  let valleys = 0; 
  for (let i = 0; i < n; i++) { 
    if (s[i] === 'U') { 
      seaLevel++; 
      if (seaLevel === 0) { 
        valleys++; 
      } 
    } else if (s[i] === 'D') { 
      seaLevel--; 
    } 
  } 
  return valleys;
}
Enter fullscreen mode Exit fullscreen mode

Pretty amazed this worked on the first try, in all honesty! lol Let me know if anything doesn't make sense, I'd be happy to walk through this with you!

Happy coding, friends!

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️