Coding Problem: Array GFG ( Leve 1) Sort 0s,1,s,2s.

Approach 1:

Sort the Array --> nlogn time complexity

Best Approach

Counter for 0,1,2 and then traverse the array and put the element in the array time complexity --> n

Solution



import java.io.*;
import java.util.*;


 // } Driver Code Ends
//User function template for Java

class Solution
{
    public static void sort012(int a[], int n)
    {
        // code here 
        int zeroCounter=0,oneCounter=0,twoCounter=0;

        for(int arrElement: a) {

            if(arrElement==0) {
                zeroCounter++;
            }
            else if (arrElement==1){
                oneCounter++;
            }
            else {
                twoCounter++;
            }
        }


        for(int i=0;i<zeroCounter;i++) {
            a[i]=0;
        }

        for(int j=zeroCounter;j<zeroCounter+oneCounter;j++){
            a[j]=1;
        }

        for(int k=zeroCounter+oneCounter;k<n;k++){
            a[k]=2;
        }


    }
}