Skip to main content

Counting Valleys hackerrank

Counting Valleys Hackerrank solution in c


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.
 We define the following terms: 
  • A mountain is a non-empty 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 non-empty 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.

 Input Format 

The first line contains an integer, n, denoting the number of steps in Gary's hike.
 The second line contains a single string of n characters. Each character is  ∊{U,D} (where U indicates a step up and D indicates a step down), and the ith character in the string describes Gary's ith step during the hike.
Constraints
  • 2 ≤ N ≥ 10^6
Output Format

Print a single integer denoting the number of valleys Gary walked through during his hike. 
Sample Input 

8  
UDDDUDUU 

Sample Output 



Explanation 

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

 _/\       _  
     \     /                                 
      \/\/                                   
   
It's clear that there is only one valley there, so we print on a new line.


How to solve this problem.

lets's see how can we solve this problem.

Suppose this is a valley


 _/\       _
     \     /                
      \/\/
Character wise representation 

               _UD              _
                     D         U
                       DUDU 
    
Here we can see that number of U = D, Means the number of up step count is equal to number of  down step. Now if we take +1 to up step and -1 to down to step it will count 0 to make a complete valley. But we will also have to check that if it is 0 then it must be  with up step.


int countingValleys(int n, char* s) {
 int count=0,v=0;
 scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        if(s[i] == 'D')
            count--;
        else if(s[i] == 'U')
        {
            count++;
            if(count == 0 && s[i] == 'U')// This is the most important part
                v++;
        }
    }
    return v;

}


Full code is given below;


#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* readline();

// Complete the countingValleys function below.
int countingValleys(int n, char* s) {
 int count=0,v=0;
 scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        if(s[i] == 'D')
            count--;
        else if(s[i] == 'U')
        {
            count++;
            if(count == 0 && s[i] == 'U')
                v++;
        }
    }
    return v;

}

int main()
{
    FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");

    char* n_endptr;
    char* n_str = readline();
    int n = strtol(n_str, &n_endptr, 10);

    if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); }

    char* s = readline();

    int result = countingValleys(n, s);

    fprintf(fptr, "%d\n", result);

    fclose(fptr);

    return 0;
}

char* readline() {
    size_t alloc_length = 1024;
    size_t data_length = 0;
    char* data = malloc(alloc_length);

    while (true) {
        char* cursor = data + data_length;
        char* line = fgets(cursor, alloc_length - data_length, stdin);

        if (!line) { break; }

        data_length += strlen(cursor);

        if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }

        size_t new_length = alloc_length << 1;
        data = realloc(data, new_length);

        if (!data) { break; }

        alloc_length = new_length;
    }

    if (data[data_length - 1] == '\n') {
        data[data_length - 1] = '\0';
    }

    data = realloc(data, data_length);

    return data;
}


Comments

Popular posts from this blog

Day 2: Conditional Statements: Switch

  Objective In this challenge, we learn about  switch statements . Check out the attached tutorial for more details. Task Complete the  getLetter(s)  function in the editor. It has one parameter: a string,  , consisting of lowercase English alphabetic letters (i.e.,  a  through  z ). It must return  A ,  B ,  C , or  D  depending on the following criteria: If the first character in string   is in the set  , then return  A . If the first character in string   is in the set  , then return  B . If the first character in string   is in the set  , then return  C . If the first character in string   is in the set  , then return  D . Hint:  You can get the letter at some index   in   using the syntax  s[i]  or  s.charAt(i) . Input Format Stub code in the editor reads a single string denoting   from ...

Day 2: Conditional Statements: If-Else

Day 2: Conditional Statements: If-Else || Hackerrank Solution Objective In this challenge, we learn about  if-else  statements. Check out the attached tutorial for more details. Task Complete the  getGrade(score)  function in the editor. It has one parameter: an integer,  , denoting the number of points Julia earned on an exam. It must return the letter corresponding to her   according to the following rules: If  , then  . If  , then  . If  , then  . If  , then  . If  , then  . If  , then  .

Jumping on the Clouds Hackerrank

Jumping on the Clouds solutions in c. Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1  or 2  . She must avoid the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting position to the last cloud. It is always possible to win the game. For each game, Emma will get an array of clouds numbered 0   if they are safe or 1 if they must be avoided. For example, c=[0,1,0,0,0,1,0] indexed from 0....6. The number on each cloud is its index in the list so she must avoid the clouds at indexes 1 and 5 . She could follow the following two paths:0 ➜ 2 ➜ 4➜6   or 0 ➜ 2 ➜ 3 ➜ 4 ➜ 6 . The first path takes 3   jumps while the second takes 4 . Function Description Complete the  jumpingOnClouds ...