Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Flood Area by Sim0000
from typing import List
def flood_area(diagram: str) -> List[int]:
current_height = max_height = 0
stack = [(current_height, 0, -1)] # height, area, index
for i, c in enumerate(diagram):
current_area = 0
if c == '\\':
current_height -= 1
elif c == '/':
current_height += 1
if current_height <= max_height:
while stack and stack[-1][0] < current_height:
_,area,_ = stack.pop()
current_area += area
else:
max_height = current_height
if stack and stack[-1][0] == current_height:
current_area += i - stack[-1][2] - 1
stack.append((current_height, current_area, i))
return [area for _,area,_ in stack if area]
if __name__ == '__main__':
print("Example:")
print(flood_area(r'\\//'))
assert flood_area(r'\\//') == [4], 'valley'
assert flood_area(r'/\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/') == [4, 2, 1, 19, 9], 'mountains'
assert flood_area(r'_/-\_') == [], 'hill'
print("Coding complete? Click 'Check' to earn cool rewards!")
Feb. 19, 2019