Skip to the page

JavaScript foundations for coding rounds · core

Arrays and strings in JavaScript

Most array and string problems are one pass with a few running variables, a prefix sum or a write pointer. In JavaScript, strings cannot be changed in place, so edit an array of characters and join it at the end, and keep every built-in call inside the loop O(1).

The notes

What you must know

  • One pass with running state: best-so-far, count, last seen. Kadane: cur = max(x, cur + x); best = max(best, cur). It handles all-negative arrays if you start from the first element.
  • Prefix sums: pre[i + 1] = pre[i] + a[i]; sum of a[l..r] = pre[r + 1] − pre[l]. 'Count subarrays with sum k' = for each prefix p, add count of (p − k) seen before (a Map of prefix counts, starting with {0: 1}).
  • Write pointer for in-place work: read with i, write with w (remove duplicates, move zeros). O(1) extra space.
  • Scan from the right when the answer depends on what comes after (leaders, next greater). Difference arrays turn many range updates into O(1) each (car pooling).
  • Strings: use char codes (s.charCodeAt(i) − 97) to index a 26-length count array; counting is O(n) while sorting characters is O(n log n).
  • Always test: empty input, one element, all equal, all negative, very long input.
  • Strings are immutable: s[0] = 'x' does nothing (in strict mode and in modules it throws a TypeError). To edit, take an array ([...s] or s.split('')), change it, and join('') once at the end.
  • length counts UTF-16 code units: '😀'.length is 2. [...s] and for...of walk by code point; s[i] and split('') walk by code unit. For plain a–z input this does not matter, but say so.

The red pen

Common traps: mistake → fix

  • Mistake: Kadane starting with best = 0 is fine

    Fix: it returns 0 for [-3, -1]; start with the first element.

  • Mistake: splice inside a loop is cheap

    Fix: each splice is O(n), so the loop becomes O(n²).

  • Mistake: Sorting characters is the only way to compare anagrams

    Fix: a 26-count array is O(n) and simpler to defend.

  • Mistake: for...in over an array is fine

    Fix: it gives string keys ('0', '1') and can include inherited properties; use for, for...of or forEach.

Easy to hard

Questions interviewers ask, easy to hard

  1. Find the maximum subarray sum. What is the complexity?
  2. What if all numbers are negative?
  3. Now the array is circular (LeetCode 918). What changes?
  4. Count subarrays whose sum is k, with negative numbers allowed.

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview