Segregate 0s and 1 using 2 pointer Java
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. Modified array will be [0, 0, 0, 1, 1].
Input: arr[] = [1, 1, 1, 1]
Output: [1, 1, 1, 1]
Explanation: There are no 0s in the given array, so the modified array is [1, 1, 1, 1]
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)
//{ Driver Code Starts
// Initial Template for Java
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t;
t = Integer.parseInt(br.readLine());
while (t-- > 0) {
String line = br.readLine();
String[] tokens = line.split(" ");
// Create an ArrayList to store the integers
ArrayList<Integer> array = new ArrayList<>();
// Parse the tokens into integers and add to the array
for (String token : tokens) {
array.add(Integer.parseInt(token));
}
int[] arr = new int[array.size()];
int idx = 0;
for (int i : array) arr[idx++] = i;
new Solution().segregate0and1(arr);
for (int i = 0; i < array.size(); i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
// System.out.println("~");
System.out.println("~");
}
}
}
// } Driver Code Ends
// User function Template for Java
class Solution {
public static void swap(int a,int b)
{
int temp=a;
a=b;
b=temp;
}
void segregate0and1(int[] arr) {
// code here
int start=0;
int end=arr.length-1;
while(start <end)
{
if(arr[start]==0)
{
start++;
else
{
if(arr[end]==0)
{
swap(arr[start],arr[end]);
start++;
end--;
}
}
}
else
{
end--;
}
}
}
}
Comments
Post a Comment