Problem: Sort an Array of 0s, 1s, and 2s

Given an array/list ARR consisting of integers where each element is either 0, 1, or 2, your task is to sort this array in increasing order.

Input:

The input starts with an integer ‘T’ representing the number of test cases. 
For each test case:
The first line contains a positive integer ‘N’, denoting the number of elements in the array.
The second line contains ‘N’ space-separated integers, which are the elements of the array.

Output:

For each test case, output the sorted array of ‘N’ space-separated integers on a new line.

Example:

Input:
2
4
0 2 1 1
5
2 1 0 0 1
Output:
0 1 1 2
0 0 1 1 2
Explanation:

For the first test case, the sorted array is [0, 1, 1, 2].
For the second test case, the sorted array is [0, 0, 1, 1, 2].

Constraints:

  • 1 ≤ T ≤ 100
  • 1 ≤ N ≤ 5000
  • 0 ≤ ARR[i] ≤ 2
  • Time limit: 1 sec

Note:

You are not required to print anything; the output handling has already been managed. Simply implement the function to sort the array.
AnswerBot
4mo

Sort an array of 0s, 1s, and 2s in increasing order.

  • Use a three-pointer approach to partition the array into sections of 0s, 1s, and 2s.

  • Iterate through the array and swap elements based on their value...read more

Help your peers!
Select
Add answer anonymously...

VMware Software Software Developer interview questions & answers

A Software Developer was asked Q. Reverse the String Problem Statement You are given a string STR which contains a...read more
A Software Developer was asked Q. What are the stages in the Software Development Life Cycle?
A Software Developer was asked Q. Common Elements in Three Sorted Arrays Given three sorted arrays A, B, and C of ...read more

Popular interview questions of Software Developer

A Software Developer was asked Q1. Reverse the String Problem Statement You are given a string STR which contains a...read more
A Software Developer was asked Q2. What are the stages in the Software Development Life Cycle?
A Software Developer was asked Q3. Common Elements in Three Sorted Arrays Given three sorted arrays A, B, and C of ...read more
VMware Software Software Developer 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