Introduction
Patience sort is one of the common sorting algorithms. This algorithm is inspired and named by the card game called Solitaire. An another variant of this algorithm is used to find the longest increasing subsequence in a given array, which is said to used in SQL Server, process control.
Little bit history from the below reference paper from David Aldous and Persi Diaconis, Patience sort was named by C.L. Mallows in early 1960's but was never published.
Time Complexity: O(N2)
Time Complexity using priority queue: O(N * log(N)) [Example is given below]
Auxiliary Space: O(N) [Auxiliary space means extra or temporary space used by the algorithm to process the logic]
Algorithm
- Rules
- Number can be added to the pile only if it is lesser than current number/card.
- If the existing piles does't meet the first rule, a new pile is created.
- Ideally the goal is to have list of lists holding sorted values, possibly lesser number of piles.
- Logic
- Involves two steps process, creation and merging of piles.
- Piles
- Initialize an empty 2D list with no piles.
- Loop through each number/card.
- First card forms a new pile consisting single number/card.
- Each subsequent card is placed in the leftmost (top) of the existing pile if the value is greater or equal to new number/card value.
- If the above rule fails, when it is unable to find greater element in any of the top values in the available piles, a new pile is created by adding the number/card on the top of the stack.
- Merge
- Given sorted arrays perform merge in k-way merge operation using priority queue (min-heap). As we would want to find the smallest element and followed by the next smallest. Let's say to find any element from the list this algorithm would not be suitable.
- Priority queue, is kind of queue data structure which additionally holds priority value for every element. There are different ways the priority could be defined. Such as :
- The largest element holds higher priority
- The smallest element holds higher priority
- In python we have predefined module available perform this operation, "heapq".
Visualization
![]() |
| Credits: https://assets.leetcode.com/users/images/4eb9f4c5-5612-4761-8da1-9f5e58e5d9ae_1616834711.464945.png |




















































