Arrays and Hashing
11 / 170Arrays and HashingLesson 6 of 10About 49 min
When each position needs to know about everything on its left and everything on its right, take two directed passes.
Nothing says the sweep has to go left to right. A backward sweep gives you, at each position, a summary of everything to its right. Two sweeps give you both sides.
Here is the shape, using running maxima rather than sums so that the mechanism is visible on its own.
def max_on_each_side(nums): n = len(nums) left = [None] * n # largest value strictly to the left of i right = [None] * n # largest value strictly to the right of i running = None for i in range(n): left[i] = running if running is None or nums[i] > running: running = nums[i] running = None for i in range(n - 1, -1, -1): right[i] = running if running is None or nums[i] > running: running = nums[i] return left, right print(max_on_each_side([3, 1, 4, 2]))Build the general tool before using the specific one. prefix_sums returns an array of length n+1 where position i is the sum of the first i elements, so it starts with 0. range_sum uses it to answer the sum from index i to j inclusive in constant time. count_ranges_equal counts how many ranges in the given list of (i, j) pairs sum to the target.
Tests
p = prefix_sums([1, 2, 3, 4, 5])print(p)print(range_sum(p, 0, 4), range_sum(p, 1, 3), range_sum(p, 2, 2))print(count_ranges_equal([1, 2, 3, 4, 5], [(0, 1), (1, 2), (0, 4), (3, 3), (4, 4)], 5))print(prefix_sums([]))Output
Run tests to see output.
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.