AlgoDaily Solution
1var assert = require('assert');
2
3function swap(arr, first, second) {
4 var temp = arr[first];
5 arr[first] = arr[second];
6 arr[second] = temp;
7}
8
9function dutchNatFlag(arr) {
10 let low = 0;
11 let mid = 0;
12 let high = arr.length - 1;
13
14 while (mid <= high) {
15 if (arr[mid] === 0) {
16 swap(arr, low++, mid++);
17 } else if (arr[mid] === 2) {
18 swap(arr, mid, high--);
19 } else if (arr[mid] === 1) {
20 mid++;
21 }
22 }
23
24 return arr;
25}
26
27dutchNatFlag([2, 2, 2, 0, 0, 0, 1, 1]);
28
29try {
30 assert.deepEqual(dutchNatFlag([2, 0, 1, 0, 2]), [0, 0, 1, 2, 2]);
31
32 console.log(
33 'PASSED: assert.deepEqual(dutchNatFlag([2, 0, 1, 0, 2]), [0, 0, 1, 2, 2]);'
34 );
35} catch (err) {
36 console.log(err);
37}
38
39try {
40 assert.deepEqual(dutchNatFlag([0, 1, 2]), [0, 1, 2]);
41
42 console.log(
43 'PASSED: ' + 'assert.deepEqual(dutchNatFlag([0, 1, 2]), [0, 1, 2]);'
44 );
45} catch (err) {
46 console.log(err);
47}
48
49try {
50 assert.deepEqual(
51 dutchNatFlag([2, 0, 0, 1, 1, 0, 2, 2]),
52 [0, 0, 0, 1, 1, 2, 2, 2]
53 );
54
55 console.log(
56 'PASSED: assert.deepEqual(dutchNatFlag([2, 0, 0, 1, 1, 0, 2, 2]), [0, 0, 0, 1, 1, 2, 2, 2]);'
57 );
58} catch (err) {
59 console.log(err);
60}
Community Solutions
Community solutions are only available for premium users.
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.
xxxxxxxxxx
44
var assert = require('assert');
function swap(arr, first, second) {}
function dutchNatFlag(arr) {
// Fill in this method
return arr;
}
dutchNatFlag([2, 2, 2, 0, 0, 0, 1, 1]);
try {
assert.deepEqual(dutchNatFlag([2, 0, 1, 0, 2]), [0, 0, 1, 2, 2]);
console.log(
'PASSED: assert.deepEqual(dutchNatFlag([2, 0, 1, 0, 2]), [0, 0, 1, 2, 2]);'
);
} catch (err) {
console.log(err);
}
try {
assert.deepEqual(dutchNatFlag([0, 1, 2]), [0, 1, 2]);
console.log(
'PASSED: ' + 'assert.deepEqual(dutchNatFlag([0, 1, 2]), [0, 1, 2]);'
);
OUTPUT
Results will appear here.