C C++ JAVA PYTHON SQL HTML CSS DSA Robotics AWS CODING INTERVIEW PREPARATION

Made with & Code

# Sort an array of 0s, 1s, 2s

Written By -

## Brute Force Approach

### Using Sorting

Sort the given array using sort function.

TC – O(NlogN)

SC – O(1)

## Better Approach

### Using Hashmap

Keep the occurence count of 0s, 1s and 2s in a hashmap. Then iterate the given array and put all the 0s first, then 1s and then 2s according to the occurence count storedd in hash map.

TC – O(N)

SC – O(N)

## Optimal Approach

Count the number of 0s, 1s, 2s and store it in three diffrent variables respectively. Then iterate the given array and put all the 0s first, then 1s and then 2s according to the occurence count storedd in the variables.

``````#include<bits/stdc++.h>
using namespace std;

void printSorted012(int arr[], int arrSize){
int zeroCount = 0,
oneCount  = 0,
twoCount  = 0;

for(int i = 0; i < arrSize; i++){
if(arr[i] == 0) zeroCount++;
else if(arr[i] == 1) oneCount++;
else if(arr[i] == 2) twoCount++;
}

for(int i = 0; i < arrSize; i++){
if(zeroCount > 0){
arr[i] = 0;
cout<<arr[i]<<" ";
zeroCount--;
}else if(oneCount > 0){
arr[i] = 1;
cout<<arr[i]<<" ";
oneCount--;
}else if(twoCount > 0){
arr[i] = 2;
cout<<arr[i]<<" ";
twoCount--;
}
}
}

int main(){
int arr[] = {0,1,1,0,1,2,1,2,0,0,0,1};
int arrSize = sizeof(arr)/sizeof(arr);
printSorted012(arr, arrSize);
return 0;
}``````

TC – O(N)

SC – O(1)

Related Posts:

Online Compilers
{"ft_lang_label":"__label__en","ft_lang_prob":0.6180976,"math_prob":0.9969602,"size":1257,"snap":"2021-31-2021-39","text_gpt3_token_len":419,"char_repetition_ratio":0.12609737,"word_repetition_ratio":0.22966507,"special_character_ratio":0.36197296,"punctuation_ratio":0.17454545,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9964009,"pos_list":[0,1,2,3,4],"im_url_duplicate_count":[null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-09-17T02:14:19Z\",\"WARC-Record-ID\":\"<urn:uuid:54d9dac3-f857-41f5-9818-ae4be37167ea>\",\"Content-Length\":\"101290\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:51675b9c-03b4-4aad-98ec-46416c11c02d>\",\"WARC-Concurrent-To\":\"<urn:uuid:36764bee-20a3-4635-a066-f84270b84e01>\",\"WARC-IP-Address\":\"104.21.25.133\",\"WARC-Target-URI\":\"https://www.studymite.com/sort-an-array-of-0-1-2/?utm_source=home_recentpost&utm_medium=home_recent\",\"WARC-Payload-Digest\":\"sha1:DLP2UN3U5LVINLU33WH6TZS5LU2WRGXO\",\"WARC-Block-Digest\":\"sha1:HBQKHFZ6MFAB4RFN7KHCDL6HUO654YLK\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-39/CC-MAIN-2021-39_segments_1631780053918.46_warc_CC-MAIN-20210916234514-20210917024514-00651.warc.gz\"}"}