DSA Interview Questions
60 DSA interview questions with worked answers, complexity notes, and runnable code you can edit in the browser — ordered easy to hard so you build up steadily. Free, no signup. Open any question for the full answer.
Method beats memorization
Frontend DSA rounds are rarely about exotic algorithms. They lean easy-to-medium — arrays, strings, hash maps, trees, and usually one design-flavored problem — and what gets scored is not whether you produce the optimal answer but how you get there. Interviewers are watching a process, and the candidates who pass make that process visible every time.
The sequence is always the same. First clarify: what are the inputs, how big can they get, what are the edge cases, can the input be empty or contain duplicates? Then state the brute-force solution and its Big-O out loud, before optimizing — this proves you understand the problem and gives you a baseline to improve on. Then name the pattern. Most interview problems are one of a handful in disguise: two pointers, sliding window, a hash map for O(1) lookup, binary search on a sorted space, breadth-first or depth-first traversal, or a heap for top-k. Recognizing which one applies is most of the battle, and it is a skill you build by pattern, not by grinding hundreds of problems.
Only then do you code — cleanly, with names a reader can follow — and finish by dry-running one normal example plus the edge cases you named at the start. Complexity gets discussed in terms of both time and space, because the trade-off between them is often the actual question. The decision table on this page exists to short-circuit the hardest step: map the shape of the input to the pattern before you write a line. These questions give you the reps to make that mapping automatic.
Easy
- Two Sum Hash Map / Set
Given an array of integers and a target, return the indices of the two numbers that add up to target. Exactly one solution; can't reuse an… - First Unique Character Hash Map / Set
Return the index of the first non-repeating character in a string, or -1 if none. - Valid Palindrome Two Pointers
Given a string, return true if it reads the same forwards and backwards, considering only alphanumeric characters and ignoring case. - Max Average Subarray (size k) Sliding Window
Find the contiguous subarray of length k with the maximum average, return that average. - Running Sum of 1d Array Prefix Sum
Return an array where result[i] = sum of nums[0..i]. - Binary Search / Search Insert Position Binary Search
Given a sorted array and a target, return its index, or the index where it would be inserted to keep the array sorted. - Maximum Depth of Binary Tree DFS (Depth-First)
Return the maximum depth (number of nodes along the longest root-to-leaf path) of a binary tree. - Valid Parentheses Stack / Monotonic Stack
Given a string of '()[]{}', return true if brackets are correctly opened and closed in order. - Reverse a Linked List Linked List / Fast-Slow
Reverse a singly linked list and return the new head. - Climbing Stairs Dynamic Programming
You can climb 1 or 2 steps at a time. How many distinct ways to reach the n-th step? - Single Number Bit Manipulation
Every element appears twice except one. Find the element that appears once, in O(n) time and O(1) space. - Best Time to Buy and Sell Stock Greedy / One-Pass
Given daily prices, find the max profit from a single buy followed by a later sell.
Medium
- Group Anagrams Hash Map / Set
Group a list of strings so that anagrams are together. e.g. ['eat','tea','tan','ate','nat','bat'] →… - Container With Most Water Two Pointers
Given heights[], each a vertical line, find two lines that together with the x-axis hold the most water. Return the max area. - 3Sum Two Pointers
Return all unique triplets [a,b,c] in an array that sum to zero. - Longest Substring Without Repeating Characters Sliding Window
Given a string, return the length of the longest substring with no repeating characters. - Subarray Sum Equals K Prefix Sum
Count the number of contiguous subarrays whose sum equals k. - Subsets (Power Set) Backtracking
Return all possible subsets of a set of distinct integers. - Generate Parentheses Backtracking
Given n pairs of parentheses, generate all combinations of well-formed parentheses. - Combination Sum Backtracking
Given distinct candidates and a target, return all unique combinations that sum to target. Each number may be reused unlimited times. - Search in Rotated Sorted Array Binary Search
A sorted array was rotated at an unknown pivot. Find a target's index in O(log n), or -1. - Number of Islands DFS (Depth-First)
Given a grid of '1' (land) and '0' (water), count the islands (land connected 4-directionally). - Binary Tree Level Order Traversal BFS (Breadth-First)
Return the node values grouped by level, top to bottom. - Rotting Oranges BFS (Breadth-First)
In a grid, 2 = rotten orange, 1 = fresh, 0 = empty. Each minute, rotten oranges rot 4-directional fresh neighbors. Return minutes until… - Daily Temperatures Stack / Monotonic Stack
For each day, how many days until a warmer temperature? Return an array of waits (0 if none). - Kth Largest Element Heap / Top-K
Return the k-th largest element in an unsorted array. - Top K Frequent Elements Heap / Top-K
Return the k most frequent elements in an array. - Merge Intervals Intervals
Given a list of intervals, merge all overlapping ones. e.g. [[1,3],[2,6],[8,10]] → [[1,6],[8,10]]. - Linked List Cycle Detection Linked List / Fast-Slow
Return true if a linked list has a cycle. - Coin Change (fewest coins) Dynamic Programming
Given coin denominations and an amount, return the fewest coins to make that amount, or -1 if impossible. - Jump Game Greedy / One-Pass
Each element is the max jump length from that index. Starting at index 0, can you reach the last index? - Implement a Trie Trie (Prefix Tree)
Implement a prefix tree supporting insert(word), search(word), and startsWith(prefix). - Course Schedule (cycle detection) Topological Sort / Graph
Given numCourses and prerequisite pairs [a, b] (b must be taken before a), can you finish all courses? - Maximum Subarray (Kadane's Algorithm) Dynamic Programming / Kadane
Given an integer array (may contain negatives), find the contiguous subarray with the largest sum and return that sum. e.g.… - Product of Array Except Self Prefix Sum
Return an array where output[i] is the product of every element except nums[i] — without using division and in O(n). e.g. [1,2,3,4] →… - Number of Connected Components Union-Find (Disjoint Set)
Given n nodes labelled 0..n-1 and a list of undirected edges, count how many connected components the graph has. e.g. n=5,… - LRU Cache Design (Hash Map + Doubly Linked List)
Design a cache with fixed capacity supporting get(key) and put(key,value), both in O(1). When full, evict the least-recently-used entry.… - Spiral Matrix Matrix Traversal
Return all elements of an m×n matrix in spiral order (right across the top, down the right side, left across the bottom, up the left side,… - Validate Binary Search Tree DFS (Depth-First)
Determine whether a binary tree is a valid BST: every node's left subtree holds only smaller values, its right subtree only larger, and… - House Robber Dynamic Programming
Given an array where each element is the money in a house along a street, maximise what you can rob without robbing two adjacent houses.… - Meeting Rooms II (minimum rooms) Intervals
Given meeting intervals [[start,end], ...], return the minimum number of rooms needed so no two overlapping meetings share a room. e.g.… - Longest Common Subsequence Dynamic Programming (2D)
Given two strings text1 and text2, return the length of their longest common subsequence — characters appearing left-to-right but not… - Word Break Dynamic Programming (partition)
Given a string s and a dictionary of words, return true if s can be segmented into a space-separated sequence of one or more dictionary… - Unique Paths Dynamic Programming (grid count)
A robot sits at the top-left of an m×n grid and can move only right or down. How many distinct paths reach the bottom-right corner? e.g.… - Decode Ways Dynamic Programming (1D)
A message of digits is encoded where 'A'→1 … 'Z'→26. Given a digit string, count how many ways it can be decoded. e.g. '226' → 3 ('2 2 6',… - Maximum Product Subarray Dynamic Programming (running extremes)
Given an integer array, return the maximum product of any contiguous non-empty subarray. e.g. [2,3,-2,4] → 6, [-2,3,-4] → 24. - Rotate Image (90° in place) Matrix (in-place transform)
Rotate an n×n matrix 90° clockwise in place, using no second matrix. e.g. [[1,2,3],[4,5,6],[7,8,9]] → [[7,4,1],[8,5,2],[9,6,3]]. - Set Matrix Zeroes Matrix (in-place markers)
Given an m×n matrix, if a cell is 0 set its entire row and column to 0, in place. The catch: use O(1) extra space, not O(m+n) marker arrays. - Non-overlapping Intervals Greedy (interval scheduling)
Given a set of intervals, return the minimum number you must remove so the rest do not overlap. e.g. [[1,2],[2,3],[3,4],[1,3]] → 1 (remove… - Clone Graph Graph traversal + hashmap
Given a reference to a node in a connected undirected graph, return a deep copy: every node cloned, every edge reproduced, no node… - Word Search Backtracking (grid)
Given a grid of characters and a word, return true if the word can be formed by a path of horizontally/vertically adjacent cells, each cell… - Longest Consecutive Sequence Hashing (O(n) set trick)
Given an unsorted integer array, return the length of the longest run of consecutive integers. e.g. [100,4,200,1,3,2] → 4 (for 1,2,3,4).… - Longest Palindromic Substring Expand around center
Return the longest contiguous substring of s that is a palindrome. e.g. 'babad' → 'bab' (or 'aba'), 'cbbd' → 'bb'. - Lowest Common Ancestor of a BST BST property walk
Given a binary search tree and two nodes p and q, return their lowest common ancestor — the deepest node that has both as descendants (a… - Merge Sort & Quick Sort Divide & conquer (sorting)
Implement merge sort and quick sort from scratch, and be ready to explain their time/space trade-offs and when each is preferable. - Sort Colors (Dutch National Flag) Three-pointer partition
Given an array of 0s, 1s, and 2s (red/white/blue), sort it in place in a single pass without a library sort or counting. e.g. [2,0,2,1,1,0]…
Hard
- Minimum Window Substring Sliding Window
Given strings s and t, return the smallest substring of s that contains every character of t (with multiplicity). Return '' if none. - Longest Increasing Subsequence Dynamic Programming
Return the length of the longest strictly increasing subsequence (not necessarily contiguous). - Merge k Sorted Lists Heap / Top-K
Merge k sorted linked lists into one sorted list. e.g. [[1,4,5],[1,3,4],[2,6]] → 1,1,2,3,4,4,5,6. - Binary Tree Maximum Path Sum Tree DP (postorder)
A path is any sequence of nodes connected by edges (it need not pass through the root and can start/end anywhere). Return the maximum…
Other topics
HTML/CSS · Browser · JavaScript · TypeScript · React · System Design · Accessibility · Web Performance · Testing · Networking/Security