Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Sort 0 1 2

Easy
0/40
Average time to solve is 22m
profile
Contributed by
1248 upvotes
Asked in companies
HCL TechnologiesWalmartOptum

Problem statement

You have been given an integer array/list(ARR) of size 'N'. It only contains 0s, 1s and 2s. Write a solution to sort this array/list.

Note :
Try to solve the problem in 'Single Scan'. ' Single Scan' refers to iterating over the array/list just once or to put it in other words, you will be visiting each element in the array/list just once.
Detailed explanation ( Input/output format, Notes, Images )
Input format :
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then the test cases follow.

The first line of each test case contains an Integer 'N' denoting the size of the array/list.

The second line of each test case contains 'N' space-separated Integers denoting the array/list.
Output format :
For each test case/query, print the sorted array/list(ARR) as space-separated Integers.

Output for every test case will be printed in a separate line.
Note:
You need to change in the given array/list itself. Hence, no need to return or print anything.
Constraints :
1 <= T <= 10
1 <= N <= (5 * (10 ^ 5))
0 <= ARR[i] <= 2

Where 'N' is the size of the given array/list.
And, ARR[i] denotes the i-th element in the array/list.

Time Limit: 1sec 
Sample Input 1 :
2
6
0 1 2 2 1 0
7
0 1 2 1 2 1 2
Sample Output 1 :
0 0 1 1 2 2
0 1 1 1 2 2 2
Sample Input 2 :
2
7
2 2 2 1 1 1 0
6
2 1 2 0 1 0
Sample Output 2 :
0 1 1 1 2 2 2
0 0 1 1 2 2
Hint

Can try to find the sorting algorithm of best time Complexity.

Approaches (3)
Sorting

Use any good sorting algorithm like Merge Sort, Quick Sort or inbuilt sorting function of different languages.

  • Sort the Array and just return.
Time Complexity

O(N*log(N)), where ‘N’ is the size of the array.

We are using inbuilt sort algorithm which has Overall Time Complexity O(N*log(N))

Space Complexity

O(1), As we are using constant space.

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Sort 0 1 2
All tags
Sort by
Search icon

Interview problems

Dutch national flag algorithm

We can have 3 pointers: low, mid and high. low and high are at the either ends of the array and mid traverses through it. If element at mid == 0, we swap it with low pointer, if element at mid == 1, we simply move forward else it is 2 for which we swap it with high pointer. The loop runs till mid≤high.

2 views
0 replies
0 upvotes

Interview problems

why is the program printing an extra 0 at the beginning of the output

#include <bits/stdc++.h> 

void swap(int &m,int &n)

{

   int temp=m;

   m=n;

   n=temp;

}

void sort012(int *arr, int n)

{

 

   for(int i=0;i<n;i++)

   {

      for(int j=0;j<n;j++)

      {

         if(arr[i]<arr[j])

         swap(arr[i],arr[j]);

      }

   }

   

      for (int k = 0; k < n; k++) {

         cout << arr[k] << " ";

         break;

      }

   

}

 

45 views
0 replies
0 upvotes

Interview problems

sort012

 

#include <bits/stdc++.h> 

void sort012(int *arr, int n)

{

   //   Write your code here

   int temp1,temp2;

   for(int i=0;i<n-1;i++)

   {

      if(arr[i]>arr[i+1])

      {

         temp1 = arr[i];

         arr[i] = arr[i+1];

         arr[i+1] = temp1;

      }

 

      while(i>0 && arr[i]<arr[i-1])

      {  

          temp2 = arr[i];

         arr[i] = arr[i-1];

         arr[i-1] = temp2;

         i--;

 

      }

   }

}

126 views
0 replies
0 upvotes

Interview problems

Sort 0 1 2

import java.util.* ;

import java.io.*; 

public class Solution 

{

    public static void sort012(int[] arr)

    {

       int low=0,mid=0,high=arr.length-1;

       while(mid<=high){

           if(arr[mid]==0){

               int temp=arr[low];

               arr[low]=arr[mid];

               arr[mid]=temp;

               low++;

               mid++;

           }else if(arr[mid]==1){

               mid++;

           }else{

               int temp2=arr[mid];

               arr[mid]=arr[high];

               arr[high]=temp2;

               high--;

           }

       }

    }

}

74 views
0 replies
1 upvote

Interview problems

My rookie solution

//I created new array and I would traverse around the given array and if I saw 0 then I would put it in consecutively in indexes starting from 0 and if I saw 2 then I would put that backwardly starting from index N-1 and remaining places I would fill them with 1.

 

 

 

 

 

#include <bits/stdc++.h> 

void sort012(int *arr, int n)

{

   int new_arr[n];

   int j=0, k=n-1;

   for(int i=0; i<n; i++){

      if(arr[i]==0){

         new_arr[j]=0;

         j++;

      }

      if(arr[i]==2){

         new_arr[k]=2;

         k--;

      }

      

   }

   for(int l=j; l<k+1; l++){

      new_arr[l]=1;

   }

   for(int i=0; i<n; i++){

      arr[i]=new_arr[i];

   }

}

63 views
0 replies
0 upvotes

Interview problems

using DNF - Dutch National Flag Algorithm

int low = 0;

        int mid = 0;

        int high = arr.length-1;

 

        while(mid<=high) {

            if (arr[mid] == 0) {

                int temp = arr[low];

                arr[low] = arr[mid];

                arr[mid] = temp;

                low++;

                mid++;

            }

            else if (arr[mid] == 1) {

                mid++;

            }

            else if (arr[mid] == 2) {

                int temp = arr[high];

                arr[high] = arr[mid];

                arr[mid] = temp;

                high--;

            }

        }

109 views
0 replies
0 upvotes

Interview problems

c++ shortest way to solve

#include <bits/stdc++.h> 

#include<algorithm>

void sort012(int *arr, int n)

{

   //   Write your code here

  sort(arr , arr+n);

//this function sort the array from start to end where //n represents no. of elements

}

144 views
0 replies
0 upvotes

Interview problems

solve in "single line " Check it out.............

import java.util.* ;

import java.util.concurrent.ArrayBlockingQueue;

import java.io.*; 

public class Solution 

{

    public static void sort012(int[] arr)

    {

        //Write your code here 

      Arrays.sort(arr);

       

    }

}

46 views
0 replies
0 upvotes

Interview problems

o(n) complexity

int x=0,y=0,z=0,j=0;

    for (int i = 0; i < n; i++)

    {

        if(arr[i]==0) x++;

        else if (arr[i]==1) y++;

        else  z++;

    }

 

    while(x){

        arr[j++] = 0;

        x--;

    }

    while(y){

        arr[j++] = 1;

        y--;

    }

    while(z){

        arr[j++] = 2;

        z--;

    }

71 views
0 replies
0 upvotes

Interview problems

sort 0 1 2

#include <bits/stdc++.h>

void sort012(int *arr, int n)

{

int c1=0;

int c2=0;

int c3=0;

for(int i=0;i<n;i++){

if(arr[i]==0){

c1++;

}

else if(arr[i]==1){

c2++;

}

else{

c3++;

}

}

int index=0;

for(int i=0;i<c1;i++){

arr[index]=0;

index++;

}

for(int i=0;i<c2;i++){

arr[index]=1;

index++;

}

for (int i = 0; i < c3; i++) {

arr[index] = 2;

index++;

}

 

}

void print(int arr[],int n){

for (int i = 0; i < n; i++) {

cout << arr[i] << " ";

}

}

 

88 views
0 replies
0 upvotes
Full screen
Console