DSA Interview Questions

Data Structures & Algorithms - 60+ problems organized by topic and difficulty

15-Minute DSA Cheatsheet

Quick reference for last-minute interview preparation

Time Complexity

O(1)Hash lookup, array access
O(log n)Binary search
O(n)Single loop, linear search
O(n log n)Merge sort, heap sort
O(n²)Nested loops, bubble sort
O(2ⁿ)Recursive subsets

Data Structures

Array: O(1) access, O(n) insert/delete
LinkedList: O(n) access, O(1) insert/delete
HashMap: O(1) avg for all ops
Stack/Queue: O(1) push/pop
Heap: O(log n) insert, O(1) peek
BST: O(log n) balanced, O(n) worst

Common Patterns

Two Pointers: Sorted arrays, palindromes
Sliding Window: Subarrays, substrings
Binary Search: Sorted data, search space
BFS/DFS: Trees, graphs, matrices
Dynamic Programming: Optimal substructure
Backtracking: Permutations, combinations

Problem-Solving Tips

1. Clarify constraints and edge cases
2. Start with brute force, then optimize
3. Think about which data structure fits
4. Consider space-time tradeoffs
5. Test with examples before coding
6. Walk through code with test case

Trees & Graphs

Traversals: Inorder, Preorder, Postorder, Level
BST Property: left < root < right
BFS: Queue, level-order, shortest path
DFS: Stack/recursion, path finding
Graph: Adjacency list vs matrix
Cycle Detection: Visited set, coloring

Dynamic Programming

Key Signs: Optimal, count ways, min/max
Steps: Define state → recurrence → base case
1D DP: Fibonacci, climbing stairs, house robber
2D DP: LCS, edit distance, grid paths
Knapsack: 0/1 vs unbounded
Optimization: Memoization → tabulation

Must-Know Problems

Two Sum (HashMap)
Valid Parentheses (Stack)
Merge Intervals (Sorting)
Binary Search variants
Reverse Linked List
Level Order Traversal
Number of Islands (DFS/BFS)
Longest Substring (Sliding Window)
Climbing Stairs (DP)

Quick Formulas

Binary search: mid = left + (right - left) // 2
Heap parent: (i-1)//2, children: 2i+1, 2i+2
Tree height balanced: |h(L) - h(R)| ≤ 1
Graph edges: V-1 (tree) to V(V-1)/2 (complete)

Given an array of integers and a target sum, return indices of two numbers that add up to the target. You may assume that each input has exactly one solution.

Python

Reverse a singly linked list iteratively and recursively. This is a fundamental linked list problem.

Python

Given a string containing just the characters '(', ')', ', ', '[' and ']', determine if the input string is valid. Brackets must close in the correct order.

Python

Find the contiguous subarray within an array which has the largest sum. This is solved efficiently using Kadane's algorithm.

Python

Traverse a binary tree level by level from left to right using Breadth-First Search (BFS).

Python

Find the length of the longest substring without repeating characters using sliding window technique.

Python

Given a collection of intervals, merge all overlapping intervals.

Python

Find the lowest common ancestor (LCA) of two nodes in a binary tree.

Python

Determine if you can finish all courses given prerequisites. This is a graph cycle detection problem.

Python

Design and implement a Least Recently Used (LRU) cache with O(1) time complexity for both get and put operations.

Python

Implement binary search to find the index of a target value in a sorted array.

Python

You're climbing a staircase with n steps. Each time you can climb 1 or 2 steps. How many distinct ways can you climb to the top?

Python

Given an array, return an array where each element is the product of all elements except itself, without using division and in O(n) time.

Python

Find the kth largest element in an unsorted array using QuickSelect algorithm.

Python

Search for a target in a rotated sorted array in O(log n) time.

Python

Given a string s and a dictionary of words, determine if s can be segmented into space-separated sequence of dictionary words.

Python

Count the number of islands in a 2D grid where '1' represents land and '0' represents water.

Python

Find the minimum number of coins needed to make up a given amount using unlimited coins of given denominations.

Python

Determine if a binary tree is a valid Binary Search Tree (BST).

Python

Given an elevation map where the width of each bar is 1, compute how much water can be trapped after raining.

Python

💻 Coding Interview Questions

Organized by difficulty level - from foundational to expert problems

📗 Level 1: Foundational Problems

Given a string s, return the first non-repeating character. If none exists, return -1.
Input: "swiss" → Output: 'w'

Java

Check if a string containing {}, [], () is valid.
Input: "{'[()]'}"Output: true

Java

Return indices of two numbers that add up to target.
Input: [2,7,11,15], target = 9 → Output: [0,1]

Java

Return true if t is an anagram of s.
Input: s = "anagram", t = "nagaram" → true

Java

Return true if linked list has a cycle using Floyd's slow & fast pointer technique.
Time: O(n), Space: O(1)

Java

Find maximum sum of any contiguous subarray of size k.
Input: [2,1,5,1,3,2], k=3 → Output: 9 (subarray [5,1,3])

Java

Array of size n-1 contains numbers 1..n. Find the missing number.
Input: [1,2,4,5] → Output: 3

Java

Find the longest common prefix among an array of strings.
Input: ["flower","flow","flight"] → Output: "fl"

Java

Given API isBadVersion(version), find the first bad version.
Input: n = 10, bad = 4 → Output: 4

Java

Compress a string by counting consecutive characters. Return original if compressed is longer.
Input: "aabcccccaaa" → Output: "a2b1c5a3"

Java

📙 Level 2: Intermediate Problems

Return length of longest substring without duplicate characters.
Input: "abcabcbb" → Output: 3 ("abc")

Java

Find kth largest element in an unsorted array.
Input: [3,2,1,5,6,4], k = 2 → Output: 5

Java

Group strings that are anagrams together.
Input: ["eat","tea","tan","ate","nat","bat"]
Output: [["eat","tea","ate"],["tan","nat"],["bat"]]

Java

Find the contiguous subarray with the largest sum.
Input: [-2,1,-3,4,-1,2,1,-5,4] → Output: 6 (subarray [4,-1,2,1])

Java

Return array where answer[i] is product of all elements except nums[i]. No division allowed.
Input: [1,2,3,4] → Output: [24,12,8,6]

Java

Merge overlapping intervals.
Input: [[1,3],[2,6],[8,10]] → Output: [[1,6],[8,10]]

Java

Find all unique triplets [nums[i], nums[j], nums[k]] that sum to 0.
Input: [-1,0,1,2,-1,-4] → [[-1,-1,2],[-1,0,1]]

Java

Find two lines that together with x-axis form a container that holds the most water.
Input: [1,8,6,2,5,4,8,3,7] → Output: 49

Java

Can string be segmented into dictionary words?
Input: s = "leetcode", wordDict = ["leet","code"] → true

Java

Return the longest palindromic substring.
Input: "babad" → "bab" or "aba"

Java

Implement a rate limiter that allows max N requests per second per user. Common in screening interviews.

Java

Return all possible letter combinations from digits 2-9 (phone keypad).
Input: "23" → ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Java

Return level order traversal of binary tree (left to right, level by level).

Java

Given numCourses and prerequisites, return true if you can finish all courses.
This is essentially detecting if a directed graph has a cycle.

Java

Implement a Trie with insert, search, and startsWith methods.

Java

Count number of islands in a 2D grid where '1' is land and '0' is water.
Input: [["1","1","0"],["1","1","0"],["0","0","1"]] → Output: 2

Java

Find minimum number of coins to make up the amount.
Input: coins = [1,2,5], amount = 11 → Output: 3 (5+5+1)

Java

Rotate an n×n 2D matrix by 90 degrees clockwise in-place.

Java

Return all elements of the matrix in spiral order.
Input: [[1,2,3],[4,5,6],[7,8,9]] → [1,2,3,6,9,8,7,4,5]

Java

Given a reference to a node in a connected undirected graph, return a deep copy of the graph.

Java

Return the k most frequent elements.
Input: nums = [1,1,1,2,2,3], k = 2 → Output: [1,2]

Java

Design a Least Recently Used (LRU) cache with get and put operations in O(1) time.

Java

📕 Level 3: Advanced/Expert Problems

Given n non-negative integers representing an elevation map, compute how much water can be trapped after raining.
Input: [0,1,0,2,1,0,1,3,2,1,2,1] → Output: 6

Java

Find the largest rectangle area in a histogram.
Input: [2,1,5,6,2,3] → Output: 10

Java

Find the minimum window in s which contains all characters of t.
Input: s = "ADOBECODEBANC", t = "ABC" → Output: "BANC"

Java

Transform beginWord to endWord, changing one letter at a time. Each transformed word must be in wordList.
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] → 5

Java

Merge k sorted linked lists into one sorted list.

Java

Find the maximum path sum in a binary tree. Path can start and end at any node.
Input: [-10,9,20,null,null,15,7] → Output: 42 (15→20→7)

Java

Design an algorithm to serialize and deserialize a binary tree.

Java

Find the length of the longest valid parentheses substring.
Input: "(()" → 2, ")()())" → 4

Java

Place N queens on an N×N chessboard such that no two queens attack each other.

Java

Implement regex matching with '.' (matches any char) and '*' (matches zero or more of preceding element).
Input: s = "aab", p = "c*a*b" → true

Java

Design a data structure that supports adding numbers and finding the median in O(log n) add, O(1) find.

Java

Given a sorted dictionary of an alien language, find the order of characters.
Input: ["wrt","wrf","er","ett","rftt"] → "wertf"

Java

Find the longest increasing path in a matrix.
Input: [[9,9,4],[6,6,8],[2,1,1]] → 4 (1→2→6→9)

Java

Find minimum operations (insert, delete, replace) to convert word1 to word2.
Input: "horse", "ros" → 3

Java

Return max value in each sliding window of size k.
Input: [1,3,-1,-3,5,3,6,7], k = 3 → [3,3,5,5,6,7]

Java

Burst balloons to maximize coins. Burst balloon i to get nums[i-1] * nums[i] * nums[i+1] coins.
Input: [3,1,5,8] → 167

Java

Coding Interview Tips

  • Always clarify input constraints and edge cases before coding
  • Discuss time and space complexity for each approach
  • Start with brute force, then optimize
  • Use meaningful variable names and add comments
  • Test your code with examples, including edge cases
  • Common patterns: Two Pointers, Sliding Window, DFS/BFS, DP, Binary Search
  • Practice on LeetCode, HackerRank, and CodeSignal