← Back to JavaScript, page 9

javascript-0166 · Easy fresher

How do you solve common array warm-ups: rotate an array, find the second largest value, find a missing number, and merge two sorted arrays?

Rotate with slice and modulo or three reversals, find the second largest in one pass by tracking the two best values, find the missing number in 0..n by comparing the expected sum or using XOR, and merge sorted arrays with two indexes in O(n + m). State the edge cases: empty input, duplicates, negative values, and k larger than the length.

Full answer

These problems appear in screens because each has a clean linear solution and several traps.

Rotate right by k: use k % n first, so large k works and an empty array does not divide by zero. A simple answer is arr.slice(-k).concat(arr.slice(0, -k)) with care for k === 0 (since slice(-0) returns the whole array). An in-place version reverses the whole array, then the first k items, then the rest, using O(1) extra space.

Second largest: sorting works in O(n log n) but one pass is better. Keep first and second as -Infinity. For each value, if it is greater than first, move first to second and set first; else if it is greater than second and different from first, set second. Decide how to treat duplicates (distinct second largest or not) and what to return when it does not exist.

Missing number in 0..n (array has n numbers, one missing): the expected sum is n * (n + 1) / 2, so the answer is the expected sum minus the actual sum. XOR gives the same result without any risk of large sums: XOR all indexes and values; pairs cancel and the missing one remains. Both are O(n) time and O(1) space. For sums, mention that values stay exact in doubles up to 2 to the 53.

Merge two sorted arrays: keep indexes i and j, push the smaller head, then append what is left. It is O(n + m). Use <= to keep it stable. Do not use concat plus sort, which is O(n log n) and, without a numeric comparator, sorts as strings.

Also common: finding duplicates with a Set, flattening with recursion, and chunking.

Interview habit: ask about input size and duplicates, write the simple solution first, then improve and name the complexity.

javascript
function rotateRight(array, k) {
  if (array.length === 0) return [];
  const shift = ((k % array.length) + array.length) % array.length;
  return shift === 0 ? array.slice() : array.slice(-shift).concat(array.slice(0, -shift));
}

function rotateInPlace(array, k) {
  const n = array.length;
  if (n === 0) return array;
  k = ((k % n) + n) % n;
  const reverse = (from, to) => {
    for (; from < to; from++, to--) [array[from], array[to]] = [array[to], array[from]];
  };
  reverse(0, n - 1);
  reverse(0, k - 1);
  reverse(k, n - 1);
  return array;
}

function secondLargest(numbers) {
  let first = -Infinity;
  let second = -Infinity;
  for (const n of numbers) {
    if (n > first) {
      second = first;
      first = n;
    } else if (n > second && n < first) {
      second = n;
    }
  }
  return second === -Infinity ? undefined : second;
}

const missingBySum = (numbers) => (numbers.length * (numbers.length + 1)) / 2 - numbers.reduce((a, b) => a + b, 0);
function missingByXor(numbers) {
  let result = numbers.length;
  numbers.forEach((value, index) => { result ^= index ^ value; });
  return result;
}

function mergeSorted(a, b) {
  const out = [];
  let i = 0;
  let j = 0;
  while (i < a.length && j < b.length) out.push(a[i] <= b[j] ? a[i++] : b[j++]);
  while (i < a.length) out.push(a[i++]);
  while (j < b.length) out.push(b[j++]);
  return out;
}

console.log(rotateRight([1, 2, 3, 4, 5], 2), rotateRight([1, 2, 3], 0), rotateRight([1, 2, 3], 7), rotateRight([1, 2, 3], -1), rotateRight([], 3));
console.log(rotateInPlace([1, 2, 3, 4, 5, 6, 7], 3), rotateInPlace([1], 5));
console.log(secondLargest([3, 9, 4, 9, 1]), secondLargest([5, 5]), secondLargest([7]), secondLargest([-1, -5, -3]), secondLargest([]));
console.log(missingBySum([3, 0, 1]), missingByXor([3, 0, 1]), missingBySum([0, 1]), missingByXor([9, 6, 4, 2, 3, 5, 7, 0, 1]));
console.log(mergeSorted([1, 4, 9], [2, 3, 10, 11]), mergeSorted([], [1]), mergeSorted([5, 5], [5]));
console.log([10, 9, 1].concat([2]).sort(), [10, 9, 1, 2].sort((a, b) => a - b));

Run with Node.js v24.22.1 as js-166.js; two runs gave identical output. Output: [ 4, 5, 1, 2, 3 ] [ 1, 2, 3 ] [ 3, 1, 2 ] [ 2, 3, 1 ] [] [ 5, 6, 7, 1, 2, 3, 4 ] [ 1 ] 4 undefined undefined -3 undefined 2 2 2 8 [ 1, 2, 3, 4, 9, 10, 11 ] [ 1 ] [ 5, 5, 5 ] [ 1, 10, 2, 9 ] [ 1, 2, 9, 10 ]

Key points

  • Rotate: normalize k with modulo; slice and concat, or three in-place reversals.
  • Second largest: one pass with two variables; decide how to treat duplicates and short arrays.
  • Missing number: expected sum minus actual sum, or XOR; both O(n) time, O(1) space.
  • Merge sorted arrays with two pointers in O(n + m); do not concat and sort.
  • Clarify edge cases and state complexity.

Common mistakes

  • Forgetting k % n, or dividing by zero for an empty array.
  • Sorting to find the second largest when a single pass is enough.
  • Returning the largest value as the second largest for arrays with duplicates, without stating the rule.
  • Merging with concat and the default sort.

Follow-ups

  • How would you rotate a linked list or a matrix?
  • How would the second largest solution change for the kth largest?
  • How would you find two missing numbers?

Tips

  • Ask about duplicates, negative numbers, and empty input.
  • Offer the simple answer first, then the improved one.
  • Say the complexity of each version.