14(July) Segregate 0s and 1s
14. Segregate 0s and 1s
The problem can be found at the following link: Question Link
Problem Description
Given an array arr consisting of only 0's and 1's in random order, modify the array in-place to segregate 0s onto the left side and 1s onto the right side of the array.
Examples:
Input:
arr[] = [0, 0, 1, 1, 0]Output:
[0, 0, 0, 1, 1]Explanation: After segregation, all the 0's are on the left and 1's are on the right. The modified array will be [0, 0, 0, 1, 1].
My Approach
Initialization:
Create two pointers,
leftandright, both initialized to 0.leftwill track the position to place the next 0, andrightwill traverse the array.
Segregation Process:
Traverse the array using the
rightpointer.If
arr[right]is 0, swap it witharr[left]and incrementleft.Always increment
rightto continue traversing the array.
Return:
The array
arris modified in place with all 0s on the left and 1s on the right.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we traverse the array once.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for the pointers.
Code (C++)
Code (Java)
Code (Python)
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