Given an array arr[] consisting of only 0s, 1s, and 2s. Sort the array, i.e., put all 0s first, then all 1s and all 2s in last.
Go through the entire list and count how many times each number (0, 1, and 2) appears. Create a new list by filling it with the correct number of 0s, then 1s, and finally 2s based on the counts.
ls = [1, 2, 1, 0, 0, 2, 1, 1, 0] zero = 0 one = 0 two = 0 for item in ls: if item == 0: zero += 1 elif item == 1: one += 1 elif item == 2: two += 1 print([0] * zero + [1] * one + [2] * two)
const list = [1, 2, 1, 0, 0, 2, 1, 1, 0]; let zero = 0; let one = 0; let two = 0; for (let i of list) { if (i === 0) { zero++; } if (i === 1) { one++; } if (i === 2) { two++; } } console.log([...Array(zero).fill(0), ...Array(one).fill(1), ...Array(two).fill(2)]);