Saturday, January 26, 2019

Counting Valleys - Hacker Rank Solution

Counting Valleys -  Hacker Rank Solution

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  steps. For every step he took, he noted if it was an uphill, or a downhill step.
Gary's hikes start and end at sea level and each step up or down represents a  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 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 , he first enters a valley  units deep. Then he climbs out an up onto a mountain  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 , the number of steps in Gary's hike. 
The second line contains a single string , of  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.

Counting Valleys -  Hacker Rank Solution

Our goal is to count the number of valleys. A valley is a sequence of steps starting with a step downward from sea level and ending with a step upward to sea level. Let  be a variable denoting the current altitude. If we take a step upwards,  is incremented by one; if we take step downwards,  is decremented by one.
Since we know that the sequence of input steps starts and ends at sea level, then we can say that our  variable is  at the beginning and end of the hike. The number of valleys can be counted as the number of steps taken upwards to sea level (i.e., when  goes from  to . This is true, because each such step ends the sequence of steps below sea level, signifying the end of a valley.

Problem Setter's code:

C++


#include <iostream>
#include <cstdio>
#include <string>
#include <sstream> 
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <ctime>
#include <cassert>
using namespace std;
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define vi vector<int>
#define vpii vector<pii>
#define SZ(x) ((int)(x.size()))
#define fi first
#define se second
#define FOR(i,n) for(int (i)=0;(i)<(n);++(i))
#define FORI(i,n) for(int (i)=1;(i)<=(n);++(i))
#define IN(x,y) ((y).find((x))!=(y).end())
#define ALL(t) t.begin(),t.end()
#define FOREACH(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++)
#define REP(i,a,b) for(int (i)=(a);(i)<=(b);++i)
#define REPD(i,a,b) for(int (i)=(a); (i)>=(b);--i)
#define REMAX(a,b) (a)=max((a),(b));
#define REMIN(a,b) (a)=min((a),(b));
#define DBG cerr << "debug here" << endl;
#define DBGV(vari) cerr << #vari<< " = "<< (vari) <<endl;

typedef long long ll;

const int MINN = 2;
const int MAXN = 1e6;

int main()
{
    ios_base::sync_with_stdio(0);
    int n; 
    cin >> n;
    assert(n >= MINN && n <= MAXN);
    string s;
    cin >> s;
    assert(s.length() == n);
    int res = 0;
    int level = 0;
    FOR(i, n)
    {
        if(s[i] == 'D')
        {
            --level;
        }
        else if(s[i] == 'U')
        {
            ++level;
            if(level == 0) ++res;
        }
    }
    assert(level == 0);
    cout << res << endl;
}
Problem Tester's code:

Python 2

# Solution uses a two pointer technique, 
# we check if current step leads to height 0 and previous height was -ve.  
height = 0
prev_height = 0
cnt = 0
n = input()
s = raw_input().strip()
for i in range(len(s)):
    if (s[i] == 'U'):
        height += 1
    elif s[i] == 'D':
        height -= 1
    if height == 0 and prev_height < 0:
        cnt += 1
    prev_height = height
print cnt

Java

import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        char[] hike = scan.next().toCharArray();
        
        int count = 0;
        int altitude = 0;
        
        for(char c : hike) {
            // Step up
            if(c == 'U') {
                if(altitude == -1) {
                    count++;
                }
                altitude++;
            }
            // Step down
            else {
                altitude--;
            }
        }

        scan.close();
        
        System.out.println(count);
    }
}

Swift

var n = Int(readLine()!)!
var hike = readLine()!
var numValleys = 0
var altitude = 0

for char in hike.characters {
    if(char == "U") {
        if(altitude == -1) {
            numValleys += 1;
        }
        altitude += 1;
    }
    // Step down
    else {
        altitude -= 1;
    }
}

print(numValleys)

4 comments:

  1. // Complete the countingValleys function below.
    static int countingValleys(int n, String s) {
    char[] steps = s.toCharArray();
    int valleys=0;
    int pos=0;
    int prevPos=0;
    for(char step : steps){
    if(step == 'U'){
    prevPos = pos++;
    if(pos == 0){
    valleys++;
    }
    }else{
    prevPos = pos--;
    }
    }
    return valleys;
    }

    ReplyDelete
  2. #include
    #include
    int main()
    {
    int val=0,steps;
    int level=0,i;
    char altitude[20];
    scanf("%d",&steps);
    for(i=1;i<=steps;i++)
    scanf("%c",&altitude[i]);
    for(i=1;i<=steps;i++)
    {
    if(altitude[i]=='D')
    {--level;
    if(level==0)
    val=val+1;
    }

    else if(altitude[i]=='U')

    { ++level;
    if(level==0)
    val=val+1;
    }
    }
    //return valleys;


    printf("%d",val);
    }

    ReplyDelete
  3. bhn pdh len de ..kyu bacho ko bigad rhi h..pta nhi rhi h ya rha h

    ReplyDelete
  4. IN JS(NODEJS)

    function countingValleys(steps, path) {
    // Write your code here
    let a = Array.from(path);
    let valleys=0;
    let pos=0;
    let prevpos=0;

    for(let i=0;i<a.length;i++){
    if(a[i]==='U'){
    prevpos=pos++;
    if(pos===0){
    valleys++;
    }
    }else{
    prevpos = pos--;
    }
    }

    return valleys;

    }

    ReplyDelete

Powered by Blogger.