![]() |
VOOZH | about |
Given an integer array arr[]. The task is to calculate the minimum number of deques required to make the array sorted.
Example:
Input: arr[] = [3, 6, 0, 9, 5, 4]
Output: 2
Explanation: All elements can be placed into 2 deques while maintaining sorted order:
Start deque d1 with 3 β d1 = [3]
Start deque d2 with 6 β d2 = [6]
Push 0 to the front of d1 β d1 = [0, 3]
Push 9 to the back of d2 β d2 = [6, 9]
Push 5 to the front of d2 β d2 = [5, 6, 9]
Push 4 to the front of d2 β d2 = [4, 5, 6, 9]Input: arr[] = [50, 45, 55, 60, 65, 40, 70, 35, 30, 75]
Output: 1
Explanation: All elements can be placed into a single deque while maintaining sorted order:
Insert 50 β [50]
Push 45 to front β [45, 50]
Push 55 to back β [45, 50, 55]
Continue pushing to front or back as suitable β Final deque: [30, 35, 40, 45, 50, 55, 60, 65, 70, 75]
The idea is to use greedy insertion into the minimum number of deques such that each deque maintains a sorted order from front to back. The thought process is to iterate through the array and try to place each element at the front or back of an existing deque, only if doing so wonβt violate the potential future placements. This is done by checking if any intervening element would make the insertion invalid. If it can't fit into any existing deque, we create a new one.
Steps to implement the above idea:
2
Time Complexity: O(nΒ²), Each element may scan ahead in the array to check valid front/back insertion.
Space Complexity: O(n), Arrays fronts and backs may grow up to size n in worst case.