
Learning DSA in JavaScript makes sense if you're a frontend or full-stack developer: you already write JavaScript every day, LeetCode and most online coding tests accept it, and frontend interviews increasingly include a DSA round. But JavaScript has a few traps that C++ and Java users never hit. There's no built-in heap or queue, the default sort compares numbers as strings, and shift() is slower than it looks.
This roadmap gives you a week-by-week plan, the JavaScript-specific details you need for each topic, and ready-to-use code for the data structures JavaScript doesn't ship with. It follows the same order as our Learn DSA roadmap, so you can read the theory there and practise it here in JavaScript.
Is JavaScript good for DSA?
Yes, for interviews and most coding tests. The language is expressive, arrays and hash maps are built in, and your solutions read almost like pseudocode. The limits are real but manageable:
- No standard heap, queue or deque. You write a small class once and reuse it (code below).
- Numbers are 64-bit floats. Integers are exact only up to
Number.MAX_SAFE_INTEGER(253 − 1). UseBigIntor take results modulo a prime when values grow beyond that. - Recursion depth is limited. Very deep recursion (tens of thousands of calls) can throw a stack overflow, so use an explicit stack for deep trees or long linked lists.
If you're preparing for competitive programming with tight time limits, C++ is still faster. For product-company interviews and placement tests that allow JavaScript, it's a perfectly good choice.
JavaScript traps to know first
| Trap | What happens | Fix |
|---|---|---|
[10, 9, 1].sort() | Sorts as strings: [1, 10, 9] | Always pass a comparator: sort((a, b) => a - b) |
arr.shift() in a loop | O(n) per call, because every element moves | Use a head index or a proper queue |
Building a string with += in a loop | Can be slow for very large outputs | Push parts into an array and join('') once |
| Plain objects as hash maps | Keys become strings; inherited keys can clash | Use Map and Set |
Math.floor(a / b) for negatives | Rounds toward −∞, unlike C++/Java | Use Math.trunc when you need C-style division |
new Array(3).fill([]) | All three slots share one array | Array.from({ length: 3 }, () => []) |
The 10-week DSA in JavaScript roadmap
Plan for about 1.5 to 2 hours a day. Each week links to the matching Learn DSA post for theory. Solve 15 to 25 problems per topic, mostly easy and medium.
| Week | Topic | JavaScript focus | Theory |
|---|---|---|---|
| 1 | Complexity, arrays and strings | Array methods and their costs, string immutability, split/join | Complexity, Arrays and strings |
| 2 | Hashing | Map, Set, frequency counting | Hashing |
| 3 | Two pointers and sliding window | Index-based loops, window counts in a Map | Two pointers |
| 4 | Linked lists, stacks and queues | Node classes, arrays as stacks, a real queue | Linked list, Stack and queue |
| 5 | Recursion and backtracking | Passing paths by copy vs push/pop, depth limits | Recursion |
| 6 | Sorting and binary search | Comparators, binary search on the answer | Sorting and search |
| 7 | Trees and BST | Recursive and iterative traversals | Trees |
| 8 | Heaps and priority queues | Your own MinHeap class | Heaps |
| 9 | Graphs | Adjacency lists with arrays, BFS with a queue | Graphs |
| 10 | Greedy and dynamic programming | 1D/2D DP arrays, memo with Map | Greedy, DP |
Data structures you must build yourself
A fast queue
Using shift() makes BFS O(n²) on large inputs. A head index keeps every operation O(1):
class Queue {
constructor() { this.items = []; this.head = 0; }
push(x) { this.items.push(x); }
shift() { return this.items[this.head++]; }
get size() { return this.items.length - this.head; }
}
Time: O(1) per push and shift. Space: O(n). The array isn't shrunk, which is fine for a single algorithm run.
A min-heap (priority queue)
Needed for Dijkstra, "k smallest/largest" problems, merging sorted lists and scheduling problems.
class MinHeap {
constructor(compare = (a, b) => a - b) { this.h = []; this.cmp = compare; }
get size() { return this.h.length; }
peek() { return this.h[0]; }
push(x) {
const h = this.h; h.push(x);
let i = h.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (this.cmp(h[i], h[p]) >= 0) break;
[h[i], h[p]] = [h[p], h[i]]; i = p;
}
}
pop() {
const h = this.h; const top = h[0]; const last = h.pop();
if (h.length) {
h[0] = last; let i = 0;
while (true) {
const l = 2 * i + 1, r = l + 1; let m = i;
if (l < h.length && this.cmp(h[l], h[m]) < 0) m = l;
if (r < h.length && this.cmp(h[r], h[m]) < 0) m = r;
if (m === i) break;
[h[i], h[m]] = [h[m], h[i]]; i = m;
}
}
return top;
}
}
Time: O(log n) for push and pop, O(1) for peek. Space: O(n). For a max-heap, pass (a, b) => b - a. For pairs such as [distance, node], pass (a, b) => a[0] - b[0].
Linked list node and tree node
class ListNode { constructor(val, next = null) { this.val = val; this.next = next; } }
class TreeNode { constructor(val, left = null, right = null) { this.val = val; this.left = left; this.right = right; } }
These match the node shapes LeetCode uses for JavaScript, so code you practise locally pastes straight in.
Core patterns in JavaScript
Binary search (first index where condition is true)
function lowerBound(arr, target) {
let lo = 0, hi = arr.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (arr[mid] < target) lo = mid + 1; else hi = mid;
}
return lo;
}
Time: O(log n). Space: O(1). The >> 1 trick is safe only while indices stay below about 2 billion, which is always true for arrays.
Sliding window with a Map (longest substring without repeating characters)
function longestUnique(s) {
const last = new Map(); let start = 0, best = 0;
for (let i = 0; i < s.length; i++) {
if (last.has(s[i]) && last.get(s[i]) >= start) start = last.get(s[i]) + 1;
last.set(s[i], i);
best = Math.max(best, i - start + 1);
}
return best;
}
Time: O(n). Space: O(k), where k is the number of distinct characters.
BFS on a grid
function shortestPath(grid, sr, sc, tr, tc) {
const R = grid.length, C = grid[0].length;
const dist = Array.from({ length: R }, () => new Array(C).fill(-1));
const q = new Queue(); q.push([sr, sc]); dist[sr][sc] = 0;
const dirs = [[1,0],[-1,0],[0,1],[0,-1]];
while (q.size) {
const [r, c] = q.shift();
if (r === tr && c === tc) return dist[r][c];
for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < R && nc >= 0 && nc < C && grid[nr][nc] === 0 && dist[nr][nc] === -1) {
dist[nr][nc] = dist[r][c] + 1; q.push([nr, nc]);
}
}
}
return -1;
}
Time: O(R × C). Space: O(R × C). Note the Array.from to create the 2D array, which avoids the shared-row trap from the table above.
Dynamic programming with an array (climbing stairs)
function climbStairs(n) {
let a = 1, b = 1;
for (let i = 2; i <= n; i++) [a, b] = [b, a + b];
return b;
}
Time: O(n). Space: O(1). For problems with large answers, apply % 1_000_000_007 at each step, or switch to BigInt, because results above 253 lose precision.
Time complexity of JavaScript built-ins (cheat sheet)
Interviewers love asking why a JavaScript solution is slower than expected, and the answer is usually a built-in that looks cheap but is not. Keep this table in your head while you code.
| Operation | Time | What to watch for |
|---|---|---|
arr[i], arr.length | O(1) | Fine everywhere. |
arr.push(x), arr.pop() | O(1) amortised | Use these for a stack. |
arr.shift(), arr.unshift(x) | O(n) | Every element moves. Using shift() as a queue turns BFS into O(n²); use the fast queue above. |
arr.includes(x), arr.indexOf(x) | O(n) | Inside a loop this becomes O(n²). Use a Set for lookups. |
arr.slice(), [...arr], arr.concat() | O(n) | Copies the array. Avoid copying inside recursion; pass indexes instead. |
arr.splice(i, 1) | O(n) | Shifts everything after i. |
arr.sort() | O(n log n) | Without a comparator it sorts numbers as strings: [10, 9, 1].sort() gives [1, 10, 9]. Always pass (a, b) => a - b. |
Map / Set: get, set, has, delete | O(1) average | Your hash map. Prefer Map over a plain object when keys are not simple strings. |
str.slice(), str.split(), str.indexOf() | O(n) | Strings are immutable, so every change creates a new string. |
s += ch in a loop | Can add up to O(n²) | For big outputs, push pieces into an array and join("") once at the end. |
Math.max(...arr) | O(n) | Spreading a very large array can throw a RangeError. Use a loop or reduce for big inputs. |
Input and output in online coding tests
LeetCode-style platforms call your function directly. HackerRank-style tests give you standard input instead. In Node.js the simplest way is to read everything at once:
const data = require('fs').readFileSync(0, 'utf8').trim().split(/\s+/);
let pos = 0;
const next = () => data[pos++];
const n = Number(next());
const out = [];
for (let i = 0; i < n; i++) out.push(Number(next()) * 2);
console.log(out.join('\n'));
Collect output in an array and print once. Many separate console.log calls can be slow for large outputs. If you see "no response on stdout", check that you actually print the result and that the platform's template doesn't expect you to fill in a specific function instead.
Resources and how to practise
- Theory: our Learn DSA series, one post per topic in the order above.
- JavaScript reference: MDN Web Docs for exact behaviour of
Array,Map,SetandBigInt. - Practice: LeetCode and HackerRank both accept JavaScript. Our coding test online practice set is a good timed warm-up.
- Revision: the Data Structures and Algorithms Hub and our JavaScript MCQs.
How to practise: do one topic a week, write each data structure from memory once, time yourself on two medium problems at the end of each week, and keep a short "mistakes" list (wrong sort, off-by-one, forgotten edge case). That list is your revision sheet before interviews.
FAQ
Can I crack DSA interviews using only JavaScript?
Yes. Most product companies and online assessments allow JavaScript, and interviewers care about your approach and complexity analysis, not the language. Just be ready to write a heap or queue yourself.
How long does it take to learn DSA in JavaScript?
About 10 to 12 weeks at 1.5 to 2 hours a day is enough to be interview-ready for most roles, if you already know JavaScript basics. Add a few weeks for graphs and DP if they're new to you.
Should I learn DSA in JavaScript or Java?
If you're aiming for frontend or full-stack roles, JavaScript keeps you in one language. If you're targeting roles or tests where Java or C++ is expected, or competitive programming, learn in that language. The concepts transfer either way.
Is TypeScript okay for DSA?
Yes. LeetCode supports TypeScript, and types help catch mistakes. The data structures and patterns above work the same with type annotations added.
What is the time complexity of array shift() in JavaScript?
O(n), because every remaining element moves one place to the left. That is why using shift() as a queue makes BFS slow on big inputs. A queue with a head index, like the one in this post, keeps each dequeue at O(1).
Learning DSA with others? Join the CodingHumans WhatsApp community for daily problems and practice sets.
Comments
Post a Comment