Skip to content

Commit f523138

Browse files
committed
Segregate 0s and 1s
1 parent 45f28d8 commit f523138

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

CircularQueue.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ class CircularQueue {
3535

3636
const queue = new CircularQueue(5);
3737

38-
queue.enqueue(10);
38+
queue.enqueue(10);
3939
queue.enqueue(20);
4040
queue.enqueue(30);
4141
queue.enqueue(40);

Segregate0sand1s.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// You are given an array of 0s and 1s in random order.
2+
// Segregate 0s on left side and 1s on right side of the array
3+
// [Basically you have to sort the array]. Traverse array only once.
4+
5+
// Approach 1 (The array is traversed multiple times)-->Not Efficient
6+
function Segregate0sand1s(arr) {
7+
let length = arr.length;
8+
let count0 = 0;
9+
10+
for (let i = 0; i < length; i++) {
11+
if (arr[i] === 0) {
12+
count0++;
13+
}
14+
}
15+
16+
for (let i = 0; i < count0; i++) {
17+
arr[i] = 0;
18+
}
19+
for (let i = count0; i < length; i++) {
20+
arr[i] = 1;
21+
}
22+
console.log(arr);
23+
}
24+
25+
const arr = [0, 1, 0, 1, 0, 1, 0, 0, 0, 1];
26+
Segregate0sand1s(arr);
27+
28+
// Approach 2()-->Efficient
29+
30+
function Segregate0sand1s(arr) {
31+
let low = 0;
32+
let high = arr.length - 1;
33+
34+
while (low < high) {
35+
while (arr[low] == 0 && low < high) low++;
36+
37+
while (arr[high] == 1 && low < high) high--;
38+
39+
if (low < high) {
40+
arr[low] = 0;
41+
arr[high] = 1;
42+
low++;
43+
high--;
44+
}
45+
}
46+
return arr;
47+
}
48+
49+
const arr = [0, 1, 0, 1, 0, 1, 0, 0, 0, 1];
50+
console.log(Segregate0sand1s(arr));

0 commit comments

Comments
 (0)