![]() |
VOOZH | about |
Given an array and a range [lowVal, highVal], partition the array around the range such that array is divided in three parts.
The individual elements of the three sets can appear in any order.
Input: arr[] = {1, 14, 5, 20, 4, 2, 54, 20, 87, 98, 3, 1, 32} , lowVal = 14 , highVal = 20
Output: arr[] = {1, 5, 4, 2, 1, 3, 14, 20, 20, 98, 87, 32, 54}
Explanation: all elements which are less than 14 are present in the range of 0 to 6
all elements which are greater than 14 and less than 20 are present in the range of 7 to 8
all elements which are greater than 20 are present in the range of 9 to 12Input: arr[] = {1, 14, 5, 20, 4, 2, 54, 20, 87, 98, 3, 1, 32} , lowVal = 20 , highVal = 20
Output: arr[] = {1, 14, 5, 4, 2, 1, 3, 20, 20, 98, 87, 32, 54}
The idea is based on Dutch National Flag based QuickSort. We traverse the given array of elements from left. We keep track of two pointers, first to store next position of smaller element (smaller than range) from beginning, and second to store next position of greater element from end. while traversing the array use these two pointers to place elements according to their range.
Follow the steps mentioned below to implement the idea:
Below is the implementation of the above approach:
Modified array 1 5 4 2 1 3 14 20 20 98 87 32 54
Time Complexity: O(N)
Auxiliary Space: O(1)