Expert · Interview preparation and career · topic 60 of 61 · 30 min
Data-structure questions in JavaScript
Explanation
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
// 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
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')); // true3. 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
// 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
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 false6. Binary search
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.
| Pattern | Clue in the problem | Typical complexity |
|---|---|---|
| Hash map / Set | "find a pair", "count", "duplicates", "seen before" | O(n) time, O(n) space |
| Two pointers | sorted input, pairs, palindromes | O(n) time, O(1) space |
| Sliding window | "subarray / substring of length k", "longest/shortest window" | O(n) |
| Stack | matching brackets, undo, "next greater element" | O(n) |
| Binary search | sorted input, "find the first/last", "minimum that works" | O(log n) |
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
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.
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)); // 9800Practice (0/4 done)
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).
Write isBalanced(s) that returns true when every (, [ and { is closed in the right order. Other characters are ignored.
Write binarySearch(sorted, target) that returns the index of target in a sorted array of numbers, or -1. Do not use indexOf or includes.
Write longestUniqueRun(s) that returns the length of the longest substring without repeating characters, using a sliding window. "abcabcbb" → 3 ("abc").
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Projects, portfolio and jobsInterview preparation and career · same module
- Predict-the-output questionsInterview preparation and career · same module
- Core DSA patterns in C++C++ Programming (modern C++ and DSA) · Competitive programming, interviews and careers
- Sliding window: fixed sizeData Structures and Algorithms (DSA) for interviews · Hashing, two pointers and sliding window
- Counting and grouping with hashingData Structures and Algorithms (DSA) for interviews · Hashing, two pointers and sliding window
- Recognising the patternData Structures and Algorithms (DSA) for interviews · Interview strategy and mock problems
Questions people ask about this
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.
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.
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.
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.
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 more topic in “Interview preparation and career” before its exam: Projects, portfolio and jobs.
- Module 12 exam: Interview preparation · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- 61 topics left in the course before the final exam.