Skip to content

Expert · Interview preparation and career · topic 60 of 61 · 30 min

Data-structure questions in JavaScript

Explanation

Most coding rounds include data-structure and algorithm (DSA) problems. A handful of patterns solve the majority: hash maps for counting and lookups (two-sum, anagrams), two pointers on sorted data, sliding windows over subarrays, stacks for matching brackets, and binary search on sorted arrays. Always state the time and space complexity.

Why patterns?

There are thousands of practice problems online, but they reuse a small number of ideas. Recognising the pattern is most of the work. JavaScript gives you the tools directly: Map and Set for hashing, arrays as stacks (push/pop), and plain index variables for pointers and windows.

1. Hash map: two-sum

javascript
// Return indexes of two numbers that add up to target. O(n) time, O(n) space.
function twoSum(nums, target) {
  const seen = new Map();             // value → index
  for (let i = 0; i < nums.length; i++) {
    const need = target - nums[i];
    if (seen.has(need)) return [seen.get(need), i];
    seen.set(nums[i], i);
  }
  return null;
}
console.log(twoSum([2, 7, 11, 15], 9)); // [0, 1]

2. Counting: anagrams

javascript
function isAnagram(a, b) {
  if (a.length !== b.length) return false;
  const count = new Map();
  for (const ch of a) count.set(ch, (count.get(ch) ?? 0) + 1);
  for (const ch of b) {
    if (!count.get(ch)) return false;
    count.set(ch, count.get(ch) - 1);
  }
  return true;
}
console.log(isAnagram('listen', 'silent')); // true

3. Two pointers on sorted data

With a sorted array, start one pointer at each end. If the sum is too small, move the left pointer right; if too big, move the right pointer left. O(n) time and O(1) extra space.

4. Sliding window

javascript
// Maximum sum of k consecutive days of sales. O(n).
function maxWindowSum(sales, k) {
  let sum = 0;
  for (let i = 0; i < k; i++) sum += sales[i];
  let best = sum;
  for (let i = k; i < sales.length; i++) {
    sum += sales[i] - sales[i - k];   // slide: add the new day, drop the old one
    best = Math.max(best, sum);
  }
  return best;
}
console.log(maxWindowSum([4, 2, 9, 1, 7, 3], 3)); // 17 (9 + 1 + 7)

5. Stack: balanced brackets

javascript
function isBalanced(s) {
  const pairs = { ')': '(', ']': '[', '}': '{' };
  const stack = [];
  for (const ch of s) {
    if ('([{'.includes(ch)) stack.push(ch);
    else if (ch in pairs) {
      if (stack.pop() !== pairs[ch]) return false;
    }
  }
  return stack.length === 0;
}
console.log(isBalanced('{[()]}'), isBalanced('(]')); // true false

On a sorted array, compare with the middle element and discard half each step: O(log n). Watch the loop condition (lo <= hi) and the updates (mid + 1, mid - 1) to avoid infinite loops and off-by-one errors.

PatternClue in the problemTypical complexity
Hash map / Set"find a pair", "count", "duplicates", "seen before"O(n) time, O(n) space
Two pointerssorted input, pairs, palindromesO(n) time, O(1) space
Sliding window"subarray / substring of length k", "longest/shortest window"O(n)
Stackmatching brackets, undo, "next greater element"O(n)
Binary searchsorted input, "find the first/last", "minimum that works"O(log n)
Careful: Do not forget to say the complexity, and do not claim O(n) when your loop calls includes, indexOf or splice inside it; those are O(n) each, making the total O(n²).
Think of it like this: These patterns are like the standard moves in carrom. Once you know the cut shot and the rebound, every new board position is a matter of picking the right move, not inventing one from scratch.
Tip: Practise on free platforms (LeetCode, HackerRank, GeeksforGeeks practice) by pattern: ten hash-map problems, then ten sliding-window problems. Write the solution in JavaScript, then say its complexity aloud.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Data-structure questions in JavaScript · 1/6

DSA patterns

In this lesson you will solve the most common data-structure questions in JavaScript.

Prefer a video by a teacher? Find free videos on “javascript data structures algorithms interview two pointers sliding window” on YouTube ↗

In real life: Fraud checks on UPI transactions

A payments team flags accounts with an unusual total in any 10-minute window. That is a sliding-window sum over time-ordered transactions. A naive version recomputed every window from scratch (O(n × k)); the sliding version runs in O(n) and handles millions of transactions a day.

javascript
function maxInWindows(amounts, k) {
  let sum = amounts.slice(0, k).reduce((a, b) => a + b, 0), best = sum;
  for (let i = k; i < amounts.length; i++) { sum += amounts[i] - amounts[i - k]; best = Math.max(best, sum); }
  return best;
}
console.log(maxInWindows([200, 50, 5000, 4800, 100], 2)); // 9800

Practice (0/4 done)

Task 1 · Code · Javascript

Write twoSum(nums, target) that returns the indexes [i, j] (i < j) of two numbers adding up to target, or null. Use a Map for O(n).

Task 2 · Code · Javascript

Write isBalanced(s) that returns true when every (, [ and { is closed in the right order. Other characters are ignored.

Task 3 · Code · Javascript

Write binarySearch(sorted, target) that returns the index of target in a sorted array of numbers, or -1. Do not use indexOf or includes.

Task 4 · Code · Javascript

Write longestUniqueRun(s) that returns the length of the longest substring without repeating characters, using a sliding window. "abcabcbb" → 3 ("abc").

Quick quiz

Question 1

1.Which pattern fits "find two numbers that add up to a target" in unsorted data?

Question 2

2.What is the time complexity of binary search?

Question 3

3.Which data structure checks balanced brackets?

Question 4

4.A loop with arr.indexOf inside it on the same array is…

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which pattern fits "find two numbers that add up to a target" in unsorted data?

Answer: Hash map

Store what you have seen and look up the complement.

What is the time complexity of binary search?

Answer: O(log n)

The search range halves every step.

Which data structure checks balanced brackets?

Answer: Stack

The most recent opener must match the next closer: last in, first out.

A loop with arr.indexOf inside it on the same array is…

Answer: O(n²)

indexOf is itself O(n).

What is the time complexity of BFS with an adjacency list?Related

Answer: O(V + E)

Each vertex and edge is processed a constant number of times.

From Core DSA patterns in C++

Why start best at the first window's sum instead of 0?Related

Answer: Because every window sum might be negative

If all sums are negative, starting at 0 would return 0, which is not the sum of any window.

From Sliding window: fixed size

In the subarray-sum pattern, why look up running − k BEFORE storing running?Related

Answer: So a prefix is never matched with itself, which would count an empty subarray when k = 0

If running were stored first, running − 0 would find the prefix just stored.

From Counting and grouping with hashing

Why is a sliding window wrong for "count subarrays with sum exactly k" when numbers can be negative?Related

Answer: Adding a number may make the sum go down, so you cannot decide when to shrink

With negatives the sum is not monotonic as the window grows; prefix sums with a hash map handle it.

From Recognising the pattern

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “Interview preparation and career” before its exam: Projects, portfolio and jobs.
  2. Module 12 exam: Interview preparation · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. 61 topics left in the course before the final exam.

← Previous: Classic coding questions