Sort an Array of 0s and 1s
Sort an array that contains only 0s and 1s, ensuring that the array is traversed only once to achieve the sorting.
Input:
T = number of test cases
N = size of the array for each test case
A = array containing only 0s and 1s
Output:
The sorted array for each test case, maintaining the order of 0s followed by 1s.
Example:
For the given array:
[0, 1, 1, 1, 0, 0, 1]
The output should be:
[0, 0, 0, 1, 1, 1, 1]
Constraints:
1 <= T <= 5
1 <= N <= 105
A[i] = 0
or1
Note:
The array should be sorted in place, meaning you do not need to return a new array, simply modify the given array.
AnswerBot
9d
Use two pointers approach to traverse the array and swap 0s and 1s to achieve sorting in place.
Initialize two pointers, one at the beginning and one at the end of the array.
Move the left pointer until...read more
Help your peers!
Add answer anonymously...
Popular interview questions of Software Engineer
>
Evoke Technologies Software Engineer Interview Questions
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