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 or 1

Note:

The array should be sorted in place, meaning you do not need to return a new array, simply modify the given array.

AnswerBot
4mo

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!
Select
Add answer anonymously...
Evoke Technologies Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits