DSA in JavaScript: Roadmap, Resources and Code (2026)

DSA in JavaScript roadmap and resources 2026 - CodingHumans

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). Use BigInt or 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

TrapWhat happensFix
[10, 9, 1].sort()Sorts as strings: [1, 10, 9]Always pass a comparator: sort((a, b) => a - b)
arr.shift() in a loopO(n) per call, because every element movesUse a head index or a proper queue
Building a string with += in a loopCan be slow for very large outputsPush parts into an array and join('') once
Plain objects as hash mapsKeys become strings; inherited keys can clashUse Map and Set
Math.floor(a / b) for negativesRounds toward −∞, unlike C++/JavaUse Math.trunc when you need C-style division
new Array(3).fill([])All three slots share one arrayArray.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.

WeekTopicJavaScript focusTheory
1Complexity, arrays and stringsArray methods and their costs, string immutability, split/joinComplexity, Arrays and strings
2HashingMap, Set, frequency countingHashing
3Two pointers and sliding windowIndex-based loops, window counts in a MapTwo pointers
4Linked lists, stacks and queuesNode classes, arrays as stacks, a real queueLinked list, Stack and queue
5Recursion and backtrackingPassing paths by copy vs push/pop, depth limitsRecursion
6Sorting and binary searchComparators, binary search on the answerSorting and search
7Trees and BSTRecursive and iterative traversalsTrees
8Heaps and priority queuesYour own MinHeap classHeaps
9GraphsAdjacency lists with arrays, BFS with a queueGraphs
10Greedy and dynamic programming1D/2D DP arrays, memo with MapGreedy, 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.

OperationTimeWhat to watch for
arr[i], arr.lengthO(1)Fine everywhere.
arr.push(x), arr.pop()O(1) amortisedUse 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, deleteO(1) averageYour 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 loopCan 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

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

Answered 0/0Correct 0