# Counting Valleys Hacker Rank Solution Best & Easiest Counting Valleys Hacker Rank Solution Best & Easiest

In this Counting Valleys Hacker Rank Problem, there is An avid hiker keeps meticulous records of their hikes. During the last hike that took exactly steps steps, for every step it was noted if it was an uphillU, or a downhillD step. Hikes always start and end at sea level, and each step up or down represents a 1 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 the sequence of up and down steps during a hike, find and print the number of valleys walked through.

## Counting Valleys Hacker Rank Solution

### Problem solution in Python programming:

```def countingValleys(steps, path):
level=0
valleys=0
for i in path:
if i == 'D':
level -= 1
else:
if level+1 == 0:
valleys += 1
level += 1

return valleys
```

### Problem solution in JavaScript programming:

```function countingValleys(steps, path) {
let altitude = 0, valleys = 0;

for (let step of path) {
if (step === 'U') {
if (altitude === -1) valleys++;
altitude++;
}
else altitude--;
}
return valleys;
}
```

### Problem solution in C++ programming:

```int countingValleys(int steps, string path) {
int valleys = 0;
int height = 0;
for (int i = 0; i < steps; i++) {
if (height == -1 && path[i] == 'U') valleys++;
if (path[i] == 'U') height++;
if (path[i] == 'D') height--;
}
return valleys;
}
```

### Problem solution in PHP programming:

```function countingValleys(\$steps, \$path) {
\$valleys = 0;
\$currentAltitude = 0;
for (\$i = 0; \$i < \$steps; \$i++) {
if (\$path[\$i] === 'U') {
\$currentAltitude++;
} else {
if (\$currentAltitude === 0) {
\$valleys++;
}
\$currentAltitude--;
}
}
return \$valleys;
}
```

### Problem solution in Go programming:

```package main

func countingValleys(steps int, path string) int {
valleys := 0
currentAltitude := 0
for i := 0; i < steps; i++ {
if path[i] == 'U' {
currentAltitude++
} else {
if currentAltitude == 0 {
valleys++
}
currentAltitude--
}
}
return valleys
}```