Skip to content
Programmingoneonone
Programmingoneonone

LEARN EVERYTHING ABOUT PROGRAMMING

  • Home
  • CS Subjects
    • IoT ? Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone

LEARN EVERYTHING ABOUT PROGRAMMING

HackerRank Counting Valleys problem solution

YASH PAL, 31 July 20249 August 2024

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 solution
Hackerrank counting valleys solution

Topics we are covering

Toggle
  • Problem solution in Python programming.
  • Problem solution in Java Programming.
    • Problem solution in C++ programming.
    • Problem solution in C programming.
    • Problem solution in JavaScript programming.

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);
});

 

coding problems solutions interview prepration kit AlgorithmsHackerRank

Post navigation

Previous post
Next post
  • Automating Image Format Conversion with Python: A Complete Guide
  • HackerRank Separate the Numbers solution
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
How to download udemy paid courses for free

Pages

  • About US
  • Contact US
  • Privacy Policy

Programing Practice

  • C Programs
  • java Programs

HackerRank Solutions

  • C
  • C++
  • Java
  • Python
  • Algorithm

Other

  • Leetcode Solutions
  • Interview Preparation

Programming Tutorials

  • DSA
  • C

CS Subjects

  • Digital Communication
  • Human Values
  • Internet Of Things
  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2025 Programmingoneonone | WordPress Theme by SuperbThemes