VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-number-of-deques-required-to-make-the-array-sorted/

⇱ Minimum deques to make array sorted - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum deques to make array sorted

Last Updated : 24 Mar, 2026

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]

Approach:

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:

  • Initialize two arrays: fronts and backs to track front and back values of all current deques.
  • Loop through each element in the input arr and try to insert it into an existing deque.
  • For each arr[i], first check if it can be pushed at the front of any deque by comparing with fronts[j].
  • If valid for front insertion, update fronts[j] and mark the element as inserted.
  • If not inserted, check if it can be pushed at the back of any deque using the same logic with backs[j].
  • If neither insertion is valid, create a new deque by adding the element to both fronts and backs.
  • After traversing the entire array, return the size of fronts, which gives the minimum number of deques required.

Output
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.


Comment
Article Tags: