• + 147 comments

    Java solution

    We only care about the number of valleys... So just figure out the number of times you came back up to sea level.

    public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            String s = sc.next();
            
            int v = 0;     // # of valleys
            int lvl = 0;   // current level
            for(char c : s.toCharArray()){
                if(c == 'U') ++lvl;
                if(c == 'D') --lvl;
                
                // if we just came UP to sea level
                if(lvl == 0 && c == 'U')
                    ++v;
            }
            System.out.print(v);
        }
    
    • + 5 comments

      Brilliant

      • + 13 comments

        The problem statement says consecutive steps below sea level. Does this solution work for 4 DUDU or does it return 1? Based on the problem statement that input should return 0.

        Edit: I removed the condition to check that the previous step was also below sea level and all the tests passed. However, this no longer matches the definition of a valley "consecutive steps below sea-level"... unless I am misunderstanding the implied multiplicity in the word consecutive.

        • + 13 comments

          I think the word consecutive is misleading here. Think about it, the number of valleys is just the number of times you went down below sea level and back up again. Every time it starts at sea level and goes down then back up to sea level, that is a valley. It doesn't need the word 'consecutive' in there.

          • + 1 comment

            Right.

            • + 1 comment

              Here comes the solution in python.

              Hackerrank - Counting Valleys Solution

              • + 0 comments

                here is solution of problem in Python java c++ and c programming. https://solution.programmingoneonone.com/2020/07/hackerrank-counting-valleys-solution.html

          • + 0 comments

            That's right.

          • + 0 comments

            I am equally seeing it from your own point of view, that word "consecutive" is misleading

          • + 3 comments

            I totally agreed. When I analyse the test case and even I manually count the number of valleys and I also got the different answer from the test case. The word "consecutive" makes me think it needs at least two "D" to start with. I strongly reccommend to remove the word "consecutive" which is misleading!

            • + 0 comments

              Yup, this confusion took me down the wrong path. Pulled my hairs when the submission failed.

            • + 0 comments

              Yes, the word "consecutive" make me lost about 3 hours trying to understand where I was wrong. So, removing the constraint that I was considering (at least 2 steps below sea level), makes all test pass

            • + 0 comments

              No wonder... I was think the same that it needs 2 D to start a valley..

          • + 0 comments

            yeah ,you are right

          • + 1 comment

            yes. right. it misleads me too.

            • + 0 comments

              Please suggest the edit in the question.

          • + 0 comments

            I totally thought 'consecutive' meant DU would not count as 1.

          • + 1 comment

            That's right..In the explanation part the answer should be 2 not 1 as per the definition because the hiker is coming 2 times to the sea level.

            • + 0 comments

              Totally agree with you, consecutives steps down means at least 2 steps down. It means 1 step down from sea level than 1 step up is not a valley according to the description.

          • + 0 comments

            Exactly spent half an hour cuz of this misleading consective statment!

          • + 0 comments

            Completely agree!!! The word 'consecutive' is misleading and if I have not had a look in the discussion tab, I would have never known about this. Thanks guys!!!

          • + 0 comments

            Ya, i'm also totally agreed with you i was failed to execute after checking the test cases and got the word 'consecutive' is missleading. good!!

          • + 0 comments

            thank you, that was my problem, i i though i need to be atleast 2levels down from sea level.. after making it only 1 level, everything worked out...

          • + 0 comments

            Entirely misleading wording. It is assumed you need two "D" steps from sea level in order for a valley to start. They obviously include DUDU as two separate valleys.

        • + 2 comments

          I think you are right.* "A valley is a sequence of consecutive steps below sea level, "* to me, means Gary took two or more steps below sea level. Problem description is misleading.

          • + 1 comment

            Yes I agree with this,The description is misleading

            • + 0 comments

              Please suggest editing.

        • [deleted]
          + 7 comments

          excatly my doubt is what about case dudu?

          • + 1 comment

            that's 2 vallys

          • + 0 comments

            in the case dudu the function must returned 2

            this is my c++ solution it works for all cases

            int countingValleys(int steps, string path) {

            int seaLevel = 0, countValley = 0;
            bool isU = false;
            for (char c : path)
            {
                if(c == 'U' || c == 'u')
                {
                    isU = true;
                    ++seaLevel;
                }            
                else
                {
                    isU = false;
                    --seaLevel;
                }
            
                if(seaLevel == 0 && isU)
                {           
                    ++countValley;
                }
            
            }
            
            return countValley;
            

            }

          • + 1 comment

            This is python 3

            valleys,count,sealevel=0,0,0
                for move in path:
                    if move == "U":
                        count+=1
                        if count== sealevel:
                            valleys+=1
                    else:
                        count-=1
                return valleys
            
          • + 0 comments

            In case of DUDU, there will be 2 valleys.

            Explantion

            sea-level \/\/ sea-level

            You can verify my correct solution, using the custom test case

            4 DUDU

          • + 0 comments

            Because at the end of the journey, the hiker will always return to sea level. So if you check every time the hiker goes back to sea level, and in this case, if the hiker comes from below, it means that the hiker went through a valley on the last walk.

          • + 0 comments

            get u with that dudududu!

          • + 0 comments

            it means 2 valleys

        • + 1 comment

          Yes, I think the word "consecutive" is misleading; it threw me off as well. One could argue it doesnt say "consecutive steps down". Unlocking one of the test case helped clear the doubt for me though.

          • + 0 comments

            Even i thought for climbing from or into a valley we need 2 steps.

        • + 0 comments

          Yes I agree your you . I had similar understanding. Looks like the word 'consecutive ' is misleading in the question

        • + 0 comments

          Yeah, "consecutive" lead me astray for a while. Always fun when test questions are wrong :D

        • + 0 comments

          I think that if we consider that for making even an only one-level-deep valley we need two consecutives steps (D and U) below sea level, there is no problem with the description.

          In other words, if we take into account only where (above/below sea level) the steps themselves took place (and not wheter they are uphill or downhill, nor what are their starting or edning points) to classify them as being above or below sea level, the tests match with the statement:

          A 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.

          I hope it makes sense.

        • + 0 comments

          I think if we take into account only where (above/under sea level) the steps themsleves took place (not wheter they are downhill or uphill) to classify them as being above or under sea level, the tests match with the statement:

          A valley is a sequence of consecutive steps below sea level, (...)

          In other words, I think we sould consider where the "body" of each step is to solve this problem.

          I hope it makes sense.

        • + 0 comments

          Exactly, I also was stuck because of the definition-'consecutive steps below sea-level'.. After seeing the solution here, I also thought of the same situation with case DUDU. And if a move up while current level is 0 counts as a valley, then a move down while current level is 0 should also work as a solution, but it doesn't.

      • + 3 comments

        nice one!

        • + 1 comment

          Here comes the solution in python.

          Hackerrank - Counting Valleys Solution

          • + 1 comment

            Can you please explain what you were doing here:

            if not a+d[i] and a <0: b+=1 a+=d[i]

            How is it possible to add (a = 0) to d[i] (a key). Please just explain oyour overall logic to me. Thanks in advance.

            • + 0 comments

              d[i] is value not key. The logic is brilliant. a is taking the sum of the consequitive steps of the path.So, after decending a valley if someone ascending to sea level then a=0 and if again it is negative that means new valley is explored so b will be increased 1 otherwise no change.

        • + 0 comments

          here is problem solution in java python c++ and c javascript programming. https://programs.programmingoneonone.com/2021/03/hackerrank-counting-valleys-solution.html

        • + 0 comments

          Here is my c++ solution, you can watch the explanation here : https://youtu.be/fgJ-i8RJ1Qw

          int countingValleys(int steps, string path) {
              int res = 0, level = 0;
              for(char c : path){
                  if(c == 'U'){
                      level++;
                      if(level == 0) res ++;
                  }
                  else level--;
              }
              return res;
          }
          
    • + 1 comment

      simple and superb

      • + 6 comments

        the most optimized fastest code: c#

        static int countingValleys(int n, string s) {
          int sum = 0;
          int count = 0;
          for(int i=0;i<n;i++){
            if(s[i]=='U'){
              if(++sum==0)
                count++;
            }
            else sum--;
          }
          return count;
        }
        
        • + 2 comments

          in if condition u r passing as a string but array is required. We can use like this: if(s.charAt(i)=='U') i got correct solution

          • + 0 comments

            In c# a string is an array of char.

        • + 0 comments

          what logic behind this

        • + 0 comments

          Why are you using static int type fuction when int type serves our purpose?

        • + 1 comment

          This code is correct but the test cases are getting failed. I think they are pulling us into wrong track.

          • + 0 comments

            I checked the above code but it didn't passed the test cases. This problem can be solved like this...

            int countingValleys(int steps, char* path)

            {

            int c=0; int valley_count=0; for (int i=0;i

                    else if((c==0) &&(path[i]=='D'))
                    {
                        valley_count++;
                        c++; 
                    }
            
                    else if (path[i]=='D')
                    {
                        c++;
                    }
            
                    else 
                    {
                    c--;
                    }       
            

            } return valley_count;

            }

    • + 2 comments

      short, simple and stright to the point. love it!

      • + 1 comment

        the most optimized fastest code: c#

        static int countingValleys(int n, string s) {
          int sum = 0;
          int count = 0;
          for(int i=0;i<n;i++){
            if(s[i]=='U'){
              if(++sum==0)
                count++;
            }
            else sum--;
          }
          return count;
        }
        
        • + 1 comment

          why are u using function type as static int?? can you explain that bro?

          • + 0 comments

            I can't understand what u r trying to say...plz explain in detail

    • + 3 comments

      image

      whats the problem in this code??\

      • + 2 comments
        public static void main(String[] args) {
        		Scanner scan = new Scanner(System.in);
        		int times = scan.nextInt();
        		scan.nextLine();
        		String UDs = scan.nextLine();
        		int[] levels = new int[times];
        		int up = 0, down = 0, count = 0;
        		for (int i = 0; i < times; i++) {
        			if (UDs.charAt(i) == 'U') {
        				up++;
        			} else {
        				down++;
        			}
        			levels[i] = up - down;
        
        		}
        		for(int i=0; i<times;i++){
        		if(levels[i]<0){
        		for(int ii = i; ii<times;ii++){
        			if(levels[ii]==0){
        				count++;
        				i=ii;
        				break;
        			}
        		}
        		}
        		}
        		System.out.println(count);
        	}
        }
        

        I thought i did well but looking at the very first commment, I realized im not good

        • + 1 comment

          Nice try but i know how it looks when u r at the begginer level of coding and all other are giving answers like one line python code and very small code

          • + 0 comments

            I'd rather see well-commented code than magical one-liners. Unless the performance increases to the roof.

        • + 0 comments

          great i didn't know how to solve this....

      • + 0 comments

        The problem is that it is not visible to the compiler.

      • + 0 comments

        its blurry

    • + 14 comments
      #include<stdio.h>
      
      int main()
      {
          int n;
          scanf("%d", &n);
          int j = 0, i = 0, cnt = 0;
          char a[n];
          //  INPUT THE STEPS
          for(j = 0; j < n; j++)
          {
              scanf("%c", &a[j]);
          }
      
          for(j = 0; j < n; j++)
          {
              if(a[j] == 'U')
              {
                  i = i + 1;
                  if(i == 0)
                      cnt++;
              }
              else if(a[j] == 'D')
              {
                  i = i - 1;
              }
          }
      
          printf("%d", cnt);
      
          return 0;
      }
      

      I've implemented the same logic as yours... Still it does not pass many testcases. Please help

      • + 1 comment

        Ya mine also many test case did not pass in he same logic

        • + 0 comments

          I have done the same,but may of my test cases failed.

      • + 5 comments

        try this logic:

        #include <iostream>
        #include <cstddef>
        
        int main()
        {
            std::size_t n; std::cin >> n;
            int sea_level = 0, Ans = 0;
            while(n--)
            {
                char input; std::cin >> input; 
                input == 'U' ? ++sea_level : --sea_level;
        	// else case is reductant here
                sea_level == 0 && input == 'U' ? ++Ans : Ans; 
            }
            std::cout << Ans << std::endl;
            return 0;
        }
        
        • + 0 comments

          Yeah yours is cool! Thanks

        • + 4 comments

          Hi, I think we can get by without using the character array. My submission below (translated to reflect your variable names). Passes all test cases.

          #include <iostream>
          using namespace std;
          
          int main()
          {
              unsigned int n; 
              cin>>n;
              cin.ignore();
              char ch;
              int sea_level=0, Ans=0;
              
              while(cin >> ch){ 
                  if(ch=='U')
                      ++sea_level;
                  if(ch=='D')
                      --sea_level;
                  if(sea_level==0 && ch=='U')
                      ++Ans;
                  }
              
              cout<<Ans<<endl;
              
              return 0;
          }
          
          • + 1 comment

            y hav you taken ch=='u' in the third if loop, iam nt getting y it is... can u pls explain it

            • + 1 comment

              In the third if condition, we are checking if we returned to sea level (0) from a valley by moving upwards (U). So we are verifying and incrementing the answer with respect to these 2 parameters

              • + 1 comment

                then y didnt you consider "D"- moving downwards?? please answer?

                • + 0 comments

                  I guess that would lead to hill, not valley, so that's why.

          • + 1 comment

            what's cin.ignore()?

            • + 1 comment

              Why don't you just google, rather asking here: https://en.cppreference.com/w/cpp/io/basic_istream/ignore

              • + 0 comments

                motherfucker, we are here to learn, and discuss in case of any doubt. Stop with your bullshit suggestions, asshole.

          • + 0 comments

            what is roll of a cin.ignore(); in these code

          • + 0 comments

            Nice Observation!

        • + 0 comments

          Change the size of the array initialized in the main function. It should work! 1*10^6.

        • + 1 comment

          what that n<=1000000 is for ??

        • + 1 comment

          C++14? I don't think that means what you think it means ;-)

      • + 0 comments

        what alteration can we do in the above code to pass all the test case and why ?

      • + 0 comments

        if one mountain is ended it again start again mountain then ur count value is increased but in actually it is not increased.so u must add this line in ur code also for(i=0;i

            }
            else if(arr[i]=='D')
            {
                count--;
            }
             if(count==0 && arr[i+1]=='D')
                {
                    s++;
                }
            else if(arr[0]=='D')
            {
                s++;
            }
        }
        
      • + 0 comments

        I have used the same logic, but still it doesn't passes many test cases ! If I replace 'U' in if statement by 'D' and 'D' in else if statement by 'U' , it passes all the test cases ! I don't understand why this happen ? please help !

      • + 2 comments

        i find your mistake, char array's last element should be reserved for null. you need to take extra size and after the array is sifted towards right b'coz each elements moved by 1 in right side . you nedd to strat array with i=1;

        include

        int main() { int n; scanf("%d", &n); int j = 0, i = 0, cnt = 0; char a[n]; // INPUT THE STEPS for(j = 0; j < n+1; j++) { scanf("%c", &a[j]); }

         /*for(j = 1; j < n+1; j++)
           printf("%c", a[j]);
        */
        
        for(j = 1; j < n+1; j++)
        {
            if(a[j] == 'U')
            {
                i = i + 1;
                if(i == 0)
                    cnt++;
            }
            else if(a[j] == 'D')
            {
                i = i - 1;
            }
        }
        
        printf("%d", cnt);
        
        return 0;
        

        }

        • + 0 comments

          thank you

        • + 1 comment

          this is right. but why array elements shifted to right ? m not getting? plz explain?

          • + 1 comment

            #include

            include

            using namespace std; int main() { int n; cin>>n; int j , i = 0, cnt = 0;

                    string s;
                    cin>>s;
            

            for(j = 0; j < n; j++) { if(s[j] == 'U') { i = i + 1; if(i == 0) cnt++; } else if(s[j] == 'D') { i = i - 1; } }

                    cout<<cnt<<endl;
            

            return 0; }

            • + 1 comment

              The idea do work my program was success fully run in C But I wanna know theoretical reason behind why array elements got shifted to

              • + 1 comment

                if you don't shift the array you can't read the input correclty. I'm just manipulate the char array in this way so that it can read the input char element correclty. if you want to do this without shifting you can see the buffer code of this problem. and then complete the code.

                • + 1 comment

                  Ok thank you but buffer was not working

                  • + 0 comments

                    Thank You

      • + 1 comment

        put a space infornt of "%c"..... or replace with this [ scanf(" %c", &a[j]); ] Hope,it will work!

        • + 0 comments

          It workss thx!!

      • + 0 comments

        the constrain given is n<10^6 the loop variable i is of type int and it does not hold that much values . so use data types of higher bits like int32_t and int64_t

      • + 0 comments

        here you scan only n char but last char is '\n' so that use n+1 in instead of n

      • + 0 comments

        in the abouve code you are also calculating the hill crossed ,but only valley is asked so edit if(i==0 && s[j]=='U') { cnt++; }

      • + 0 comments

        // Complete the countingValleys function below. int countingValleys(int n, string s) {

        int sea_level = 0; bool sea_level_cross = false; int valley;

        for(int i=0; i if(s[i]=='U') { sea_level++; if (sea_level < 0 && sea_level_cross == false) { sea_level_cross = true; valley++; } if(sea_level>= 0 && sea_level_cross == true) { sea_level_cross = false; } } else { sea_level--; if (sea_level < 0 && sea_level_cross == false) { sea_level_cross = true; valley++; } if (sea_level >= 0 && sea_level_cross == true) { sea_level_cross = false; } } } return valley; }

      • + 1 comment

        for for loop use for(j=0;j<=n;j++)

      • + 0 comments

        i have implemented the same logic as yours but it's work in all testcases.

      • + 0 comments

        you should execute the loop for <= in voth loops,during inputs of elemnt and during logic part as well

    • + 0 comments

      I implemented the same, nice to see concepts matching :P

    • + 1 comment

      it is not able to pass all the test cases,as input constrain is 1000000; and we are getting segmentation error

      • + 0 comments

        The following code in C will not get the segmentation error:

        #ifdef bool
          #undef bool
        #endif
        #define bool int
        #define true 1
        #define false 0
        
        long countingValleys(long n, char* s) {
            // Complete this function
            long valleys = 0;
            long level = 0;
            bool neg = false;
            
            for(long i=0; i < n; i++){
                if(s[i]=='U'){
                    level++;
                    if(level >= 0 && neg == true){
                        neg = false;
                    }
                }else{
                    level--;
                    if(level < 0 && neg == false){
                        neg = true;
                        valleys++;
                    }
                }
            }
            
            
            return valleys;
        }
        
        int main() {
            int n; 
            scanf("%i", &n);
            /* Change the default from 512000 to 1024000 */
            char* s = (char *)malloc(1024000 * sizeof(char));
            scanf("%s", s);
            long result = countingValleys(n, s);
            printf("%ld\n", result);
            free(s);
            return 0;
        }
        

        The code given as a default does not allocate enough space for the array. You can also do this:

        char* s = (char *)malloc((n + 1) * sizeof(char));
        

        A better solution is not to use the function provided and just parse the array while it is being entered. So, you can do something like this:

        char buf;
        for(int i = 0; i < n; i++){
            scan("%c", &buf);
            /* embed the logic of the function here */
           
        }
        
    • + 0 comments

      Excellent.

    • + 2 comments

      Would this work if "we only care about the number of" mountains?

      • + 0 comments

        I think no. Because you can go to valley, come back to sea level, again go to valley, so on... without ever climbing the mountain.

      • + 0 comments

        Yea you could just add another if statement testing basically the opposite.

    • + 0 comments

      superb!!!

    • + 0 comments

      Beautiful Solution

    • + 0 comments

      Awesome .... just brilliant

    • + 0 comments

      I came up with same concept, but yours is better executed. the use of s.toCharArray() is nice.

      public static void main(String[] args) {
              int valley = 0;
              int elevation = 0;
              Scanner in = new Scanner(System.in);
              int t = in.nextInt();
              String s = in.next();
              
              for (int i=0;i<t;i++) {
                  char c = s.charAt(i);
                  if (c == 'D') {
                      if (elevation == 0)
                          valley++;
                      elevation--;     
                  } else
                      elevation++;
              }
              System.out.println(valley);
          }
      
    • + 1 comment

      I got the exact same code:) import java.io.; import java.util.; import java.text.; import java.math.; import java.util.regex.*;

      public class Solution {

      public static void main(String[] args) {
          Scanner sc = new Scanner(System.in);
          int n = sc.nextInt();
          String s = sc.next();
      
          int v = 0;     
          int lvl = 0;   
          for(char c : s.toCharArray()){
              if(c == 'U') ++lvl;
              if(c == 'D') --lvl;
      
      
              if(lvl == 0 && c == 'U')
                  ++v;
          }
          System.out.print(v);
      }
      

      }

      • + 0 comments

        In this code if(lvl==0 && c=='U') ++v; this will count the uphill steps but in this question they are asking for the down hill steps when level ==0 so instead of that if you can write if(lvl==0 && c=='U') for downhill steps

    • + 0 comments

      superb...

    • + 0 comments

      True, but only because he had to end at sea level. Without that it becomes messier. In any case - awesome!

    • + 5 comments

      Am I missing something, or does this code assume that there will always be at least one valley, and that there will always be a valley inbetween any two mountains? If so, it should fail with something like:

      2 UD expected: 0 actual: 1

      or

      4 UDUD expected: 0 actual: 2

      For comparison (Python 3):

      def countingValleys(n, s):
      
          inValley = False
          vallies = 0
          hgt = 0
          
          for step in s:
              if step == 'U':
                  hgt += 1
              else:
                  hgt -= 1
                  
              if not inValley:
                  if hgt < 0:
                      inValley = True
              elif hgt == 0:
                  inValley = False
                  vallies += 1
                  
          return vallies
      
      • + 1 comment

        I believe you are referring to the following code segment. It increments/decrements lvl prior to checking for valley. It does not assume a valley nor that one exists between any two mountains, as it only increments the valley count if the level is zero.

        for(char c : s.toCharArray()){
            if(c == 'U') ++lvl;
            if(c == 'D') --lvl;
                    
            // if we just came UP to sea level
            if(lvl == 0 && c == 'U')
                ++v;
        

        I have a different issue with this code: it counts the valley only if it is climbed out of. Therefore, it would be wrong for any journey that ended in a valley. For example, DUDUD would respond 2, when the correct answer is 3. To count the valleys on entry, check elevation on descent:

        if (c == 'D') {
            if (elevation == 0)
                valley++;
            elevation--;     
        } else
            elevation++;
        
        • + 1 comment

          Actually, I've realized my mistake. I was failing to notice that the move was incremented first, then the current level and how it was obtained was checked. So, this should work just fine.

          As for the issue you brought up, it's not possible within the confines of the question. It was stated that all journies will begin and end at zero, so any valley entered will be exited, and thus registered.

          • + 0 comments

            ...and that's why I should start reading the instructions in their entirety, lol.

      • + 1 comment

        def countingValleys(n, s): l=list(s) count=0 up=0 down=0 for step in l: if step=='U': up+=1 if(up==down): count+=1 else: count+=0 else: down+=1 return count

        • + 0 comments
          You made it easy
          
      • + 1 comment

        will you please explain the above code?

        • + 1 comment

          Whenever you encounter a 'U' , increment count. And encounter 'D', decrement count. A valley ends at such a point when the count becomes 0 after encountering a 'U'. Thus increment valley_count when such a thing occurs

          • + 0 comments

            Thanks

      • + 0 comments

        i see a problem with your logic, if the first letter is U and the second letter is D your code will enter the elif hgt == 0 and its going to add a 1 in vallies even thought maybe next letter is another U so for example in [U,D,U,D] your code will add to vallies twice, even though you never actually entered a valley, just climbed two mountains, what you need to do is a try: and then see if the next letter is a D, if it true then you add 1 to valley, if not then just continue with the code

      • + 0 comments

        It worked for my test cases. Just take a look at it.

        Test Case Image

        Joe loves to travel. In her journey she notes 'U' when she travel from low to high (Uphill) and notes 'D' when she travels from high to low (down hill)

        Here high to low means from higher sea level to lower sea level low to high means from lower sea level to higher sea level

        when she travels above sea level it is a hill when she travels below sea level she travels a valley Count the number of valley she travelled

        see the image "6-valley.png" for example

        header('Content-type: application/json'); echo countingValleys('DDUUDDUDUUUD');

        function countingValleys($s) {

        counts and returns the number of valleys joe has travelled

        $inValley = false;
        
        $valleys = 0;
        
            $h = 0;
        
        for (`$step=0; $`step < strlen(`$s); $`step++) { 
            if(`$s[$`step] == 'U'){
                $h++;
            }else{
                $h--;
            }
            if(!$inValley){
                if($h < 0){
                    $inValley = true;
                }
            }
            else if($h == 0){
                $inValley = false;
                $valleys++;
            }
        }
        
        return $valleys;
        

        } }

        return $valleys;
        

        }

    • + 6 comments

      That's what I thought; For those who are in love with C++,

      int countingValleys(int n, string s) {
          int a=0,count=0;
          for(int i=0;i<s.length();i++)
          {
              if(s[i]=='U')
                  a++;
              else
                  a--;
              if(a==0 && s[i]=='U')
                  count++;
          }
          return count;
      }
      
      • + 0 comments

        same code in c isn't giving correct output?y?

      • + 0 comments

        what z "a" here you has taken?

      • + 0 comments

        You are using the length of the string to use your for loop, that will work as well as the number of steps n, since each step is a single letter in your String, but you should place n in that for loop and not the length of the string, since the specification gives you that value, if you dont put it, you are not considering the problem as someone could bring to you

      • + 1 comment

        This won't work for "UUUDDUUDDD"

           /\    /\
         /    \/    \
        _/            \_
        

        There should be one valley here right? This solution gives 0.

        • + 1 comment

          Actually not! The valley you are assuming is not a valley because it is above the sea level.

          Read the 2nd term in the problem: A valley is a sequence of consecutive steps below sea level...

          • + 0 comments

            Ohh yeah! Correct. Sorry my bad.

            Can you believe? I spent 3 hour using that as one of my test case.

      • + 0 comments

        How did you figure out that s[i] == 'U'?

      • + 0 comments

        Best of all, Thankyou

    • + 1 comment

      precise and easy to understand! amazing code!

    • + 1 comment

      10/10 solution. Simple,efficient and short.

      • + 0 comments

        thank you

    • + 0 comments

      same code in c is giving segmentation fault for some cases

      include

      include

      include

      include

      include

      include

      include

      int countingValleys(int n, char* s) { int count1=0; int count=0;
      for (int i=0;i

    • + 0 comments

      Thanks man !! It's Simple braining sol.

    • + 0 comments

      I compacted that a bit because for me, since you know that a valley will always come back up to sea level, you only care about the transition from 0 height to -1 height.

      static int countingValleys(int n, String s) { int height = 0; int valleyCount = 0; for(int i = 0; i < n; i++) { if(s.charAt(i) == 'D') { if(height == 0) { valleyCount++; } height--; } if(s.charAt(i) == 'U') { height++; } } return valleyCount; }

    • + 0 comments

      Wonderful solution

    • + 0 comments

      brilliant logic man

    • + 0 comments

      Brilliant

    • + 0 comments

      Brilliant

    • + 0 comments

      A Quick Tip:

      ++var and var++, both will result same in the above program, as there were not being assigned to any variable.

    • + 0 comments

      Kudos for using the foreach loop syntax! To save up space, the alternative String.charAt() is also an interesting improvement, and it's the one I used for my attempt.

    • + 1 comment

      Hi,

      Could you please help me understand the question first ? When i need to check count of comeback at sea level then why we need to check if(lvl == 0 && c == 'U') ++v;

      Though we can check it only with if(lvl == 0) ++v;

      Please help me to understand.

      • + 0 comments

        The condition check combo you mentioned has two parts to it: a) if lvl == 0 signifies if we are currently at sea level (but we don't know at which level we came from previously) b) if c == U means if we just climbed from a lower place to a higher one.

        A AND B results in the condition check: if we came back to sea level from a lower place, then we just came from a valley; thus, we add that valley into the number of valleys we already visited.

    • + 0 comments

      Good logic!

    • + 11 comments

      can any one can write simpler than this "python" land=0

      valley=0
      
      for i in s:
      
          if i=='U':
      
              land+=1
      
          if i=='D':
      
              land+=-1
      
          if land==0 and i=='U':
      
             valley+=1
      
      return valley
      
      • + 0 comments

        Best solution I've seen so far; very "Pythonic"

      • + 1 comment

        I had about the same solution. Isn't it necessary to declare your 'land'?

        level = 0
        val = 0
        for  move in s:
            if move == "U":
               level += 1
               if level == 0:
                   val += 1
            else:
               level -= 1
        return val
        
        • + 0 comments

          why you used this

          if level == 0: val += 1

      • + 1 comment

        Second if is of no use.. directly else would work. But Best program dude:)

        • + 0 comments

          yes, what you say is correct, BUT, considering the different test cases that might test this , you could get an input of TTTYYYUUUDDDDUUDD where T and Y are not U and D , and those could broke your method, if you doble check for U and D only , you are considering just those two letters, and that is what the problem suggests to check for.

      • + 0 comments

        brilliant solution!

      • + 1 comment

        Using your land==0 and i=='U' test

        def countingValleys(n, s):
            UD = {'U': 1, 'D': -1}
            sea_level = 0
            valley = 0
            for step in s:
                sea_level = sea_level + UD[step]
                if not sea_level and step == 'U':
                    valley += 1
            return valley
        
        • + 0 comments

          nice

      • + 0 comments

        Mindblown !!

      • + 0 comments

        mind blowing

      • + 0 comments

        Very succint

      • + 1 comment

        Did something similar:

        steps=0
        count_valleys=0
        
        for x in s:
            if steps==(-1) and x.upper()=='U':
                count_valleys+=1
            if x.upper()=='D':
                steps-=1
            elif x.upper()=='U':
                steps+=1
        
        return count_valleys
        
        • + 0 comments

          this is awesome bro

    • + 0 comments

      Awesome! simple and brilliant logic.

    • + 0 comments

      Awesome

    • + 0 comments

      Perfect solution.

      Just a side subtle question - what is the advantage of pre-incrementing the variable rather than post incrementing ? i.e. ++lvl vs lvl++, in general ?

    • + 0 comments

      Brilliant! I missed the && c == 'U' part in mine. Thanks

    • + 0 comments

      Awesome!!!!!!!!

    • + 0 comments

      how did you get this logic??

    • + 0 comments

      Simple and short.

    • + 1 comment

      But they didn't guaranteed that he will climb back to sea level from valley. Then how did you use this logic. What if he doesn't climb up the valley. Note: I used your logic and all test case is passed. Please Reply

      • + 1 comment

        valley condition occurs when he climbs up .this is basic knowledge

        • + 1 comment

          What if he doesn't climb up?.

          • + 1 comment

            doesn't occurs valley

            • + 1 comment

              As soon as he moves downside, valley counts. So the checking should be at starting of valley not at end of

              • + 0 comments

                the wording of the problem explains that a valley js created when the man returns to sea level from below it

    • + 0 comments

      if(lvl == 0 && c == 'U')

      Could you please Explain why You wrote c == 'U'?

    • + 0 comments

      great and simple one, super

    • + 1 comment

      What if the input is DDDDDDD Shouldnt it return a valley, but will it do so in the above code

      • + 0 comments

        The problem states that he always returns to sea level.

    • + 0 comments

      Good solution, be sure to give meaningful names to your variables. I wouldn't use 'v' or 'c', just for good practices.

    • + 0 comments

      GREAT SOLUTION.......i did not consider the fact that at the end of the journey we are always coming upwards to sea level

      so c=='U' in if(level==0 && c=='U')...... will eventually eliminate the cases where we are going upward from sealevel and then coming backwards to sealevel

    • [deleted]
      + 1 comment

      Please note that second if statement should replace by else if statement cause of same character at a time does not need double check!

      • + 0 comments

        if you double check you are considering the boundings of the problem, if you do an else after just checking 1 letter you could have TTZZZPPP or whatever letter there , and that is not what the problem suggest you to check for, its always a good practice if someone asks for something in a problem to give the code back with the exact request.

    • + 0 comments

      Nice and simple solution. We can avoid String.toCharArray() and use just one if else as the String contains only 'U' and 'D'. Count how many times Gary moved to vally from sea level. Example-

      static int countingValleys(int n, String s) {

          int valleyCount = 0;
          int currentState = 0;
      
          for(int i=0; i<s.length(); i++) {
              if(s.charAt(i)=='U') {
                  currentState++;
              } else {
                  currentState--;
                                  // Moved from sea level to vally
                  if(currentState == -1){
                      valleyCount++;
                  }
              }
          }
          return valleyCount;
      
      }
      
    • + 0 comments

      cool

    • + 1 comment

      what made u to find out " if we just came up to the sea level"??? . I got an idea upto incrementing and decrementing the levels.. but later i did not understand why u have checked for 3rd 'if' loop

      • + 0 comments

        We will have to "find and print the number of valleys Gary walked through". What is a valley? Vally is nothing but step below the sea level (no matter how many steps walked belew the sea level, it's just 1 vally until Gary comes back to sea level again). Whice is equvalent to moving from 0 (sea level) to -1 (one level below the sea).

        So third if is counting the the number of valleys (move from 0 to -1). We don't need to check the privious state as we got -1 after the decrement (0 - 1 = -1, it's possible only when Gary is moving from sea level to the below).

    • + 0 comments

      Great!

    • + 1 comment

      PHP Version:

      $pos = 0;
      $valleys = 0;
      
      foreach(str_split($s) as $step) {
      	$pos += $step === 'U' ? 1 : -1;
      	if($pos === 0 && $step === 'U')
      		$valleys++;
      }
      
      return $valleys;
      
      • + 0 comments

        (y)

    • + 0 comments

      i think this can be improved a little bit, lets say that you have count of 'D's that's greater than the half of the length of s. this will keep looping can u stop it since you will never be able to come to the sea level?

      if think you can do this

      if (lvl >= n / 2) return 0;

    • + 0 comments

      Any one please explain why c==='u' in the if condition? The level can be 0 at downward step also right?

    • [deleted]
      + 0 comments

      what about if case is DUDU?

    • + 0 comments

      if we use String s=sc.nextLine(); the output is 0. Can you please tell me why it's giving zero.

    • + 0 comments

      Brilliant. Thank you :)

    • + 0 comments

      well described.

    • + 1 comment

      100 % working code with video explanation -- All Test Case Passed..!!

      Here is the video explanation of my simple solution -

      https://youtu.be/MMmFELo0QjM

      and you can find most of the hackerrank solutions with video explaination here-

      https://github.com/Java-aid/Hackerrank-Solutions

      and many more needs to be addeed.

      Regards,

      Kanahaiya Gupta

      Git Hub URL | https://github.com/Java-aid/

      • + 1 comment

        It not true, I do not help me problem, I do not like your channel.

        • + 0 comments

          May i konw what is not true? what is the problem you have seen in my algo?

    • + 2 comments

      Similar slightly better(imho) C++ solution, but not while reading in chars

      int countingValleys(int n, string s)
      {
          int level = 0;
          int valleys = 0;
          for (char c : s)
          {
              if (c == 'D') --level;
              else if (++level == 0) ++valleys;
          }
          return (valleys);
      }
      
      • + 0 comments

        cool..(Y).

      • + 1 comment

        awesome

        • + 1 comment

          what?

          • + 1 comment

            the if statements are on point, I had a tough time communicating that simply.

            • + 1 comment

              did you saw the video tutorial?

              • + 1 comment

                it's great, thank you.

                • + 0 comments

                  If you dont mind can you please like, dislike or leave your feedback on my video. it motivates me and help other too find the solution over internet.

    • + 1 comment

      Simple and good approach. Thanks

      • + 0 comments

        hey just wanted to confirm you are talking about the video tutorial or something else..:)

    • + 0 comments

      @I0000

      I had a very similar solution, but I counted the valleys as we went below sea level instead of coming back up.

      static int countingValleys(int n, String s) { final int SEALVL = 0; int alt = 0; //current altitude int valleys = 0; //number of valleys

          for (int i = 0; i < n; i++){
              if (s.charAt(i) == 'D'){
                  if (alt == SEALVL) valleys++; //dipping into a valley
                  alt--;
              }
              if (s.charAt(i) == 'U') alt++;
          }
      
           return valleys;
      }
      
    • + 0 comments

      You can avoid doing the test lvl == 0 when Gary goes down and retest if c == 'U'.

      Domain : {U or D}

      Two less tests.

      Do like this :

      if(c == 'U') {
      
          ++lvl; 
      
          if(lvl == 0) 
      
              ++v;
      }
      
      else --lvl;
      
    • + 0 comments

      Nicely done, i was very close to a similar solution. Just couldnt quite figure out the right way to count the valleys

    • + 0 comments

      Hey here is my code for "how many time we came back to sea level"

      "UDDDUDUU".chars.map{|i| i == 'U' ? 1 : -1}.reduce([0]) { |a, v| a.push(a.last.to_i + v.to_i); a}.count(0) - 1

    • + 0 comments

      What will happen if the input is UUUDDD? Techically it is not a valley, but the programm will increment valley count since a sea level will be 0 at the end.

    • + 1 comment

      UDUD It gives 0 output why ? but there is 1 valley

      • + 0 comments

        you are right but there was a condition the valley must be dawnword. above the line valley will not be count.

    • + 1 comment

      It's cool. By the way, we have to check whether it is valley or not first before modifying the level. Don't we?

      static int countingValleys(int n, String s) {

      static int countingValleys(int n, String s) {
      
      
          int valleyNum = 0;
          int level = 0;
          for(char c : s.toCharArray()) {
      
              if(level ==0 && c=='D') {
                  valleyNum++;
              }
      
              if(c == 'D') {
                  level--;
              }
              else {
                  level++;
              }
          }
      
          return valleyNum;
      }
      
      • + 0 comments

        we can solve this problem by graph and i did exactly this

    • + 0 comments

      nice

    • + 0 comments

      char[] steps = s.ToArray(); int level = 0; int valleys = 0; for (int i =0;i

    • + 0 comments

      you explained the question in very simple way... thank you

    • + 1 comment

      the most optimized fastest code: c#

      static int countingValleys(int n, string s) {
        int sum = 0;
        int count = 0;
        for(int i=0;i<n;i++){
          if(s[i]=='U'){
            if(++sum==0)
              count++;
          }
          else sum--;
        }
        return count;
      }
      
      • + 0 comments

        Spammer

    • + 0 comments

      Thank you so much ! Helped a lot..

    • + 0 comments

      I ended up in a similar solution, but there's something that has bothered me for a while and it is the fact that when you go deep into a valley, you know that you must eventually come up, which means that if (|altitude| = remaining-steps ) then we know this is the last valley and there's no need to count the remaining steps.

      In a string of 10^6 characters, where the first half are 'D' and the second half 'U', we shouldn't need to sum the second half to know this is the final valley.

      Interestingly, that optimization was not necessary to pass the test and actually derailed my efforts for a while.

      My solution still suffers from that shortcoming.

      (defn- decode-step [s]
       (case s
        \U 1
        \D -1))
      
      (defn- valley? [[x y]]
       (and (= x -1) (= y 0)))
      
      (defn counting-valleys [n s]
       (let [hike (reductions + (map decode-step s))]
        (count (filter valley? (map vector hike (rest hike))))))
      
    • + 0 comments

      Great Logic

    • + 0 comments

      Brillant

    • + 0 comments

      nice

    • + 1 comment

      Javascript

      function countingValleys(n, s) {
          let seaLevel = 0, result = 0;
          for (let i = 0; i < s.length; i++) {
              seaLevel = (s[i] === 'U') ? seaLevel + 1 : seaLevel - 1;
              result = ((seaLevel === 0) && (s[i]==='U')) ? result+1 : result;
          }
          return result;
      }
      
      • + 0 comments

        Hola ! Sabrian decirme porqué mi código no soporta todas las pruebas ? (11/22) JavaScript:

        function countingValleys(n, s) {

        var result = Array.from(s).reduce((lvl,path)=> {

        path == "U" ? lvl+=1 : lvl-=1;
        lvl  == 0 && path == "U" ? lvl+=1 : "";      
        return lvl;
        },0
        );
        

        return result; }

        Y si se podría mejorarlo para seguir usando el método reduce(); Gracias!
        
    • + 0 comments

      Actually you dont need to track with two variables, you could use the same variable to track up and down and check at what point it becomes zero and use the condition that we are coming from below.

    • + 0 comments

      Simple and brilliant. How long it took in minutes to solve this? :)

    • + 1 comment

      Thankyou, well formed algo.I also though something similar to this but this one is better.

      • + 0 comments

        It's execellent, but more he content in spanish

    • + 0 comments

      Thanks

    • + 0 comments

      I also used same approach. Kudos.

    • + 0 comments

      Babbbooskha...nice one!

    • + 0 comments

      Counting Valley's problem solving is the task that is handled on this page. The clear idea of the topic explained with the proper example and tries to share some different types of agricultural technology facts codes to make it very clear for the readers.

    • + 1 comment

      anyone explain me the question first plzzzzzzzzzzzzzzz.

      • + 1 comment

        hey man it's nothing but in this problem you have to find out like how many mountains are created below the see level or downside the see level I hope this will help you

        • + 0 comments

          thank u bhaiiii.i understand now.

    • + 0 comments

      this working in symmertry for valley so, we consider count(v) which comes under when "U" with lvl == 0, not for "D"....

      i understood thanks,

    • + 0 comments

      tqsm buddy!

    • + 0 comments

      amazing

    • + 0 comments

      it's too simple solution dude.

    • + 0 comments

      nice solution but i recommend you to use if-else because you double check every time a step is taken. It's either up or down. Check my solution if you like! Cheers!

    • + 0 comments

      Awesome

    • + 0 comments

      Used the same approach. Works fine.

    • + 1 comment

      Other way to achieve result. But your solution is much cleaner.

          char[] path = s.toCharArray();
      
          int valleys = 0;
          int level = path[0] == 'U' ? 1 : -1;
          boolean enteredValley = level < 0;
          for(int i = 1; i < n; i++) {
              if(path[i] == 'U'){
                  level++;
              } else {
                  level--;
              }
      
              if(level < 0){
                  enteredValley = true;
              } else if(level == 0 && enteredValley) {
                  enteredValley = false;
                  valleys++;
              }
          }
          return valleys;
      }
      
      • + 0 comments

        Thanks. Still new at this and learning the complexity thing I have never used before. Some of the solutions are very interesting and make me learn new things. Thanks for the comment :)

    • + 0 comments

      I was stuck here, I just counted number of times we came back to surface, this is the reason my program was counting valleys even hicker came down from mountain to sea level. Thanks buddy...

    • + 0 comments

      had similar idea in python

      def countingValleys(n, s):
          g=0
          count=0
          for i in s:
              if i =='U':
                  g+=1
              else:
                  g-=1
              if g==0 and i=='U':
                  count+=1
          return count
      
    • + 1 comment

      I am a beginner. I am confused now. Can u plz tell me why are we checking c == 'U' in the last if statement. I did not get it.

      • + 0 comments

        for(int i=0;i

        In the above code, I have applied the condition that whenever there is upward trend, sum increases by 1 else decreases by 1. When Gary reaches sea level during upward trend and reaches sea level(sum = 0), it is counted as crossing a valley. So, D = -1; U = +1. We forget the Ds and focus on Us.

        i

    • + 0 comments

      this code fails for the test DDUUUUDD it gives a answer 1 whereas the answer should be 2 as per the problem statement

    • + 0 comments

      I tried the same logic in JS but it gives me only 0

    • + 0 comments

      Great!!!

    • + 0 comments

      Thank you. It was really helpful. It took long enough for me to figure it out. Your trick is very easy and understandable. Thank you very much.

    • + 0 comments

      Hi, I don't understand this. Can you please explain how is this code right for the input "DDDUUUUUUUDDDUUUDDDD". If the valley is determined by climbing down and climbing up to same level then there should 2 vallies in my case. Can you explain this?

    • + 0 comments

      Used your logic in Ruby - Thanks for the hint !!

      ar=s.split(''); newarr=Array.new; v=0; lvl=0; ar.each do |item| if item == 'U' lvl=lvl+1; else lvl=lvl-1; end if lvl==0 && item == 'U' v+=1; end end return v;

    • + 0 comments

      Same solution as above but using switch case instead.

       static int countingValleys(int n, String s) {
      
          int valleyCount = 0;
          int seaLevel = 0;
      
          for (int i = 0; i < n; i++) {
              switch(s.charAt(i)) {
                  case 'U':
                      seaLevel++;
                      if (seaLevel == 0) valleyCount++;
                      break;
                  case 'D':
                      seaLevel--;
                      break;
              }
          }
          return valleyCount;
      }
      
    • + 0 comments

      Actually, based on the problem statement, we can assume the hiker always returns to sea level so what you really want to do is count any down transition out of sea level (i.e. if(lvl == -1 && c == "D")). Your way, I think you could potentially miss a valley if the hiker never explictly reached sea level at the end.

    • + 0 comments

      Similar approach in python, was trying this for over 1 hour so forgot how I arrived at the solution 😂

      https://www.hackerrank.com/challenges/counting-valleys/forum/comments/818842

      Please suggest any glitch correction or code optimization if you don't mind! (Btw this solution passed all test cases, but just wondered whether it would other test cases apart from the 21 test cases given here)

    • + 0 comments

      Wow didn't think this problem could be solved so easily...Great work!

    • + 0 comments

      I used the same logic, but why write the condition to count valley separately, write it this way:

          int i, p=0, v=0;
          
          for(i=0;i<n;i++){
              if(s[i]=='U'){
                  p+=1;
                  v+=(p==0);
              }
              else
                  p-=1;
          }
          return v;
      
    • + 1 comment

      If not that each hike ends at sea level as declared in the question, this concept would have missed cases where hikes end within the valley like 'UDD', 'D', 'DD', etc

      • + 0 comments

        these hike are not valleys these will be mountains and we don't have to count them

    • + 0 comments

      excellent approach

    • + 0 comments

      hey bro i think this code won't work for this case 15 DUDUDUDUDUDDDD Just try this out

    • + 1 comment

      it says that starting will be a down first. how this condition statisfy?

      • + 0 comments

        okk thnx it was my mistake

    • + 0 comments

      your mindset is great.

    • + 0 comments

      I am just starting here in HackerRank:

      def countingValleys(steps, path): uc = 0 dc = 0 vel = False vc = 0 for s in path: if (s == 'D'): if(uc > 0): uc -= 1 else: dc += 1 vel = True elif (s == 'U'): if(dc > 0): dc -= 1 if (dc == 0): vc += 1 vel = False else: uc += 1 return vc

    • + 0 comments

      can you explain me the problem statement once.....

    • + 0 comments

      int n = sc.nextInt() is unused here! So if I provide 4 steps but path -> DDDDUU(6 steps) it is still going to accept the input and return 0! I think that's where the code fails.

    • + 0 comments

      Why do pre increment and pre decrements?

    • + 0 comments

      Why pre increment?

    • + 0 comments

      Same in py3 :)

      for x in range(steps-1):
              if path[x] == "U":
                  depth+=1
              else : depth-=1
              print(depth ,depth + int(path[x+1] == 'U'))
              if path[x+1] == 'U' and (depth + 1) ==0 :
                  valley+=1
          return valley 
      
    • + 0 comments

      Your logic is brilliant .How can i improve my logical ability and problem solving skills ? please give me suggestions and tips .Thanks in advance !

    • + 0 comments

      In case you all need the Golang version:

      // Akdira (c) Akmal Dirgantara 2021 (www.akdira.com)
      func countingValleys(steps int32, path string) int32 {
      	// Write your code here
      
      	pathList := strings.Split(path, "")
      	level := 0
      	var valleyTransversed int32 = 0
      
      	for _, onePath := range pathList {
      		if onePath == "U" {
      			level++
      		}
      
      		if onePath == "D" {
      			level--
      		}
      		if level == 0 && onePath == "U" {
      			valleyTransversed++
      		}
      
      	}
      	return valleyTransversed
      }
      
    • + 0 comments

      Thank U very much...I was stuck at the problem statement and could not figure it out that what it want to say..but..by read your code line that says..."We only care about the number of valleys... So just figure out the number of times you came back up to sea level." I understand and solved it..

    • + 0 comments

      Brilliant!

    • + 0 comments

      OMG I was using strange logics😂, and you solved it in such an easy way like a magic....

    • + 0 comments
      public static void main(String[] args) {
              Scanner sc = new Scanner(System.in);
              int n = sc.nextInt();
              String s = sc.next();
              
              int nOV = 0;     // no of valleys
              int altitude = 0;   // current level
              for(char c : s.toCharArray()){
                  if(altitude == 0 && c == 'D')
                  nOV++;
      	altitude= (c=='D')? --altitude : ++ altitude; 
      		}
      	System.out.println(nOV);
      	}
          
      				
      				
      				
           
      
    • + 0 comments

      Hey! Can you please explain the code logic.

    • + 0 comments

      @mandingaro I just wanted to know the output for the test case : 10 DDUUUUDDUD......here it crosses the sealevel twice but the output is one.

    • + 0 comments

      python3:

      def countingValleys(steps, path):
          height=0
          valleys=0
          for i in path:
              height=height+1 if i=='U' else height-1
              
              if height==0 and i=='U':
                  valleys+=1
                  
          return valleys
      
    • + 0 comments

      you should include the test lvl==0 in c=='D' to avoid test repitation and also minimize test quantity

      let level=0,res=0; for (let i=0;i

    • + 0 comments

      Didnt understand if this part, somebody please help - if(lvl == 0 && c == 'U')

    • + 0 comments

      Thanks a lot bro , applied your logic , happened in 1st attempt , used a variable to store the current position of the hiker and after every loop iteration of the path string added the new value of the position in a vector and from that vector checked for position 0 (sea level) and checked if the previous position was -ve(below sea level)

    • + 0 comments

      Why did you use Pre-increment? Is that make any difference to the above code?

      Because, I tried the same above with post-increment and post-decrement but it worked as expected.

    • + 0 comments

      Why did you use Pre-increment? Is that make any difference to the above code?

      Because, I tried the same above with post-increment and post-decrement in C++ but it worked as expected without any issues.

    • + 0 comments

      this is great. i figured the same logic soon but it took me so long to write it down and i made the code more complicated than it needed to be. im not used to dealing with char, so i used split() and transformed it in a string array, waste of time. thanks for your comment