HackerRank Counting Valleys Problem Solution

In this post, We are going to solve HackerRank Counting Valleys Problem.

Avid hiker keeps meticulous records of their hikes. During the last hike that took exactly 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:

  • 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.
  • 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 = [DDUUUUUDDD]

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 counting alleys function in the editor below.

counting Valleys 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 integer steps, the number of steps in the hike.
The second line contains a single string path, of steps characters that describe the path.

Sample Input

8
UDDDUDUU

Sample Output

1

Explanation

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

_/\      _
   \    /
    \/\/

The hiker enters and leaves one valley.

HackerRank Counting Valleys Problem Solution
HackerRank Counting Valleys Problem Solution

Counting Valleys C Solution

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */    
    int n; 
    scanf("%d\n",&n);
    char *height = malloc(sizeof(char) * n);
    for(int height_i = 0; height_i < n; height_i++){
       scanf("%c",&height[height_i]);
    }
    int level = 0;
    int count = 0;
    int valley = 0;
    for(int height_i = 0; height_i < n; height_i++){
       if (height[height_i] == 'D')
       {
           if( level == 0 && valley == 0) 
           {
                valley = 1;
           }
           level--;
       }
       else if (height[height_i] == 'U')
        {
            if (level == -1 && valley == 1)
            {
                count++;
                valley = 0;
                
            }
           level++;
       }
      
      
    }
    printf("%d",count);
    return 0;
    
    
}

Counting Valleys C++ Solution

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    int steps;
    cin >> steps;
    int level = 0;
    int valleys = 0;
    char c;
    for (int i = 0; i < steps; i++) {
        cin >> c;
        if (c == 'U') {
            level++;
            if (level == 0) {
                valleys++;
            }
        } else if (c == 'D') {
            level--;
        }
    }
    cout << valleys << '\n';
    return 0;
}

Counting Valleys C Sharp Solution

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Counting_Valleys
{
    class Program
    {
        static void Main(string[] args)
        {
            int sea_level=1, cnt_valley=0,level=1,i=0;
            int n = int.Parse(Console.ReadLine());
            string walk = Console.ReadLine();

            while(i<n)
            {
                if(sea_level<level)
                {
                    if (walk[i] == 'U')
                        level++;
                    else
                        level--;
                }
                else if(sea_level>level)
                {
                    if (walk[i] == 'U')
                        level++;
                    else
                        level--;

                    if (sea_level == level)
                        cnt_valley++;
                }
                else
                {
                    if (walk[i] == 'U')
                        level++;
                    else
                        level--;
                }
                i++;
            }
           
            Console.WriteLine(cnt_valley);
        }
    }
}

Counting Valleys Java Solution

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        int steps=s.nextInt();
        char[] seq= s.nextLine().toCharArray();
         seq= s.nextLine().toCharArray();
        int level=0;
        int valleys=0;
        boolean valleyStart=false;
         //System.out.println("jaja");
        for(int i=0;i<steps;i++)
        {
            //System.out.println(level+" "+seq[i]);
            if(level==0 && seq[i]=='D'){
                valleyStart=true;
            }
            if(level==-1 && seq[i]=='U' && valleyStart){
                valleyStart=false;
                valleys++;                
            }
            if(seq[i]=='D'){               
            level--;
            }
            else{
                level++;
            }           
            
        }
        System.out.println(valleys);
    }
}

Counting Valleys JavaScript Solution

function processData(input) {
    //Enter your code here
    var steps = input.split("\n")[1];
    steps = steps.split("");
    var valleys = 0;
    var level = 0;
    steps.map(function(step){
       if(level == 0 && step == "D"){
           valleys += 1;
       }
       if(step == "D"){
           level -= 1;
       }
       if(step == "U"){
           level += 1;
       }
    });
    
    console.log(valleys);
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

Counting Valleys Python Solution

first =input()
second=input()
count_1 =0
count_2 =0
below_sea = False
for element in range(0,len(second)):
    if second[element] == "U":
        count_1 += 1
        
    if second[element] == "D":
        count_1 -=1
        
    
    if count_1 < 0:
        if not below_sea :
            count_2 +=1
            below_sea = True
    else:
        below_sea =False
print(count_2)

Other Solutions

Leave a Comment