In this HackerRank Counting Valleys problem in the Interview preparation kit you have Given the sequence of up and down steps during a hike, find and print the number of valleys walked through.


HackerRank Counting Valleys Interview preparation kit solution


Problem solution in Python programming.

#!/bin/python3

import math
import os
import random
import re
import sys

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

def countingValleys(steps, path):
    # Write your code here
    valleys = 0
    cur_level = 0
    for steps in path:
        if(steps == 'U'):
            cur_level += 1
            if(cur_level == 0):
                valleys += 1
        elif(steps == 'D'):
            cur_level -= 1
    return(valleys)

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    steps = int(input().strip())

    path = input()

    result = countingValleys(steps, path)

    fptr.write(str(result) + '\n')

    fptr.close()



Problem solution in Java Programming.

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

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        in.nextInt();
        String s = in.next();
        
        int level = 0;
        int valleys = 0;
        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) == 'U'){
                level++;
            }else if(s.charAt(i) == 'D'){
                if(level == 0){
                    valleys++;
                }
                level--;
            }
        }
        System.out.println(valleys);
    }
}


Problem solution in C++ programming.

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


int main() {
    int l;
    string str; cin>>l>>str;
    int height = 0;
    int count = 0;
    for(int i=0;i<l;i++){
        if (str[i]=='U') height++;
        else {
            if (height==0) count++;
            height--;
        }
    }
    if (height<0) count--;
    cout<<count<<endl;
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    return 0;
}


Problem solution in C programming.

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

int main() {
    int n;
    scanf("%i", &n);
    char str[n];
    scanf("%s", str);
    int level = 0, result = 0, valley = 0;
    for (int i = 0; i < n; i++) {
        if(str[i] == 'U') {
            level++;
            if(level == 0 && valley) {
                valley = 0;
                result++;
            }
        }
        else if(str[i] == 'D') {
            if(level == 0)
                valley = 1;
            level--;
        }
    }
    printf("%i", result);
    return 0;
}


Problem solution in JavaScript programming.

function processData(input) {
  var args = input.split('\n');
  var n = Number(args[0]);
  var topo = args[1];
  var belowSeaLevel = false;
  var level = 0;
  var valleysHiked = 0;
  for (let i = 0; i < n; i += 1) {
    // Adjust current level of hike
    if (topo.charAt(i) === 'D') {
      level -= 1;
    } else {
      level += 1;
    }
    if (level < 0) {
      belowSeaLevel = true;
    }
    if (belowSeaLevel && level === 0) {
      valleysHiked += 1;
      belowSeaLevel = false;
    }
  }
  console.log(valleysHiked);
} 

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

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