The diver's log
- O(n) · Medium
- Full plan
- Python
- JavaScript
- strings
- loops
Problem
Underwater, the time matters less than the depth, and Irene's watch keeps track of it: a - for every meter she goes down and a + for every meter she comes up. A dive starts when she leaves the surface and ends when she gets back to it; any ups and downs in between, without surfacing, belong to the same dive.
Write a function that takes the day's log, a string of - and +, and returns how many dives she made (a whole number). The log always starts and ends at the surface, and never goes above it. With "--+-++" she goes down 2, up 1, down 1 and up 2: she surfaces only once, so it is 1 dive. With "-+-+" it is 2. An empty log is a day without diving: 0.
Examples
The example
"--+-++" → 1
Two short dives
"-+-+" → 2
A single dive, straight down and up
"---+++" → 1
Three dives of different depths
"-+--++-+" → 3
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def dives(log):
passJavaScript
function dives(log) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.