Skip to content

Commit bfd8472

Browse files
committed
Added Counting-Valleys problem solution
1 parent aab4ecd commit bfd8472

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Counting Valleys/main.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#!/usr/bin/env node
2+
3+
// Problem Description at -> https://www.hackerrank.com/challenges/counting-valleys/problem
4+
5+
function countingValleys(n, s) {
6+
let valleysCount = 0;
7+
let seaLevel = 0;
8+
9+
for (let i = 0; i < n; i++) {
10+
if (s[i] == 'D') seaLevel--;
11+
if (s[i] == 'U') seaLevel++;
12+
// Check if we just came from a valley up to sea level
13+
if (!seaLevel && s[i] == 'U') valleysCount++;
14+
}
15+
16+
return valleysCount;
17+
}
18+
19+
// // Test cases
20+
// console.log(countingValleys(8, 'UDDDUDUU')); // 1
21+
// console.log(countingValleys(8, 'UDUDUDUDU')); // 0, since there is no vallies crossed...
22+
// console.log(countingValleys(8, 'DDDUUUDDU')); // 1
23+
console.log(countingValleys(8, 'DDUUUUDD')); // 1
24+

0 commit comments

Comments
 (0)