Click here to Skip to main content
15,308,835 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
standard input/output: 2s/128000 kB

Given an array A of size N containing 0's, 1's and 2's. The task is to segregate the 0's, 1's and 2's in the array as all the 0's should appear in the first part of the array, 1's should appear in middle part of the array and finally all the 2's in the remaining part of the array.

Note: Do not use inbuilt sort function. Try to solve in O(N) per test case
The first line contains an integer T denoting the total number of test cases. Then T testcases follow.
Each testcases contains two lines of input. The first line denotes the size of the array N.
The second lines contains the elements of the array A separated by spaces.

1 <= T <= 100
1 <= N <= 100000
0 <= Ai <= 2

Sum of N for each test case does not exceed 10^5
For each testcase, in a newline, print the sorted array.


Input :
0 2 1 2 0
0 1 0

0 0 1 2 2
0 0 1

Testcase 1: After segragating the 0s, 1s and 2s, we have 0 0 1 2 2 which shown in the output.
Testcase 2: For the given array input, output will be 0 0 1.

What I have tried:

i have try to 9 times but big error in show my program.
Updated 19hrs ago
Dave Kreskowiak 18-Dec-21 0:00am
We can't help you if you don't show your code and the error messages you're getting.
Patrice T 18-Dec-21 2:10am
You have a secret error in your secret code.
Try to show your code.

While we are more than willing to help those that are stuck, that doesn't mean that we are here to do it all for you! We can't do all the work, you are either getting paid for this, or it's part of your grades and it wouldn't be at all fair for us to do it all for you.

So we need you to do the work, and we will help you when you get stuck. That doesn't mean we will give you a step by step solution you can hand in!
Start by explaining where you are at the moment, and what the next step in the process is. Then tell us what you have tried to get that next step working, and what happened when you did.

Just posting your homework question and saying "I tried" isn't going to get you anywhere.

If you are having problems getting started at all, then this may help: How to Write Code to Solve a Problem, A Beginner's Guide[^]
Hint: how many methods do you know that sort an array in O(N) ?
vector<int> solve(int n, vector<int> arr){
int low = 0;
int high = n-1;
int mid = 0;

while(mid <= high){
case 0:
swap(arr[mid++], arr[low++]);

case 1:

case 2:
swap(arr[mid++], arr[high--]);

return arr;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900