Build a prefix sum array in O(n) time, then answer each half-open range sum query in O(1) time in Java and Python. Problem and input contract Build a prefix array for a fixed sequence of n signed 32-bit integers. Each query uses zero-based bounds 0 ≤ left ≤ right ≤ n and returns the sum of elements from left up to right exclusive. For [3, −2, 5, 1] , [1, 3) returns 3 and [0, 4) returns 7 . The empty array supports [0, 0) , which returns 0 . Two maximum Java int values sum to 4294967294 . Worked example For [3, −2, 5, 1], the sum over [1, 3) is 3. Start with 0, then append 3, 1, 6, and 7. For [1, 3), subtract prefix[1] = 3 from prefix[3] = 6. The result is 3, the sum of −2 and 5. How the solution works Each prefix stores the sum before its index. Subtract the prefix ending before left from the prefix ending before right. Keep the initial zero so a range starting at index 0 uses the same subtraction. Require 0 ≤ left ≤ right ≤ n. Java uses long because sums can exceed int even wh...
Merge overlapping closed intervals with a sort-and-scan algorithm. See how Java and Python handle touching endpoints, nesting, and empty input. Problem and input contract Given pairs (start, end) with start ≤ end , return sorted, disjoint closed intervals with the same union. The functions preserve the input. [(5, 7), (1, 3), (3, 6)] gives [(1, 7)] . [(1, 9), (2, 4), (12, 12)] gives [(1, 9), (12, 12)] . Empty input gives an empty result. Worked example [(5, 7), (1, 3), (3, 6)] merges to [(1, 7)]. After sorting, process (1, 3) first. The next interval starts at 3, so it touches the first and extends it to (1, 6). The last interval starts at 5 and extends the end to 7. How the solution works Sorting by start means the last merged interval is the only candidate for overlap with the next input interval. Using max preserves the existing end when the new interval is contained. These are closed intervals, so equality counts as overlap. Sorting by start means a gap closes off all earlier ...