Solving Programmatic Algorithms: “Counting Valleys”

Haleigh Dalke
5 min readJul 29, 2020

--

Masayoshi Son Powerpoint of Coronavirus Trajectory
SoftBank CEO Masayoshi Son’s Powerpoint for Coronavirus Trajectory

This post is intended to help prepare you for upcoming whiteboard interviews for your future employer, or (if you’re a nerd like me) for the thrill of problem-solving. A gentle warning before you begin: if you have any hope of passing a whiteboard interview, don’t be like SoftBank CEO Masayoshi Son. If you find yourself struggling mid-interview, don’t just draw horses entering the “valley of coronavirus” and emerging as unicorns. Your employer will lump you into the category of believing hydroxychloroquine cures coronavirus. Be smarter.

The Problem (Courtesy of Hacker Rank)

Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike, he took exactly n steps. For every step he took, he noted if it was an uphill, U, or a downhill, D, step. Gary’s hikes start and end at sea level and each step up or down represents a 1 unit change in altitude. We define the following terms:

  • A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
  • A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.

Given Gary’s sequence of up and down steps during his last hike, find and print the number of valleys he walked through.

For example, if Gary’s path is s = [DDUUUUDD], he first enters a valley 2 units deep. Then he climbs out and up onto a mountain 2 units high. Finally, he returns to sea level and ends his hike.

Function Description

Complete the countingValleys function in the editor below. It must return an integer that denotes the number of valleys Gary traversed.

countingValleys has the following parameter(s):

  • n: the number of steps Gary takes
  • s: a string describing his path

Input Format

The first line contains an integer n, the number of steps in Gary’s hike.
The second line contains a single string s, of n characters that describe his path.

→Constraints

Output Format

Print a single integer that denotes the number of valleys Gary walked through during his hike.

Sample Input

8
UDDDUDUU

Sample Output

1

Explanation

If we represent _ as sea level, a step up as /, and a step down as \, Gary's hike can be drawn as:

_/\      _
\ /
\/\/

He enters and leaves one valley.

Before You Begin

Think about the tools in your toolbox: conditionals, loops, data types, scope, recursion (to name a few). How can we take these tools and reshuffle them around to achieve a different result? How can you take eggs, butter, flour, and sugar and make 1000 different deserts? The French managed to figure it out, so can you! Whiteboard interview questions are meant to evaluate how well you take your fundamental understanding of a language and apply it to solving problems. I promise you that you have the programmatic tools to solve this problem, little math involved.

Note: there are typically many ways to solve one problem, so don’t be discouraged if yours looks slightly different. Just take a critical eye to the possible solutions: Does yours have a faster runtime? Does it use fewer lines of code? Does it use built-in functions specific to your language?

Breaking It Down

For this solution, I will be programming in JavaScript. Let’s start by extracting out a few important pieces of information:

  1. Gary always starts and finishes at sea level. This means he will have an equal amount of U’s and D’s in his path.
  2. A “complete” valley is a negative departure from sea level (going D from sea level) and completed by the arrival back to sea level. Similarly, a “complete” mountain is a positive departure from sea level (going U from sea level) and completed by the arrival back to sea level. Notice the language I’m using: a negative/positive departure.
  3. The function returns a number that represents the number of valleys Gary went through. We don’t care about the mountains he climbed (I know, depressing right?).

So what’s the problem really asking? Let’s say sea level is 0, a downwards step is -1, and an upwards step is +1. We want to know how many times Gary went negative and returned to 0. We don’t care about the times he was in a valley and climbed upwards (mini mountains) if he never reached sea level. Take a look at the “W” shape in the problem’s explanation. The small mountains are ignored because Gary did not reach sea level. The whole time he was negative until the point he reached 0 is counted as 1 valley.

The Solution

Pseudo Code

We want to go through every step in Gary’s path and keep track of his elevation after every step. If Gary goes U, add 1 to elevation. Otherwise, it is safe to assume he is going D, so we will subtract 1 from the elevation. IF at any point after the first step in his journey he reaches sea level, we want to know. Again, safe to assume that if the elevation is 0 after completing a U step, he was exiting a valley so we should increment our valley counter by 1. Return the number of valleys after completing all steps.

JavaScript Solution

let countingValleys = (steps, path) => {
let elevation = 0
let valleyCount = 0
path.split('').forEach(char => {
if (char === 'U'){
elevation += 1
// console.log(`We went up. Step: ${steps}`)

if (elevation === 0){
valleyCount++
// console.log("We finished a valley.")
}
}
else {
elevation -= 1
// console.log(`We went down. Step ${steps}`)
}

// steps -= 1
})
return valleyCount
}
console.log(`Total valleys: ${countingValleys(8, 'UDDDUDUU'})`)

To understand each step or to prove the solution, try uncommenting the provided helper console.log’s and running in your browser.

Congratulations, you made it through! You’re definitely smarter than Masayoshi Son, and now you have another sample interview question for the books. Hope you enjoyed this walkthrough, don’t forget to give ya girl a clap. Until next time :)

Resources: Hacker Rank

--

--