21(April) Three way partitioning
21. Three-Way Partitioning
The problem can be found at the following link: Question Link
Problem Description
Given an array of size (n) and a range ([a, b]), partition the array around the range such that the array is divided into three parts:
All elements smaller than (a) come first.
All elements in the range (a) to (b) come next.
All elements greater than (b) appear in the end.
Note: The individual elements of the three sets can appear in any order. Return 1 if you modify the given array successfully.
Example:
Input:
n = 5
array[] = {1, 2, 3, 3, 4}
[a, b] = [1, 2]Output:
1Explanation: One possible arrangement is: {1, 2, 3, 3, 4}. If you return a valid arrangement, the output will be 1.
My Approach
Initialization:
Initialize two pointers,
leftandright, pointing to the start and end of the array respectively.
Partitioning:
Iterate through the array using a loop variable
i.If
array[i]is less than (a), swaparray[i]witharray[left]and increment bothleftandi.If
array[i]is greater than (b), swaparray[i]witharray[right]and decrementright.Otherwise, increment
i.
Return:
Return 1 if the array is successfully partitioned according to the given conditions.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we iterate through the array once.
Expected Auxiliary Space Complexity: O(1), as we use only a constant amount of additional space.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated