Counting Valleys

Last modified date

Problem Description:

An avid hiker keeps meticulous records of their hikes. During the last hike that took exactly steps steps, for every step it was noted if it was an uphill, U, or a downhill, D step. Hikes always 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 the sequence of up and down steps during a hike, find and print the number of valleys walked through.

Example:

steps = 8 path = [DDUUUUDD]

The hiker first enters a valley 2 units deep. Then they climb out and up onto a mountain 2 units high. Finally, the hiker returns to sea level and ends the hike.

Function Description

Complete the countingValleys function in the editor below.

countingValleys has the following parameter(s):

  • int steps: the number of steps on the hike
  • string path: a string describing the path

Returns

  • int: the number of valleys traversed

Input Format

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

Constraints

  • 2 <= steps <= 106
  • path[i] E {UD}

Sample Input

8
UDDDUDUU

Sample Output

1

Solution

You are given the following to start with:

#include <bits/stdc++.h>

using namespace std;

string ltrim(const string &);
string rtrim(const string &);

/*
 * Complete the 'countingValleys' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts following parameters:
 *  1. INTEGER steps
 *  2. STRING path
 */

int countingValleys(int steps, string path) {
    
}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    string steps_temp;
    getline(cin, steps_temp);

    int steps = stoi(ltrim(rtrim(steps_temp)));

    string path;
    getline(cin, path);

    int result = countingValleys(steps, path);

    fout << result << "\n";

    fout.close();

    return 0;
}

string ltrim(const string &str) {
    string s(str);

    s.erase(
        s.begin(),
        find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
    );

    return s;
}

string rtrim(const string &str) {
    string s(str);

    s.erase(
        find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
        s.end()
    );

    return s;
}

We want to focus on the countingValleys() function. We will need to keep track of the following:

  • The level the hiker is at.
  • The number of valleys the hiker has traversed.

We also know that we will want to return the number of valleys that have been traversed by the hiker. The hiker always starts at sea level and has traversed no valleys so we can instantiated both variables with 0.


int countingValleys(int steps, string path) {
    int level = 0;
    int numberOfValleys = 0;
    
    return numberOfValleys;
}

Next, we will need to loop through the path string to determine if the hiker is going up or down. We can use the steps variable to determine the length of the path string. Since strings are similar in behavior to arrays we can utilize the .at() to access the path string at a specific index just like using [i] on an array.

int countingValleys(int steps, string path) {
    int level = 0;
    int numberOfValleys = 0;
    for(int i =0; i <steps; i++){
        if(path.at(i) == 'D'){
            // ????
        }
        else if (path.at(i) == 'U'){
            // ????
        }
    }
    return numberOfValleys;
}

If the hiker is descending, noted by D in the path string, we must subtract 1 unit from the level. If the hiker is going uphill, noted by the U in the path string, then we must add 1 unit to the level.

What does this mean for the number of valleys?

int countingValleys(int steps, string path) {
    int level = 0;
    int numberOfValleys = 0;
    for(int i =0; i <steps; i++){
        if(path.at(i) == 'D'){
            level = level - 1;
        }
        else if (path.at(i) == 'U'){
            level = level + 1;
        }
    }
    return numberOfValleys;
}

Remember: 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.

We also know that the hiker is starting at sea level (level = 0). If the level is 0 again AND we are NOT at the start of the path, then we know we are coming up out of a valley and we can increase the number of traversed valleys by one.


 if(level == 0 && i != 0){
    numberOfValleys = numberOfValleys +1; 
 }

Should this code go in the downhill (D) if statement or the uphill (U) else if statement?

If you read the above statement closely, you will note that a valley always ends by coming UP to sea level. The code belongs in the uphill (U) else if statement.

else if (path.at(i) == 'U'){
    level = level + 1; 
     if(level == 0 && i != 0){
        numberOfValleys = numberOfValleys +1; 
   }
}

The finished solution:

#include <bits/stdc++.h>

using namespace std;

string ltrim(const string &);
string rtrim(const string &);

/*
 * Complete the 'countingValleys' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts following parameters:
 *  1. INTEGER steps
 *  2. STRING path
 */

int countingValleys(int steps, string path) {
    int level = 0;
    int numberOfValleys = 0;
    for(int i =0; i <steps; i++){
        if(path.at(i) == 'D'){
            level = level - 1;
        }
        else if (path.at(i) == 'U'){
            level = level + 1; 
            if(level == 0 && i != 0){
                numberOfValleys = numberOfValleys +1; 
            }
        }
    }
    return numberOfValleys;
}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    string steps_temp;
    getline(cin, steps_temp);

    int steps = stoi(ltrim(rtrim(steps_temp)));

    string path;
    getline(cin, path);

    int result = countingValleys(steps, path);

    fout << result << "\n";

    fout.close();

    return 0;
}

string ltrim(const string &str) {
    string s(str);

    s.erase(
        s.begin(),
        find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
    );

    return s;
}

string rtrim(const string &str) {
    string s(str);

    s.erase(
        find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
        s.end()
    );

    return s;
}
Share post

Bailey Kramer

I am a software developer in Wisconsin who has a passion for mathematics and learning new things. So far I have spent two years in the industry mainly working for a webcasting startup.