Stacks and Monotonic Structures
35 / 170Stacks and Monotonic StructuresLesson 5 of 8About 45 min
Sort so that the collapse becomes local, then let a stack do the collapsing.
Here is the pattern on collisions. Values move right when positive and left when negative. Two that meet destroy the smaller in magnitude, or both if equal.
def survivors(moving): stack = [] for item in moving: alive = True while alive and stack and stack[-1] > 0 and item < 0: if stack[-1] < -item: stack.pop() # the older one loses, keep testing elif stack[-1] == -item: stack.pop() # both are destroyed alive = False else: alive = False # the incoming one loses if alive: stack.append(item) return stack print(survivors([5, 10, -5]))print(survivors([8, -8]))print(survivors([10, 2, -5]))Cars travel along a road toward a shared finish line at different speeds and cannot pass each other. You want to count how many distinct groups arrive. In which order should the cars be processed?
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.