Absolutely! Preparing for Data Structures and Algorithms (DSA) interviews by systematically studying problems is an excellent approach. Below is a comprehensive guide covering Easy and Medium difficulty problems from the categories you've listed: Matrix, Stack, Trees, and Graphs. Each problem includes a detailed discussion, intuition for solving it, and well-formatted Python code.
🎯 Matrix Problems
1. Set Matrix Zeroes (LeetCode #73) - Medium
Problem Statement
Given an m x n matrix. If an element is 0, set its entire row and column to 0. Do it in-place.
Intuition
To solve this problem efficiently without using extra space proportional to the matrix size, we can use the first row and first column of the matrix itself to store the information about which rows and columns should be zeroed.
Approach
- Determine Zero Rows and Columns:
- Use two flags to determine if the first row and first column need to be zeroed.
- Traverse the matrix:
- If a cell
matrix[i][j] is zero, mark matrix[i][0] and matrix[0][j] as zero.
- Zero the Cells Based on Marks:
- Iterate through the matrix (excluding the first row and column):
- If either
matrix[i][0] or matrix[0][j] is zero, set matrix[i][j] to zero.
- Handle First Row and Column Separately:
- If the first row needs to be zeroed, set all elements in the first row to zero.
- Similarly, if the first column needs to be zeroed, set all elements in the first column to zero.
Python Solution
def setZeroes(matrix):
"""
Modify the matrix in-place such that if an element is 0,
its entire row and column are set to 0.
"""
if not matrix or not matrix[0]:
return
m, n = len(matrix), len(matrix[0])
first_row_zero = any(matrix[0][j] == 0 for j in range(n))
first_col_zero = any(matrix[i][0] == 0 for i in range(m))
# Use first row and column to mark zeros
for i in range(1, m):
for j in range(1, n):
if matrix[i][j] == 0:
matrix[i][0] = matrix[0][j] = 0
# Zero out cells based on marks in first row and column
for i in range(1, m):
for j in range(1, n):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
# Zero out the first row if needed
if first_row_zero:
for j in range(n):
matrix[0][j] = 0
# Zero out the first column if needed
if first_col_zero:
for i in range(m):
matrix[i][0] = 0
Time Complexity
- O(mn) where
m is the number of rows and n is the number of columns.
Space Complexity
- O(1) extra space (in-place).
2. Spiral Matrix (LeetCode #54) - Medium
Problem Statement
Given an m x n matrix, return all elements of the matrix in spiral order.
Intuition
The idea is to traverse the matrix in layers, moving right, down, left, and up, then moving to the inner layer, and so on, until all elements are traversed.
Approach
- Initialize four pointers to keep track of the current boundaries:
top, bottom, left, right.
- While
top <= bottom and left <= right:
- Traverse from left to right on the
top row.
- Traverse from top to bottom on the
right column.
- If
top < bottom, traverse from right to left on the bottom row.
- If
left < right, traverse from bottom to top on the left column.
- Move the boundaries inward.
Python Solution
def spiralOrder(matrix):
"""
Returns the elements of the matrix in spiral order.
"""
if not matrix or not matrix[0]:
return []
result = []
top, bottom = 0, len(matrix)-1
left, right = 0, len(matrix[0])-1
while top <= bottom and left <= right:
# Traverse from left to right
for j in range(left, right+1):
result.append(matrix[top][j])
# Traverse downwards
for i in range(top+1, bottom+1):
result.append(matrix[i][right])
# Make sure we are now on a different row
if top < bottom:
# Traverse from right to left
for j in range(right-1, left-1, -1):
result.append(matrix[bottom][j])
# Make sure we are now in a different column
if left < right:
# Traverse upwards
for i in range(bottom-1, top, -1):
result.append(matrix[i][left])
top += 1
bottom -= 1
left += 1
right -= 1
return result
Time Complexity
- O(mn) where
m and n are the matrix dimensions.
Space Complexity
- O(1) extra space (output list is not considered extra space).
3. Rotate Image (LeetCode #48) - Medium
Problem Statement
You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise) in-place.
Intuition
To rotate the matrix by 90 degrees clockwise:
- Transpose the Matrix: Swap
matrix[i][j] with matrix[j][i].
- Reverse Each Row: Reverse the elements of each row.
This combination effectively rotates the matrix by 90 degrees clockwise.
Approach
- Transpose:
- Iterate through the upper triangle of the matrix and swap symmetric elements.
- Reverse Rows:
- For each row, reverse the elements to achieve the rotation.
Python Solution
def rotate(matrix):
"""
Rotates the given n x n matrix by 90 degrees clockwise in-place.
"""
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i, n):
# Swap matrix[i][j] with matrix[j][i]
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for i in range(n):
matrix[i].reverse()
Time Complexity
- O(n²) where
n is the number of rows/columns.
Space Complexity
- O(1) extra space (in-place).
4. Word Search (LeetCode #79) - Medium
Problem Statement
Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells (horizontally or vertically). The same cell cannot be used more than once.
Intuition
This is a classic Backtracking problem where we need to explore all possible paths on the board that could form the given word.
Approach
- Iterate over each cell in the grid.
- For each cell that matches the first character of the word, start a DFS (Depth-First Search).
- In the DFS:
- Check if the current cell matches the current character.
- Temporarily mark the cell as visited to avoid revisiting.
- Explore all four directions (up, down, left, right).
- Backtrack by unmarking the cell if the path does not lead to a solution.
Python Solution
def exist(board, word):
"""
Returns True if the word exists in the grid, False otherwise.
"""
if not board:
return False
rows, cols = len(board), len(board[0])
def dfs(r, c, index):
if index == len(word):
return True
# Check boundaries and current character match
if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[index]:
return False
# To avoid revisiting, mark the cell as visited
temp = board[r][c]
board[r][c] = '#'
# Explore all directions
found = (dfs(r+1, c, index+1) or
dfs(r-1, c, index+1) or
dfs(r, c+1, index+1) or
dfs(r, c-1, index+1))
# Backtrack
board[r][c] = temp
return found
for i in range(rows):
for j in range(cols):
if dfs(i, j, 0):
return True
return False
Time Complexity
- O(mn * 4^k) where
m and n are the dimensions of the board, and k is the length of the word.
Space Complexity
- O(k) for the recursion stack, where
k is the length of the word.
5. Valid Sudoku (LeetCode #36) - Medium
Problem Statement
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to Sudoku rules.
Intuition
To validate the Sudoku board:
- Each row must contain the digits
1-9 without repetition.
- Each column must contain the digits
1-9 without repetition.
- Each of the nine
3x3 sub-boxes must contain the digits 1-9 without repetition.
Approach
- Use three sets to keep track of seen numbers in rows, columns, and sub-boxes.
- Iterate through each cell:
- Skip empty cells (denoted by
.).
- Check if the number has already been seen in the current row, column, or sub-box.
- If it has, return
False.
- Otherwise, add the number to the respective sets.
Python Solution
def isValidSudoku(board):
"""
Returns True if the Sudoku board is valid, False otherwise.
"""
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
boxes = [set() for _ in range(9)] # 3x3 boxes
for i in range(9):
for j in range(9):
num = board[i][j]
if num == '.':
continue
# Check row
if num in rows[i]:
return False
rows[i].add(num)
# Check column
if num in cols[j]:
return False
cols[j].add(num)
# Check box
box_index = (i // 3) * 3 + (j // 3)
if num in boxes[box_index]:
return False
boxes[box_index].add(num)
return True
Time Complexity
- O(1) since the board size is fixed (
9x9).
Space Complexity
- O(1) extra space (fixed size sets).
6. Game of Life (LeetCode #289) - Medium
Problem Statement
Given an m x n grid representing the Game of Life, compute the next state of the grid. The rules are applied simultaneously to every cell.
Rules:
- Any live cell with fewer than two live neighbors dies (underpopulation).
- Any live cell with two or three live neighbors lives on to the next generation.
- Any live cell with more than three live neighbors dies (overpopulation).
- Any dead cell with exactly three live neighbors becomes a live cell (reproduction).
Intuition
To compute the next state in-place without using extra space, we can use specific markers to denote state changes:
1 -> Live
0 -> Dead
2 -> Live to Dead
-1 -> Dead to Live
After computing all changes, we can finalize the grid by converting 2 to 0 and -1 to 1.
Approach
- Iterate through each cell and count its live neighbors.
- Apply the rules and mark state changes using the intermediate states.
- Iterate again to finalize the grid by converting intermediate states to final states.
Python Solution
def gameOfLife(board):
"""
Computes the next state of the board in-place.
"""
if not board or not board[0]:
return
rows, cols = len(board), len(board[0])
# Directions to the 8 neighbors
directions = [(-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 1),
(1, -1), (1, 0), (1, 1)]
for r in range(rows):
for c in range(cols):
live_neighbors = 0
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
if abs(board[nr][nc]) == 1:
live_neighbors += 1
# Apply rules
if board[r][c] == 1:
if live_neighbors < 2 or live_neighbors > 3:
board[r][c] = 2 # Live to Dead
else:
if live_neighbors == 3:
board[r][c] = -1 # Dead to Live
# Finalize the board
for r in range(rows):
for c in range(cols):
if board[r][c] == 2:
board[r][c] = 0
elif board[r][c] == -1:
board[r][c] = 1
Time Complexity
- O(mn) where
m and n are the grid dimensions.
Space Complexity
- O(1) extra space (in-place).
🛠️ Stack Problems
1. Min Stack (LeetCode #155) - Medium
Problem Statement
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Intuition
To achieve constant time retrieval of the minimum element, we can use an auxiliary stack to keep track of the minimums. Each time we push a new element, we also push the new minimum onto the auxiliary stack.
Approach
- Main Stack: Stores all the elements.
- Min Stack: Stores the current minimum after each push.
Python Solution
class MinStack:
def __init__(self):
"""
Initialize two stacks:
- stack: to store all elements.
- min_stack: to store the current minimum.
"""
self.stack = []
self.min_stack = []
def push(self, val: int) -> None:
self.stack.append(val)
# If min_stack is empty or val is <= current minimum, push it to min_stack
if not self.min_stack or val <= self.min_stack[-1]:
self.min_stack.append(val)
def pop(self) -> None:
if self.stack:
val = self.stack.pop()
# If the popped value is the current minimum, pop it from min_stack as well
if val == self.min_stack[-1]:
self.min_stack.pop()
def top(self) -> int:
if self.stack:
return self.stack[-1]
return None
def getMin(self) -> int:
if self.min_stack:
return self.min_stack[-1]
return None
Usage Example
min_stack = MinStack()
min_stack.push(-2)
min_stack.push(0)
min_stack.push(-3)
print(min_stack.getMin()) # Output: -3
min_stack.pop()
print(min_stack.top()) # Output: 0
print(min_stack.getMin()) # Output: -2
Time Complexity
- All operations (
push, pop, top, getMin) are O(1).
Space Complexity
- O(n) where
n is the number of elements in the stack.
2. Minimum Remove to Make Valid Parentheses (LeetCode #1249) - Medium
Problem Statement
Given a string s of '(', ')', and lowercase English letters, remove the minimum number of parentheses to make the string valid. Return any valid string.
Intuition
To make the string valid, we need to ensure that every opening parenthesis '(' has a corresponding closing parenthesis ')' and vice versa. We can track the indices of parentheses to remove using a stack.
Approach
- Initialize a stack to keep track of indices of
'('.
- Iterate through the string:
- If the character is
'(', push its index onto the stack.
- If the character is
')':
- If the stack is not empty, pop from the stack (a matching
'(' is found).
- Else, mark this
')' as invalid.
- After iteration, any indices remaining in the stack are unmatched
'('.
- Remove all invalid indices and build the final string.
Python Solution
def minRemoveToMakeValid(s):
"""
Removes the minimum number of parentheses to make the string valid.
"""
stack = []
to_remove = set()
# First pass to identify invalid parentheses
for i, char in enumerate(s):
if char == '(':
stack.append(i)
elif char == ')':
if stack:
stack.pop()
else:
to_remove.add(i)
# Add remaining '(' indices to removal set
to_remove = to_remove.union(set(stack))
# Build the resulting string
result = []
for i, char in enumerate(s):
if i not in to_remove:
result.append(char)
return ''.join(result)
Example
s = "a)b(c)d"
print(minRemoveToMakeValid(s)) # Output: "ab(c)d"
s = "))(("
print(minRemoveToMakeValid(s)) # Output: ""
Time Complexity
- O(n) where
n is the length of the string.
Space Complexity
- O(n) for the stack and the
to_remove set.
3. Valid Parentheses (LeetCode #20) - Medium
Problem Statement
Given a string containing just the characters '(', ')', '{', '}', '[', and ']', determine if the input string is valid.
Intuition
Use a stack to ensure that every closing bracket corresponds to the most recent opening bracket.
Approach
- Initialize an empty stack.
- Iterate through each character in the string:
- If it's an opening bracket, push it onto the stack.
- If it's a closing bracket:
- Check if the stack is not empty and the top of the stack matches the corresponding opening bracket.
- If it matches, pop from the stack.
- Else, return
False.
- After iteration, if the stack is empty, the string is valid.
Python Solution
def isValid(s):
"""
Determines if the input string has valid parentheses.
"""
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping.values():
stack.append(char)
elif char in mapping:
if stack and stack[-1] == mapping[char]:
stack.pop()
else:
return False
# Ignore other characters if any
return not stack
Examples
print(isValid("()")) # Output: True
print(isValid("()[]{}")) # Output: True
print(isValid("(]")) # Output: False
Time Complexity
- O(n) where
n is the length of the string.
Space Complexity
4. Evaluate Reverse Polish Notation (LeetCode #150) - Medium
Problem Statement
Evaluate the value of an arithmetic expression in Reverse Polish Notation (RPN). Valid operators are '+', '-', '*', and '/'. Each operand may be an integer or another expression.
Intuition
Use a stack to evaluate the expression:
- When an operand is encountered, push it onto the stack.
- When an operator is encountered, pop the top two operands, apply the operator, and push the result back.
Approach
- Initialize an empty stack.
- Iterate through each token:
- If it's a number, convert and push it to the stack.
- If it's an operator, pop two numbers, apply the operator, and push the result.
- The final result is the last element in the stack.
Python Solution
def evalRPN(tokens):
"""
Evaluates the value of an arithmetic expression in Reverse Polish Notation.
"""
stack = []
operators = {'+', '-', '*', '/'}
for token in tokens:
if token not in operators:
stack.append(int(token))
else:
# Pop the operands in reverse order
b = stack.pop()
a = stack.pop()
if token == '+':
res = a + b
elif token == '-':
res = a - b
elif token == '*':
res = a * b
elif token == '/':
# Python division truncates towards negative infinity, so we need to convert to int for truncation towards zero
res = int(a / b)
stack.append(res)
return stack[0] if stack else 0
Examples
print(evalRPN(["2","1","+","3","*"])) # Output: 9
print(evalRPN(["4","13","5","/","+"])) # Output: 6
print(evalRPN(["10","6","9","3","+","-11","*","/","*","17","+","5","+"])) # Output: 22
Time Complexity
- O(n) where
n is the number of tokens.
Space Complexity
5. Generate Parentheses (LeetCode #22) - Medium
Problem Statement
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Intuition
This is a classic Backtracking problem. We need to generate all valid sequences by ensuring that at any point, the number of closing parentheses does not exceed the number of opening ones.
Approach
- Use backtracking to build the parentheses string.
- Keep track of the number of opening and closing parentheses used.
- Add a parenthesis if it doesn't lead to an invalid sequence.
- When the string reaches
2n length, it's a valid combination.
Python Solution
def generateParenthesis(n):
"""
Generates all combinations of well-formed parentheses.
"""
result = []
def backtrack(s, left, right):
if len(s) == 2 * n:
result.append(s)
return
if left < n:
backtrack(s + '(', left + 1, right)
if right < left:
backtrack(s + ')', left, right + 1)
backtrack('', 0, 0)
return result
Example
print(generateParenthesis(3))
# Output: ["((()))","(()())","(())()","()(())","()()()"]
Time Complexity
- Catalan Number: O(4^n / sqrt(n))
Space Complexity
- O(n) for the recursion stack.
6. Daily Temperatures (LeetCode #739) - Medium
Problem Statement
Given a list of daily temperatures, return a list such that for each day, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
Intuition
Use a stack to keep track of indices of temperatures. Traverse the list, and for each temperature, pop indices from the stack where current temperature is higher. Calculate the difference in days.
Approach
- Initialize a stack to store indices.
- Iterate through the temperatures:
- While the current temperature is greater than the temperature at the index on top of the stack:
- Pop the index and set the result for that day.
- Push the current index onto the stack.
- Remaining indices in the stack have no warmer days, set them to
0.
Python Solution
def dailyTemperatures(T):
"""
Returns a list indicating how many days to wait for a warmer temperature.
"""
n = len(T)
result = [0] * n
stack = [] # Stores indices
for i in range(n):
while stack and T[i] > T[stack[-1]]:
idx = stack.pop()
result[idx] = i - idx
stack.append(i)
return result
Example
print(dailyTemperatures([73,74,75,71,69,72,76,73]))
# Output: [1,1,4,2,1,1,0,0]
Time Complexity
- O(n) where
n is the number of temperatures.
Space Complexity
7. Car Fleet (LeetCode #853) - Medium
Problem Statement
There are n cars going to the same destination along a one-lane road. Each car has a speed and a starting position. A car can never pass another car ahead of it, but it can catch up to it, forming a fleet. Determine how many fleets will arrive at the destination.
Intuition
Sort the cars based on their starting positions in descending order. Compute the time each car will take to reach the destination. A new fleet is formed if a car takes more time than the current slowest fleet.
Approach
- Pair each car's position with its speed.
- Sort the cars by position in descending order.
- Iterate through the sorted cars and calculate the time to reach the destination.
- Compare with the current fleet's time:
- If the current car's time is greater, it forms a new fleet.
- Else, it joins the existing fleet.
Python Solution
def carFleet(target, position, speed):
"""
Returns the number of car fleets that will arrive at the destination.
"""
cars = sorted(zip(position, speed), reverse=True)
stack = []
for pos, spd in cars:
time = (target - pos) / spd
if not stack or time > stack[-1]:
stack.append(time)
return len(stack)
Example
print(carFleet(12, [10,8,0,5,3], [2,4,1,1,3]))
# Output: 3
Time Complexity
- O(n log n) due to sorting.
Space Complexity
🌳 Tree Problems
1. Invert Binary Tree (LeetCode #226) - Easy
Problem Statement
Invert a binary tree.
Intuition
Swapping the left and right children of every node results in the inverted tree.
Approach
- Recursive: Swap the left and right children at each node.
- Iterative: Use BFS or DFS to traverse and swap children.
Python Solution (Recursive)
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def invertTree(root):
"""
Inverts a binary tree and returns its root.
"""
if root is None:
return None
# Swap the left and right children
root.left, root.right = invertTree(root.right), invertTree(root.left)
return root
Time Complexity
- O(n) where
n is the number of nodes.
Space Complexity
- O(n) due to recursion stack in the worst case.
2. Maximum Depth of Binary Tree (LeetCode #104) - Easy
Problem Statement
Find the maximum depth of a binary tree.
Intuition
The maximum depth is the longest path from the root to a leaf node. It can be found using recursion by computing the depth of each subtree.
Approach
- Recursive: The maximum depth is
1 + max(left_depth, right_depth).
- Iterative: Use level-order traversal (BFS) and count the levels.
Python Solution (Recursive)
def maxDepth(root):
"""
Returns the maximum depth of the binary tree.
"""
if root is None:
return 0
else:
return 1 + max(maxDepth(root.left), maxDepth(root.right))
Time Complexity
- O(n) where
n is the number of nodes.
Space Complexity
- O(n) for the recursion stack in the worst case.
3. Diameter of Binary Tree (LeetCode #543) - Easy
Problem Statement
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter is the length of the longest path between any two nodes.
Intuition
The diameter can pass through the root or not. For each node, the diameter passing through it is the sum of the depths of its left and right subtrees.
Approach
- Initialize a variable to keep track of the maximum diameter.
- Use a helper function to compute the depth of each subtree.
- Update the maximum diameter at each node.
Python Solution
def diameterOfBinaryTree(root):
"""
Returns the diameter of the binary tree.
"""
diameter = 0
def depth(node):
nonlocal diameter
if not node:
return 0
left = depth(node.left)
right = depth(node.right)
diameter = max(diameter, left + right)
return 1 + max(left, right)
depth(root)
return diameter
Time Complexity
- O(n) where
n is the number of nodes.
Space Complexity
- O(n) for the recursion stack in the worst case.
4. Balanced Binary Tree (LeetCode #110) - Easy
Problem Statement
Determine if a binary tree is height-balanced (the depth of the two subtrees of every node never differs by more than one).
Intuition
For each node, check the depths of the left and right subtrees. If the difference is more than one at any node, it's unbalanced.
Approach
- Use a helper function to compute the depth.
- If a subtree is unbalanced, propagate a special value (e.g.,
-1).
Python Solution
def isBalanced(root):
"""
Determines if the binary tree is height-balanced.
"""
def check(node):
if node is None:
return 0
left = check(node.left)
if left == -1:
return -1
right = check(node.right)
if right == -1:
return -1
if abs(left - right) > 1:
return -1
return 1 + max(left, right)
return check(root) != -1
Time Complexity
- O(n) where
n is the number of nodes.
Space Complexity
- O(n) for the recursion stack in the worst case.
5. Same Tree (LeetCode #100) - Easy
Problem Statement
Given two binary trees, write a function to check if they are the same or not.
Intuition
Two trees are the same if their structures are identical and all corresponding nodes have the same values.
Approach
- Compare the roots.
- Recursively compare the left and right subtrees.
Python Solution
def isSameTree(p, q):
"""
Determines if two binary trees are the same.
"""
if not p and not q:
return True
if not p or not q:
return False
if p.val != q.val:
return False
return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
Time Complexity
- O(n) where
n is the number of nodes.
Space Complexity
- O(n) for the recursion stack in the worst case.
6. Subtree of Another Tree (LeetCode #572) - Easy
Problem Statement
Given two binary trees s and t, check if t is a subtree of s.
Intuition
Traverse the larger tree and for each node, check if the subtree rooted at that node matches the smaller tree.
Approach
- Traverse tree
s and at each node, check if the subtree matches t.
- Use the
isSameTree helper function to compare subtrees.
Python Solution
def isSubtree(s, t):
"""
Determines if tree t is a subtree of tree s.
"""
if not t:
return True
if not s:
return False
if isSameTree(s, t):
return True
return isSubtree(s.left, t) or isSubtree(s.right, t)
def isSameTree(p, q):
if not p and not q:
return True
if not p or not q:
return False
if p.val != q.val:
return False
return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
Time Complexity
- O(mn) where
m is the number of nodes in s and n is the number of nodes in t.
Space Complexity
- O(m+n) for the recursion stack.
7. Lowest Common Ancestor of a Binary Search Tree (LeetCode #235) - Medium
Problem Statement
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
Intuition
In a BST, for two nodes p and q:
- If both are less than the current node, LCA lies in the left subtree.
- If both are greater, LCA lies in the right subtree.
- Otherwise, the current node is the LCA.
Approach
- Start from the root.
- Compare the values of
p and q with the current node.
- Traverse left or right based on the comparison.
- Return the current node when it's between
p and q.
Python Solution
def lowestCommonAncestor(root, p, q):
"""
Finds the LCA of two nodes in a BST.
"""
current = root
while current:
if p.val < current.val and q.val < current.val:
current = current.left
elif p.val > current.val and q.val > current.val:
current = current.right
else:
return current
return None
Time Complexity
- O(h) where
h is the height of the tree.
Space Complexity
8. Binary Tree Level Order Traversal (LeetCode #102) - Medium
Problem Statement
Given a binary tree, return the level order traversal of its nodes' values.
Intuition
Use Breadth-First Search (BFS) to traverse the tree level by level.
Approach
- Use a queue to keep track of nodes at the current level.
- While the queue is not empty:
- Iterate through the current level and enqueue their children.
- Add the current level's values to the result.
Python Solution
from collections import deque
def levelOrder(root):
"""
Returns the level order traversal of a binary tree.
"""
if not root:
return []
result, queue = [], deque([root])
while queue:
level_size = len(queue)
level = []
for _ in range(level_size):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level)
return result
Example
# Given binary tree [3,9,20,null,null,15,7]
# 3
# / \
# 9 20
# / \
# 15 7
# Output: [[3], [9,20], [15,7]]
Time Complexity
- O(n) where
n is the number of nodes.
Space Complexity
9. Binary Tree Right Side View (LeetCode #199) - Medium
Problem Statement
Given a binary tree, return the values of the nodes you can see ordered from top to bottom when looking from the right side.
Intuition
For each level, capture the last node encountered (the rightmost node).
Approach
- Perform BFS (level-order traversal).
- For each level, record the last node's value.
Python Solution
from collections import deque
def rightSideView(root):
"""
Returns the right side view of the binary tree.
"""
if not root:
return []
view = []
queue = deque([root])
while queue:
level_size = len(queue)
for i in range(level_size):
node = queue.popleft()
# If it's the last node in the level, add to view
if i == level_size - 1:
view.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return view
Example
# Given binary tree [1,2,3,null,5,null,4]
# 1
# / \
# 2 3
# \ \
# 5 4
# Output: [1,3,4]
Time Complexity
- O(n) where
n is the number of nodes.
Space Complexity
10. Count Good Nodes In Binary Tree (LeetCode #1448) - Medium
Problem Statement
A node X in the binary tree is named good if in the path from root to X, there are no nodes with a value greater than X. Return the number of good nodes in the binary tree.
Intuition
Traverse the tree and keep track of the maximum value encountered so far. A node is good if its value is greater than or equal to this maximum.
Approach
- Use DFS (preorder traversal).
- Pass down the current maximum value.
- If the current node's value is >= max value, it's a good node.
- Update the max value and continue recursion.
Python Solution
def goodNodes(root):
"""
Returns the number of good nodes in the binary tree.
"""
def dfs(node, max_val):
if not node:
return 0
count = 1 if node.val >= max_val else 0
max_val = max(max_val, node.val)
count += dfs(node.left, max_val)
count += dfs(node.right, max_val)
return count
return dfs(root, root.val if root else float('-inf'))
Example
# Input: root = [3,1,4,3,null,1,5]
# Output: 4
Time Complexity
- O(n) where
n is the number of nodes.
Space Complexity
- O(n) for the recursion stack.
11. Validate Binary Search Tree (LeetCode #98) - Medium
Problem Statement
Given a binary tree, determine if it is a valid Binary Search Tree (BST).
Definition of BST:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
Intuition
Use in-order traversal to verify if the sequence of node values is strictly increasing.
Approach
- Perform in-order traversal.
- Check if each node's value is greater than the previous node's value.
Python Solution
def isValidBST(root):
"""
Determines if the binary tree is a valid BST.
"""
stack = []
prev = None
current = root
while stack or current:
while current:
stack.append(current)
current = current.left
current = stack.pop()
# Check the BST property
if prev is not None and current.val <= prev:
return False
prev = current.val
current = current.right
return True
Time Complexity
- O(n) where
n is the number of nodes.
Space Complexity
12. Kth Smallest Element in a BST (LeetCode #230) - Medium
Problem Statement
Find the k-th smallest element in a BST.
Intuition
An in-order traversal of a BST yields the elements in sorted order. Thus, the k-th element in an in-order traversal is the k-th smallest.
Approach
- Perform in-order traversal.
- Keep a counter and return the value when the counter reaches k.
Python Solution
def kthSmallest(root, k):
"""
Returns the k-th smallest element in a BST.
"""
stack = []
current = root
count = 0
while stack or current:
while current:
stack.append(current)
current = current.left
current = stack.pop()
count += 1
if count == k:
return current.val
current = current.right
Time Complexity
Space Complexity
13. Construct Binary Tree From Preorder and Inorder Traversal (LeetCode #105) - Medium
Problem Statement
Given preorder and inorder traversal of a tree, construct the binary tree.
Intuition
The first element in the preorder list is the root. Find this root in the inorder list to divide the list into left and right subtrees.
Approach
- Use a hash map to store the indices of inorder elements for quick lookup.
- Recursively build the tree by selecting the root from preorder and partitioning inorder accordingly.
Python Solution
def buildTree(preorder, inorder):
"""
Constructs a binary tree from preorder and inorder traversal lists.
"""
if not preorder or not inorder:
return None
# Map from value to its index in inorder
inorder_index_map = {val: idx for idx, val in enumerate(inorder)}
def helper(pre_start, pre_end, in_start, in_end):
if pre_start > pre_end or in_start > in_end:
return None
root_val = preorder[pre_start]
root = TreeNode(root_val)
in_root_index = inorder_index_map[root_val]
left_size = in_root_index - in_start
root.left = helper(pre_start + 1, pre_start + left_size, in_start, in_root_index - 1)
root.right = helper(pre_start + left_size + 1, pre_end, in_root_index + 1, in_end)
return root
return helper(0, len(preorder)-1, 0, len(inorder)-1)
Time Complexity
- O(n) where
n is the number of nodes.
Space Complexity
- O(n) for the hash map and recursion stack.
14. Binary Tree Zigzag Level Order Traversal (LeetCode #103) - Medium
Problem Statement
Given a binary tree, return the zigzag level order traversal of its nodes' values.
Intuition
Perform BFS but alternate the order of traversal at each level (left-to-right, then right-to-left).
Approach
- Use a queue for BFS.
- Use a flag to indicate the direction of traversal.
- Reverse the level list based on the flag.
Python Solution
from collections import deque
def zigzagLevelOrder(root):
"""
Returns the zigzag level order traversal of a binary tree.
"""
if not root:
return []
result = []
queue = deque([root])
left_to_right = True
while queue:
level_size = len(queue)
level = deque()
for _ in range(level_size):
node = queue.popleft()
if left_to_right:
level.append(node.val)
else:
level.appendleft(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(list(level))
left_to_right = not left_to_right
return result
Example
# Given binary tree [3,9,20,null,null,15,7]
# Output: [[3], [20,9], [15,7]]
Time Complexity
- O(n) where
n is the number of nodes.
Space Complexity
15. Implement Trie (Prefix Tree) (LeetCode #208) - Medium
Problem Statement
Implement a trie with insert, search, and startsWith methods.
Intuition
A Trie is a tree-like data structure used for efficient retrieval of a key in a large dataset of strings. Each node represents a character.
Approach
- TrieNode Class: Represents each node in the Trie.
- Trie Class: Implements the
insert, search, and startsWith methods by traversing the Trie based on the input string.
Python Solution
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
"""
Initialize the Trie.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_end
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
node = self.root
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return True
Example
trie = Trie()
trie.insert("apple")
print(trie.search("apple")) # Output: True
print(trie.search("app")) # Output: False
print(trie.startsWith("app")) # Output: True
trie.insert("app")
print(trie.search("app")) # Output: True
Time Complexity
- O(m) for each operation, where
m is the length of the word/prefix.
Space Complexity
- O(n * m) where
n is the number of words and m is the average length.
16. Add and Search Word (LeetCode #211) - Medium
Problem Statement
Implement a data structure that supports adding new words and searching for a string where '.' can represent any one letter.
Intuition
Use a Trie to store words. For the search with wildcards, perform DFS when encountering '.' to explore all possible paths.
Approach
- TrieNode Class: Represents each node.
- WordDictionary Class:
addWord inserts a word into the Trie.
search handles exact matches and wildcards using DFS.
Python Solution
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class WordDictionary:
def __init__(self):
"""
Initialize the WordDictionary.
"""
self.root = TrieNode()
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure.
A '.' can represent any one letter.
"""
def dfs(node, i):
if i == len(word):
return node.is_end
char = word[i]
if char == '.':
for child in node.children.values():
if dfs(child, i + 1):
return True
return False
else:
if char not in node.children:
return False
return dfs(node.children[char], i + 1)
return dfs(self.root, 0)
Example
wordDictionary = WordDictionary()
wordDictionary.addWord("bad")
wordDictionary.addWord("dad")
wordDictionary.addWord("mad")
print(wordDictionary.search("pad")) # Output: False
print(wordDictionary.search("bad")) # Output: True
print(wordDictionary.search(".ad")) # Output: True
print(wordDictionary.search("b..")) # Output: True
Time Complexity
- O(m) for adding words.
- O(n * m) for searching with wildcards (
n is number of nodes at depth).
Space Complexity
- O(n * m) for storing words.
17. Word Search II (LeetCode #212) - Hard
Note: Although marked as Hard, including it for completeness.
🛤️ Graph Problems
1. Course Schedule (LeetCode #207) - Medium
Problem Statement
There are numCourses courses you have to take, labeled from 0 to numCourses-1. Some courses may have prerequisites, given as pairs [a, b] where you must take course b before course a. Determine if it's possible to finish all courses.
Intuition
This is a classic Cycle Detection problem in a directed graph. If the graph has a cycle, it's impossible to complete all courses.
Approach
Use Topological Sorting via BFS (Kahn's Algorithm):
- Build the adjacency list and in-degree array.
- Initialize a queue with nodes having in-degree
0.
- Process nodes by reducing in-degrees of neighbors.
- If all nodes are processed, return
True; else, False.
Python Solution
from collections import deque, defaultdict
def canFinish(numCourses, prerequisites):
"""
Determines if it's possible to finish all courses.
"""
adj = defaultdict(list)
in_degree = [0] * numCourses
for dest, src in prerequisites:
adj[src].append(dest)
in_degree[dest] += 1
# Initialize queue with courses having no prerequisites
queue = deque([i for i in range(numCourses) if in_degree[i] == 0])
count = 0
while queue:
course = queue.popleft()
count += 1
for neighbor in adj[course]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)
return count == numCourses
Example
print(canFinish(2, [[1,0]])) # Output: True
print(canFinish(2, [[1,0],[0,1]])) # Output: False
Time Complexity
- O(V + E) where
V is number of courses and E is number of prerequisites.
Space Complexity
- O(V + E) for adjacency list and in-degree array.
2. Course Schedule II (LeetCode #210) - Medium
Problem Statement
Return the ordering of courses you should take to finish all courses. If impossible, return an empty array.
Intuition
Similar to "Course Schedule", but requires returning the actual ordering. Use Topological Sorting via BFS.
Approach
- Build adjacency list and in-degree array.
- Initialize queue with courses having in-degree
0.
- Process the queue, appending to the result.
- If the result includes all courses, return it; else, return empty array.
Python Solution
from collections import deque, defaultdict
def findOrder(numCourses, prerequisites):
"""
Returns the order of courses to finish all courses.
"""
adj = defaultdict(list)
in_degree = [0] * numCourses
for dest, src in prerequisites:
adj[src].append(dest)
in_degree[dest] += 1
queue = deque([i for i in range(numCourses) if in_degree[i] == 0])
order = []
while queue:
course = queue.popleft()
order.append(course)
for neighbor in adj[course]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)
return order if len(order) == numCourses else []
Example
print(findOrder(2, [[1,0]])) # Output: [0,1]
print(findOrder(2, [[1,0],[0,1]])) # Output: []
Time Complexity
- O(V + E) where
V is number of courses and E is number of prerequisites.
Space Complexity
- O(V + E) for adjacency list and in-degree array.
3. Redundant Connection (LeetCode #684) - Medium
Problem Statement
In this problem, a tree is an undirected graph that is connected and has no cycles. You are given a graph that started as a tree with n nodes and added one additional edge. Return the edge that can be removed to make the graph a tree.
Intuition
Use Union-Find (Disjoint Set Union - DSU) to detect the cycle. The first edge that connects two nodes already in the same set forms a cycle.
Approach
- Initialize parent array where each node is its own parent.
- Iterate through edges:
- Find the roots of both nodes.
- If roots are the same, the edge is redundant.
- Else, union the sets.
Python Solution
def findRedundantConnection(edges):
"""
Finds the redundant edge to form a tree.
"""
parent = list(range(len(edges) + 1))
def find(x):
if parent[x] != x:
parent[x] = find(parent[x]) # Path compression
return parent[x]
def union(x, y):
rootX = find(x)
rootY = find(y)
if rootX == rootY:
return False # Cycle detected
parent[rootY] = rootX
return True
for edge in edges:
if not union(edge[0], edge[1]):
return edge
return []
Example
print(findRedundantConnection([[1,2],[1,3],[2,3]])) # Output: [2,3]
Time Complexity
- O(n α(n)) where
α(n) is the inverse Ackermann function, practically constant.
Space Complexity
- O(n) for the parent array.
4. Number of Connected Components In An Undirected Graph (LeetCode #323) - Medium
Problem Statement
You have n nodes labeled from 0 to n-1. Given a list of undirected edges, count the number of connected components in the graph.
Intuition
Use Union-Find to group connected nodes and count distinct roots.
Approach
- Initialize parent array where each node is its own parent.
- Iterate through edges and union the connected nodes.
- Count the number of unique parents.
Python Solution
def countComponents(n, edges):
"""
Returns the number of connected components in an undirected graph.
"""
parent = list(range(n))
def find(x):
if parent[x] != x:
parent[x] = find(parent[x]) # Path compression
return parent[x]
def union(x, y):
rootX = find(x)
rootY = find(y)
if rootX != rootY:
parent[rootY] = rootX
for x, y in edges:
union(x, y)
# Count unique parents
return len(set(find(x) for x in range(n)))
Example
print(countComponents(5, [[0,1],[1,2],[3,4]])) # Output: 2
Time Complexity
- O(n α(n)) where
α(n) is the inverse Ackermann function, practically constant.
Space Complexity
- O(n) for the parent array.
5. Graph Valid Tree (LeetCode #261) - Medium
Problem Statement
Given n nodes labeled from 0 to n-1 and a list of undirected edges, determine if the edges make a valid tree.
Intuition
A graph is a tree if it is connected and has no cycles. Utilize Union-Find to check for cycles and connectivity.
Approach
- If the number of edges is not
n-1, it cannot be a tree.
- Use Union-Find to detect cycles.
- If no cycles and edges ==
n-1, it's a tree.
Python Solution
def validTree(n, edges):
"""
Determines if the given edges form a valid tree.
"""
if len(edges) != n - 1:
return False
parent = list(range(n))
def find(x):
if parent[x] != x:
parent[x] = find(parent[x]) # Path compression
return parent[x]
def union(x, y):
rootX = find(x)
rootY = find(y)
if rootX == rootY:
return False # Cycle detected
parent[rootY] = rootX
return True
for x, y in edges:
if not union(x, y):
return False
return True
Example
print(validTree(5, [[0,1],[0,2],[0,3],[1,4]])) # Output: True
print(validTree(5, [[0,1],[1,2],[2,3],[1,3],[1,4]])) # Output: False
Time Complexity
- O(n α(n)) where
α(n) is the inverse Ackermann function, practically constant.
Space Complexity
- O(n) for the parent array.
6. Word Ladder (LeetCode #127) - Hard
Note: Although marked as Hard, including it for completeness.
🚆 Conclusion
This comprehensive guide covers essential Easy and Medium DSA problems across Matrix, Stack, Tree, and Graph categories. Each problem is dissected with a clear intuition, step-by-step approach, and efficient Python code implementation. Studying these problems will solidify your understanding and prepare you effectively for technical interviews. Remember to practice regularly and understand the underlying concepts to excel!
If you have any specific problems you'd like further assistance with or need explanations for other categories, feel free to ask!