09. Sort 0s, 1s, and 2s
The problem can be found at the following link: Question Link
Note: Sorry for uploading late, my exam is going on.
Problem Description
Given an array arr containing only 0s, 1s, and 2s, sort the array in ascending order.
Example:
Input:
arr = [0, 2, 1, 2, 0]Output:
0 0 1 2 2Explanation: 0s, 1s, and 2s are segregated into ascending order.
Input:
arr = [0, 1, 0]Output:
0 0 1Explanation: 0s, 1s, and 2s are segregated into ascending order.
My Approach
Three-Pointer Approach:
Use three pointers
low,mid, andhighto partition the array into three segments: 0s, 1s, and 2s.
Initialization:
lowandmidpointers start at the beginning of the array, while thehighpointer starts at the end of the array.
Partitioning:
Iterate through the array using the
midpointer:If
arr[mid]is0, swaparr[mid]witharr[low], increment bothlowandmid.If
arr[mid]is1, simply move themidpointer forward.If
arr[mid]is2, swaparr[mid]witharr[high]and decrementhigh.
Final Array:
After the loop, the array will be sorted in ascending order with all
0s,1s, and2s in their respective positions.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where
nis the length of the array. Each element is processed at most once.Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for pointers.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit my LinkedIn:- Any Questions. Thank you for your input; together, we strive to create a space where learning is a collaborative endeavor.
⭐ Star this repository if you find it helpful or intriguing! ⭐
📍Visitor Count
Last updated