These are the notes for JavaScript Coding Questions, episode 6, interview and placement practice for people who finished the SyntaxPilot JavaScript course. Three array questions every interviewer loves: reverse an array in place, rotate it by k steps, and remove duplicates. The obvious attempts give us a swap loop that runs perfectly and changes nothing, a rotation that takes most of a second, and a duplicate remover that silently deletes NaN.
Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.
Every program was run with Node.js 24 (node main.js), the SyntaxPilot compiler's JavaScript command, and every output below is real. Plain modern JavaScript, no packages.
About the timings. Lines like
pop + unshift: 727.04msare copied from a real run on one machine. Times vary; what matters is the size of the gap.
In place
An algorithm works in place when it changes the input array itself, using only a few extra variables (O(1) extra space), and never builds a second array. It matters when the array is huge (50,000 rows you don't want to copy twice) and when other code holds a reference to the same array and should see the change.
Q1: Reverse an array in place
Problem. [1, 2, 3, 4, 5] → [5, 4, 3, 2, 1], changing the same array.
Think out loud
- Item i belongs at its mirror position j = n - 1 - i.
- Edge cases: odd and even lengths, one item, empty.
The obvious attempt: swap every i with its mirror
function reverseInPlace(arr) {
for (let i = 0; i < arr.length; i++) {
const j = arr.length - 1 - i;
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
const a = [1, 2, 3, 4, 5];
reverseInPlace(a);
console.log(a);
Output:
[ 1, 2, 3, 4, 5 ]
Unchanged. At i = 0 we swap positions 0 and 4: [5, 2, 3, 4, 1]. At i = 1 we swap 1 and 3: [5, 4, 3, 2, 1], already reversed. But the loop keeps going: at i = 3 it swaps 3 and 1 again, at i = 4 it swaps 4 and 0 again, putting every pair back. Every pair is swapped twice.
[arr[i], arr[j]] = [arr[j], arr[i]] is a swap with array destructuring: the right side is built from the old values first, then both are assigned.
Two pointers
Real-life picture. Five friends on a bench want to sit in reverse order. The two at the ends swap seats, then the next two in from each end, and they stop when they meet in the middle (with an odd number, the middle friend doesn't move). Each pair swaps exactly once. Two positions moving towards each other like this is the two pointers technique.
function reverseInPlace(arr) {
let left = 0, right = arr.length - 1;
while (left < right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
}
for (const a of [[1, 2, 3, 4, 5], [1, 2, 3, 4], [7], []]) {
reverseInPlace(a);
console.log(a);
}
Output:
[ 5, 4, 3, 2, 1 ]
[ 4, 3, 2, 1 ]
[ 7 ]
[]
For the empty array right starts at -1, so left < right is false and nothing happens. Time O(n) (n / 2 swaps), space O(1).
The built-ins: reverse() and toReversed()
const b = [1, 2, 3];
const c = b.toReversed();
console.log(b, c);
const d = b.reverse();
console.log(b, d === b);
[ 1, 2, 3 ] [ 3, 2, 1 ]
[ 3, 2, 1 ] true
toReversed()(ES2023) returns a reversed copy; the original is untouched.reverse()reverses the array in place and returns the same array.
Every variable that points to the array sees the change:
const a = [1, 2, 3];
const alias = a;
a.reverse();
console.log(alias);
const copy = [...a].reverse();
console.log(a, copy);
console.log([1, 2, 3].reverse() === [1, 2, 3].reverse());
[ 3, 2, 1 ]
[ 3, 2, 1 ] [ 1, 2, 3 ]
false
alias and a are two names for one array. The last line is false because two array literals are two different objects, even with the same contents.
Q2: Rotate an array right by k
Problem. Move every item k places to the right; items that fall off the end wrap around to the front. [1, 2, 3, 4, 5], k = 2 → [4, 5, 1, 2, 3].
Real life. A weekly duty roster in a hostel: everyone's job shifts one place each week (see the mini project).
Think out loud
- Rotating by n (the length) changes nothing, so rotating by 7 on 5 items = rotating by 2.
- Edge cases: k = 0, k = n, k > n, a negative k (a left rotation), a huge array.
First attempt: pop + unshift, k times
function rotate(arr, k) {
for (let step = 0; step < k; step++) arr.unshift(arr.pop());
}
const a = [1, 2, 3, 4, 5];
rotate(a, 2);
console.log(a);
const big = Array.from({ length: 100000 }, (_, i) => i);
console.time("pop + unshift");
rotate(big, 50000);
console.timeEnd("pop + unshift");
console.log(big[0], big[99999]);
Output:
[ 4, 5, 1, 2, 3 ]
pop + unshift: 727.04ms
50000 49999
Correct, but slow. pop() removes the last item (O(1)); unshift(x) inserts at index 0, so every other item moves up one place (O(n)). Done k times: O(n·k).
Second attempt: slice + concat
const rotate = (arr, k) => arr.slice(-k).concat(arr.slice(0, -k));
console.log(rotate([1, 2, 3, 4, 5], 2));
console.log(rotate([1, 2, 3, 4, 5], 7));
console.log(rotate([1, 2, 3, 4, 5], 0));
[ 4, 5, 1, 2, 3 ]
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5 ]
slice(-k) is the last k items and slice(0, -k) everything before them. Fast, but k = 7 gives the array unchanged: slice(-7) on 5 items is all 5 items and slice(0, -7) is empty. (k = 0 happens to work: slice(-0) is slice(0), the whole array.) It also builds new arrays, so it isn't in place.
The reversal trick
Real-life picture: a train. Coaches 1 2 3 4 5; the last two must come to the front.
start 1 2 3 4 5
1) reverse all 5 4 3 2 1 the last k are in front, backwards
2) reverse first k 4 5 3 2 1
3) reverse the rest 4 5 1 2 3 done
function reverse(arr, left, right) {
while (left < right) { [arr[left], arr[right]] = [arr[right], arr[left]]; left++; right--; }
}
function rotate(arr, k) {
const n = arr.length;
if (n === 0) return;
k = ((k % n) + n) % n;
reverse(arr, 0, n - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, n - 1);
}
for (const k of [2, 7, 0, 5, -1]) {
const a = [1, 2, 3, 4, 5]; rotate(a, k); console.log(k, a);
}
const big = Array.from({ length: 100000 }, (_, i) => i);
console.time("reversal"); rotate(big, 50000); console.timeEnd("reversal");
console.log(big[0], big[99999]);
Output:
2 [ 4, 5, 1, 2, 3 ]
7 [ 4, 5, 1, 2, 3 ]
0 [ 1, 2, 3, 4, 5 ]
5 [ 1, 2, 3, 4, 5 ]
-1 [ 2, 3, 4, 5, 1 ]
reversal: 3.856ms
50000 49999
Why ((k % n) + n) % n? In JavaScript % keeps the sign of the left side, so -1 % 5 is -1. Adding n and taking % n again maps it to 4 (rotating right by 4 = left by 1):
console.log([1, 2, 3, 4, 5].slice(-2), [1, 2, 3, 4, 5].slice(0, -2), [1, 2, 3].slice(-0));
console.log(-1 % 5, ((-1 % 5) + 5) % 5, 7 % 5);
[ 4, 5 ] [ 1, 2, 3 ] [ 1, 2, 3 ]
-1 4 2
(For k = 0, reverse(arr, 0, -1) does nothing, so the two outer reversals cancel out.)
Complexity. Each item is moved at most twice: O(n) time, O(1) space.
Q3: Remove duplicates
Problem. Keep the first copy of each value, in the original order. [3, 1, 3, 2, 1] → [3, 1, 2].
Real life. Merging the contacts from two phones: every number should appear once.
The obvious attempt: filter + indexOf
const unique = arr => arr.filter((x, i) => arr.indexOf(x) === i);
console.log(unique([3, 1, 3, 2, 1]));
console.log(unique([1, NaN, 2, NaN]));
const big = Array.from({ length: 100000 }, (_, i) => i % 50000);
console.time("filter + indexOf");
console.log(unique(big).length);
console.timeEnd("filter + indexOf");
Output:
[ 3, 1, 2 ]
[ 1, 2 ]
50000
filter + indexOf: 2.030s
indexOf(x) is the first index of x, so indexOf(x) === i means "this is x's first appearance". Two problems:
- Every
NaNis deleted.
console.log(NaN === NaN, [NaN].indexOf(NaN), [NaN].includes(NaN));
false -1 true
NaN is the only value not equal to itself. indexOf compares with ===, so it never finds NaN and returns -1, which never equals i. includes (and Set, Map) use SameValueZero, which treats NaN as equal to NaN (and +0 equal to -0).
- O(n²). For each of n items,
indexOfscans from the start: about n²/2 steps, ten billion for 100,000 items.
The fix: a Set
Real-life picture. A wedding guard who re-reads the whole guest list for every arrival is slow; a register where each name appears once can be checked at a glance. A Set is a collection that holds each value only once; checking it (has) or adding to it (add) takes O(1) on average, because it is stored as a hash table, not a list to scan.
const unique = arr => [...new Set(arr)];
console.log(unique([3, 1, 3, 2, 1]));
console.log(unique([1, NaN, 2, NaN]));
console.log(unique([1, "1", 1]), unique([[1], [1]]));
const big = Array.from({ length: 100000 }, (_, i) => i % 50000);
console.time("Set");
console.log(unique(big).length);
console.timeEnd("Set");
Output:
[ 3, 1, 2 ]
[ 1, NaN, 2 ]
[ 1, '1' ] [ [ 1 ], [ 1 ] ]
50000
Set: 4.738ms
- A Set keeps values in insertion order, so the first copies stay in order.
- One
NaNis kept. 1and"1"are different values (different types).[1]and[1]are two different arrays: objects and arrays are compared by reference (are they the same object in memory?), not by contents. To remove duplicate objects, choose a key (practice question 3).
Complexity: O(n) time, O(n) space for the Set.
Complexity summary
| Question | Approach | Time | Extra space | Notes |
|---|---|---|---|---|
| Reverse | swap every i with its mirror | O(n) | O(1) | wrong: swaps twice |
| Reverse | two pointers | O(n) | O(1) | |
| Reverse | toReversed() |
O(n) | O(n) | a copy |
| Rotate | pop + unshift, k times |
O(n·k) | O(1) | 727 ms for n = 10⁵, k = 5·10⁴ |
| Rotate | slice + concat |
O(n) | O(n) | wrong for k > n without k % n |
| Rotate | three reversals | O(n) | O(1) | 3.9 ms |
| Dedupe | filter + indexOf |
O(n²) | O(n) | drops NaN; 2 s for 10⁵ |
| Dedupe | [...new Set(arr)] |
O(n) | O(n) | 4.7 ms |
Common mistakes (and the exact outputs)
| Mistake | Code | What you see | Why | Fix |
|---|---|---|---|---|
| Swap across the whole array | for (i = 0; i < n; i++) swap(i, n-1-i) |
[ 1, 2, 3, 4, 5 ] |
every pair swapped twice | while (left < right) |
reverse() on shared data |
a.reverse() |
alias changes too |
in place, same array returned | toReversed() or [...a].reverse() |
unshift in a loop |
arr.unshift(arr.pop()) × k |
727.04ms |
each unshift moves every item | three reversals |
Forgetting k % n |
slice(-7) on 5 items |
[ 1, 2, 3, 4, 5 ] |
rotating by n does nothing | k = ((k % n) + n) % n |
Negative k with % |
-1 % 5 |
-1 |
% keeps the sign |
((k % n) + n) % n |
filter + indexOf |
arr.indexOf(x) === i |
NaN removed; 2.030s |
NaN !== NaN; O(n²) |
[...new Set(arr)] |
| A Set of objects | new Set(contacts) |
duplicates stay | compared by reference | dedupe by a key |
Mini project: a weekly duty roster
Rotate the duties one step every week.
// Weekly duty roster: rotate the list one step each week
function reverse(arr, l, r) { while (l < r) { [arr[l], arr[r]] = [arr[r], arr[l]]; l++; r--; } }
function rotate(arr, k) {
const n = arr.length;
if (n === 0) return;
k = ((k % n) + n) % n;
reverse(arr, 0, n - 1); reverse(arr, 0, k - 1); reverse(arr, k, n - 1);
}
const duties = ["Cooking", "Cleaning", "Shopping", "Laundry"];
const people = ["Asha", "Ravi", "Neha", "Arjun"];
for (let week = 1; week <= 3; week++) {
console.log(`Week ${week}: ` + people.map((p, i) => `${p}: ${duties[i]}`).join(" | "));
rotate(duties, 1);
}
Week 1: Asha: Cooking | Ravi: Cleaning | Neha: Shopping | Arjun: Laundry
Week 2: Asha: Laundry | Ravi: Cooking | Neha: Cleaning | Arjun: Shopping
Week 3: Asha: Shopping | Ravi: Laundry | Neha: Cooking | Arjun: Cleaning
Extend it: print the roster for any week number w directly with rotate(copy, w - 1), without looping through the earlier weeks.
Your turn: remove duplicates from a sorted array, in place (solution)
Problem. The array is sorted, so equal values sit next to each other. Remove the duplicates in place with O(1) extra space and return the new length k; the first k items must be the unique values. [1, 1, 2, 3, 3, 3, 4] → 4, [1, 2, 3, 4].
Solution
A reader walks every item; a writer marks where the next unique value goes. An item is new if it differs from the last value written.
function removeDuplicatesSorted(arr) {
if (arr.length === 0) return 0;
let write = 1;
for (let read = 1; read < arr.length; read++) {
if (arr[read] !== arr[write - 1]) arr[write++] = arr[read];
}
return write;
}
for (const a of [[1, 1, 2, 3, 3, 3, 4], [5, 5, 5], [1, 2, 3], []]) {
const k = removeDuplicatesSorted(a);
console.log(k, a.slice(0, k));
}
const b = [1, 1, 2];
const k = removeDuplicatesSorted(b);
b.length = k;
console.log(b);
4 [ 1, 2, 3, 4 ]
1 [ 5 ]
3 [ 1, 2, 3 ]
0 []
[ 1, 2 ]
Setting arr.length = k cuts the leftover tail off. Time O(n), space O(1). (It works only because the array is sorted; for an unsorted array use a Set.)
Practice questions (with solutions)
1. Rotate left by k.
Solution
The same three reversals in a different order (or rotate right by n - k):
function reverse(arr, left, right) {
while (left < right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
}
function rotateLeft(arr, k) {
const n = arr.length;
if (n === 0) return;
k = ((k % n) + n) % n;
reverse(arr, 0, k - 1);
reverse(arr, k, n - 1);
reverse(arr, 0, n - 1);
}
for (const k of [2, 7, 0]) { const a = [1, 2, 3, 4, 5]; rotateLeft(a, k); console.log(k, a); }
2 [ 3, 4, 5, 1, 2 ]
7 [ 3, 4, 5, 1, 2 ]
0 [ 1, 2, 3, 4, 5 ]
2. Is an array a palindrome? (reads the same both ways)
Solution
function isPalindrome(arr) {
let left = 0, right = arr.length - 1;
while (left < right) {
if (arr[left] !== arr[right]) return false;
left++;
right--;
}
return true;
}
console.log(isPalindrome([1, 2, 3, 2, 1]), isPalindrome([1, 2, 2, 1]), isPalindrome([1, 2, 3]), isPalindrome([]));
true true false true
Two pointers again, stopping at the first mismatch. O(n) time, O(1) space.
3. Remove duplicate objects by their id.
Solution
const contacts = [
{ id: 7, name: "Asha" },
{ id: 3, name: "Ravi" },
{ id: 7, name: "Asha (work)" },
{ id: 9, name: "Neha" },
];
console.log(new Set(contacts).size);
function uniqueById(items) {
const seen = new Set();
return items.filter(item => {
if (seen.has(item.id)) return false;
seen.add(item.id);
return true;
});
}
console.log(uniqueById(contacts).map(c => c.name).join(", "));
const lastWins = [...new Map(contacts.map(c => [c.id, c])).values()];
console.log(lastWins.map(c => c.name).join(", "));
4
Asha, Ravi, Neha
Asha (work), Ravi, Neha
A Set of the objects keeps all 4 (each object is a different reference). Keep a Set of ids instead: first copy wins. The Map one-liner keeps the last copy of each id (a later set overwrites), in the position where the id first appeared.
Quick quiz
1. (From the video.) What does this print?
const s = new Set([1, "1", 1, NaN, NaN]);
console.log(s.size);
(A) 2 (B) 3 (C) 4 (D) 5
Answer
(B) 3: 1, "1" and one NaN. The second 1 is a repeat, "1" is a different type, and a Set treats NaN as equal to NaN (SameValueZero).
2. After const a = [1, 2, 3]; const b = a; b.reverse();, what is a?
Answer
[3, 2, 1]: a and b are the same array, and reverse() works in place.
3. Rotating [1, 2, 3, 4, 5, 6] right by 8 gives?
Answer
8 % 6 = 2, so [5, 6, 1, 2, 3, 4].
Interview questions
- What does "in place" mean? The input is modified directly with O(1) extra space; no second array.
- Reverse an array in place. Two pointers from both ends, swap, step inwards, stop when
left >= right. O(n), O(1). - Difference between
reverse()andtoReversed()?reversemutates and returns the same array;toReversedreturns a new array. - Rotate by k in O(n) time and O(1) space.
k %= n, reverse all, reverse the first k, reverse the rest. - Why is
unshiftslow? It inserts at index 0, so every item moves: O(n) per call. - Remove duplicates from an array.
[...new Set(arr)]: O(n), keeps the first occurrences in order. - Why is
filter+indexOfa bad dedupe? O(n²), and it drops everyNaNbecauseindexOfuses===. - What is SameValueZero? The equality used by
includes,SetandMap: like===, exceptNaNequalsNaN. - How do you dedupe objects? By a key (id) with a Set of keys, or a Map from key to object.
- Remove duplicates from a sorted array in O(1) space. Reader and writer pointers; compare with the last value written.
Glossary
| Term | Meaning | Example |
|---|---|---|
| In place | Changing the input itself with O(1) extra space | two-pointer reverse |
| Reference | A variable's link to an object; two variables can share one array | const alias = a |
| Mirror index | The position at the same distance from the other end | n - 1 - i |
| Two pointers | Two indexes moving through an array, often from both ends | left, right |
| Array destructuring swap | Swapping two items in one statement | [a[i], a[j]] = [a[j], a[i]] |
reverse() |
Reverses in place and returns the same array | [1, 2, 3].reverse() |
toReversed() |
Returns a reversed copy (ES2023) | b.toReversed() |
| Rotate right by k | Move every item k places right, wrapping around | [4, 5, 1, 2, 3] |
pop() |
Removes and returns the last item; O(1) | [1, 2].pop() is 2 |
unshift(x) |
Inserts at index 0; O(n) | arr.unshift(0) |
slice(a, b) |
A copy of items a to b - 1; negative counts from the end | slice(-2) |
concat |
Joins arrays into a new array | [1].concat([2]) |
Remainder (%) |
Keeps the sign of the left side in JavaScript | -1 % 5 is -1 |
| Reversal trick | Rotate with three in-place reversals | reverse all, first k, rest |
| Duplicate | A value that appears more than once | the second 3 |
filter |
Keeps the items for which a function returns true | arr.filter(x => x > 0) |
indexOf |
First index of a value using ===, or -1 |
[NaN].indexOf(NaN) is -1 |
NaN |
"Not a Number"; the only value not equal to itself | NaN === NaN is false |
| SameValueZero | Equality used by includes, Set, Map: NaN equals NaN |
[NaN].includes(NaN) |
Set |
A collection that holds each value once, in insertion order | new Set([3, 1, 3]) |
| Hash table | Storage that finds an item by its key in O(1) on average | how Set and Map work |
Spread (...) |
Expands an iterable into items | [...new Set(arr)] |
| Compare by reference | Two objects are equal only if they are the same object | [1] === [1] is false |
| Reader / writer pointers | One index reads every item, one marks where to write | sorted dedupe |
| O(n·k) | Work grows with n times k | unshift k times |
| O(n²) | Work grows with the square of n | indexOf inside filter |
Summary
- In place means no second array, O(1) extra space.
- Reverse: two pointers that swap and step inwards until they meet; swapping every i with its mirror swaps each pair twice and changes nothing.
reverse()mutates;toReversed()copies. - Rotate:
unshiftin a loop is O(n·k);slicebreaks for k > n. Takek = ((k % n) + n) % n, then three reversals: O(n) time, O(1) space. - Remove duplicates:
[...new Set(arr)]is O(n), keeps order and keeps oneNaN;filter+indexOfis O(n²) and deletesNaN. Objects are compared by reference: dedupe them by a key.
Next episode: Array questions III: the missing number from 1 to n (sum and XOR), counting frequencies with a Map, and the majority element with Boyer-Moore voting.