Sort 0 and 1 Problem Statement
Given an integer array ARR
of size N
containing only integers 0 and 1, implement a function to sort this array. The solution should scan the array only once without using any additional arrays.
Input:
The first line contains an integer 't', denoting the number of test cases or queries to be run.
The next t
lines contain:
- An integer 'N' representing the size of the array/list in each test case.
- 'N' single space-separated integers (all 0s and 1s) representing the elements in the array.
Output:
For each test case, print the sorted array elements in one row, separated by a single space.
Output for every test case will be printed on a separate line.
Example:
Input:
2
5
0 1 1 0 1
3
1 0 0
Output:
0 0 1 1 1
0 0 1
Constraints:
1 <= t <= 10^2
0 <= N <= 10^5
- Time Limit: 1 sec
Note:
You need to modify the given array/list itself. No need to return or print anything within the function.
AnswerBot
1y
The function sorts an integer array containing only 0s and 1s in linear time complexity.
Use two pointers, one starting from the beginning and the other from the end of the array.
Swap the elements at t...read more
Ajay kumar
2mo
package Arrays; public class Sort_0_and_1 { public static void sort(int[] nums){ int i =0,j=0; while(j<nums.length){ if(nums[j]==0){ int temp = nums[j]; nums[j]=nums[i]; nums[i]=temp; i++; } j++; }...read more
Pooja Tiwari
4mo
public static void sortZeroesAndOne(int[] arr) { int i=0 , j=arr.length-1; while(i!=j) { if(arr[i]==1 && arr[j]==0) { arr[i] =0; arr[j] =1; } if(arr[i]!=1) i++; if(arr[j]!=0) j--; } }
Balaji Birajdar
5d
public static void sortZeroesAndOne(int[] arr) { int i = 0, j = arr.length - 1; while (i < j) { if (...read more
Shaikh Mohd Saqib
3mo
It should be while(i<j)
while(i!=j) will give error at some point
Add answer anonymously...
Deloitte Java Developer interview questions & answers
A Java Developer was asked 4w agoQ. What is the difference between an abstract class and an interface?
A Java Developer was asked 4w agoQ. How is a singleton class created?
A Java Developer was asked 3mo agoQ. What are the differences between an ArrayList and a LinkedList?
Popular interview questions of Java Developer
A Java Developer was asked 1mo agoQ1. What is the difference between an abstract class and an interface?
A Java Developer was asked 1mo agoQ2. How is a singleton class created?
A Java Developer was asked 3mo agoQ3. What are the differences between an ArrayList and a LinkedList?
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app