Problem Description
Given an array of integers and a pivot value, rearrange the array so that all elements less than the pivot appear first, followed by elements equal to the pivot, and then elements greater than the pivot. The relative order of the elements less than or greater than the pivot must be maintained.
Key Insights
- Use three separate lists/arrays for elements less than, equal to, and greater than the pivot.
- Traverse the input array once to distribute elements into the respective lists.
- Concatenate the lists in order: less-than, equal-to, and greater-than.
- Maintain order preservation by appending elements in the order they are encountered.
Space and Time Complexity
Time Complexity: O(n), where n is the number of elements in the array. Space Complexity: O(n), due to the temporary storage for three sub-arrays.
Solution
The solution uses a simulation approach by making a single pass through the input array and partitioning the elements into three separate lists: one for values less than the pivot, one for values equal to the pivot, and one for values greater than the pivot. This preserves the original relative order of the elements. Finally, the three lists are concatenated into the final result.