[
accumlate
array
]
Leetcode 0915 Partition Array into Disjoint Intervals
Problem statement
https://leetcode.com/problems/partition-array-into-disjoint-intervals/
Solution
Let us look more carefully at the phrase: every element in left is less than or equal to every element in right. Actually it means that maximum of the left part is less or equal than minimum of the right part. So, let us calculate the following arrays:
t1is accumulate maximum, starting from the left side.t2is accumulate minimum, starting from the right side.- Iterate throught these two arrays and find the first
i, wheret1[i-1] <= t2[i]: it will mean that we found exaclty the correct place.
Complexity
Time complexity is O(n), space complexity is O(n) as well.
Code
class Solution:
def partitionDisjoint(self, A):
t1 = list(accumulate(A, max))
t2 = list(accumulate(A[::-1], min))[::-1]
for i in range(1, len(A)):
if t1[i-1] <= t2[i]: return i