leetcode_slides
leetcode_slides
This presentation covers a wide range of LeetCode problems organized by data structures and algorithms, providing approaches,
solutions, and complexity analysis for each problem.
Techniques for handling sequences of Problems involving sequential access data Binary trees, BSTs, traversal methods, and
elements including sliding window, two structures and pointer manipulation tree manipulation algorithms.
pointers, and more. techniques.
BFS, DFS, and other graph algorithms to Priority queue implementations and Breaking down complex problems into
solve network and connectivity problems. problems involving finding kth elements. simpler subproblems with overlapping
solutions.
Read the problem twice. Verbalize different approaches. Code your solution step by Test with examples. Analyze
Identify inputs, outputs, and Start with a brute force step. Focus on readability and edge cases. Evaluate time and
constraints. Ask clarifying solution, then optimize. Identify correctness before space complexity.
questions. patterns. optimization.
Arrays Linked Lists Stacks Queues Trees Graphs
2 / 20
Array Problems
Fundamental techniques for handling sequences of elements
Find if array contains any duplicate values. Find two numbers that add up to target. Find the missing number in range [0,n].
Find Disappeared Numbers Smaller Than Current Min Time to Visit Points
Find all missing integers in range [1,n]. Count numbers smaller than current number. Find minimum time to visit all points in a 2D
plane.
Input: [4,3,2,7,8,2,3,1] Input: [8,1,2,2,3]
Output: [5,6] Output: [4,0,1,1,3] Input: [[1,1],[3,4],[-1,0]]
Output: 7
3 / 20
Array Techniques: Two Pointers & Sliding Window
Efficient approaches for solving array problems
Best Time to Buy and Sell Stock Squares of a Sorted Array = 3Sum
Find the maximum profit by buying low and selling Return sorted array of squared values. Find all triplets that sum to zero.
high.
Input: [-4,-1,0,3,10] Input: [-1,0,1,2,-1,-4]
Input: [7,1,5,3,6,4] Output: [0,1,9,16,100] Output: [[-1,-1,2],[-1,0,1]]
Output: 5
Use two pointers (left & right) to compare absolute values Sort array, then for each element, use two pointers to find
Use left pointer for buying day and right pointer to check and build sorted result array from the end. pairs that sum to target. Skip duplicates.
potential selling days, tracking maximum profit. O(n) O(n) O(n²) O(n)
O(n) O(1)
Find if duplicates exist within k distance. Find pairs with smallest absolute difference. Find smallest subarray with sum ≥ target.
Maintain a sliding window of size k using a set, adding new Sort array, then use a sliding window of size 2 to compare Use variable-size sliding window - expand right until sum ≥
elements and removing elements that fall outside window. adjacent elements and find minimum difference. target, then contract left to minimize length.
O(n) O(k) O(n log n) O(n) O(n) O(1)
Key Insights:
Two pointers often turn O(n²) solutions into O(n) Sliding window works great for substring/subarray problems
Pre-sorting can make both techniques more effective Hash sets/maps can optimize window operations
4 / 20
Bit Manipulation & Dynamic Programming
Low-level operations and optimization techniques 10110
Bit Manipulation
Operations on individual bits in binary representations 01001
Single Number
Find the element that appears once in an array where every other element
11010
Counting Bits
00101
appears twice. from 0 to n.
10011
Solution Approach: Solution Approach:
Use XOR (^) operation. XOR of any number with itself is 0, and XOR with 0 Use dynamic programming where dp[i] = dp[i & (i-1)] + 1. Each value is 1 + the
returns the original number. count in the number with the rightmost 1 removed.
AND
1 &
1 &
(&)
1 = 1
0 = 0
OR (|)
1 | 1 = 1
1 | 0 = 1
01100 XOR
1 ^
1 ^
(^)
1 = 0
0 = 1
11001
0 & 0 = 0 0 | 0 = 0 0 ^ 0 = 0
Dynamic Programming
Breaking down complex problems into simpler sub-problems
Find the fewest number of coins needed to make up a given amount. Count distinct ways to climb n stairs taking 1 or 2 steps at a time.
5 / 20
Backtracking Problems
Building solutions incrementally and backtracking when needed (●)
What is Backtracking? / \
An algorithmic technique that builds a solution incrementally, abandoning a path when it determines the path cannot lead to a valid solution.
Input: "a1b2"
Output: ["a1b2","a1B2","A1b2","A1B2"]
Solution Approach:
Input: [1,2,3]
/ \ / \
Output: [[],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]
Solution Approach:
(●)(●)
Recursively explore each character, creating two branches for alphabetic For each element, make a decision to either include it in the current subset or
characters (uppercase and lowercase) and one branch for digits. exclude it, then recursively build from there.
Time: O(2ⁿ) Space: O(n·2ⁿ) Time: O(n·2ⁿ) Space: O(n·2ⁿ)
Combinations
Input: n = 4, k = 2
(●)(●)
Permutations
Input: [1,2,3]
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
6 / 20
Linked List Problems
Sequential access data structures with dynamic memory allocation
1 2 3 4
Find the middle node of a linked list. Determine if a linked list has a cycle.
Finding the middle, detecting cycles, or finding the Using two pointers at different speeds to process the Restructuring links to reverse parts or all of a linked
nth element from the end. list in a single pass. list.
7 / 20
Stack Problems
Last-In-First-Out (LIFO) data structures
Item 2
Item 3
Design a stack that supports push, pop, top, and retrieving the minimum Check if the input string has valid parentheses ordering.
element, all in constant time.
Input: "({[]})"
push(x), pop(), top(), getMin() Output: true
All operations in O(1) time
Solution Approach:
Solution Approach: Use a stack to keep track of opening brackets. When a closing bracket is
Use a stack of pairs, where each pair contains the element value and the encountered, check if it matches the top element of the stack.
minimum value in the stack at that point. Time: O(n) Space: O(n)
Time: O(1) per operation Space: O(n)
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Sort a stack in ascending or descending order using only stack
operations.
Input: ["2","1","+","3","*"]
Output: 9 ((2 + 1) * 3) Input: [34, 3, 31, 98, 92, 23]
Output: [3, 23, 31, 34, 92, 98]
Solution Approach:
Use a stack to store numbers. When an operator is encountered, pop the top Solution Approach:
two elements, apply the operation, and push the result back onto the stack. Use a temporary stack. For each element in the original stack, pop elements
Time: O(n) Space: O(n) from the temporary stack that are greater, insert the element, then push back
the popped elements.
Python Implementation
When to Use Stacks:
class Stack:
def __init__(self): Implementing undo/redo functionality
self.items = []
Expression evaluation and syntax parsing
def push(self, item): Backtracking algorithms (DFS implementation)
self.items.append(item)
Converting recursion to iteration
def pop(self): Balancing symbol problems
if not self.is_empty():
return self.items.pop()
def peek(self):
if not self.is_empty():
return self.items[-1]
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
8 / 20
Queue Problems
First-In-First-Out (FIFO) data structures
What is a Queue?
A linear data structure that follows the First-In-First-Out (FIFO) principle. Elements are added at the rear and removed from the front.
A B C D ?
Front Rear
Implement Stack using Queues Time Needed to Buy Tickets Reverse First K Elements
Implement a LIFO stack using only FIFO queue Find time needed for a person at position k to buy Reverse the first k elements of a queue.
operations. tickets.
Input: q = [1,2,3,4,5], k = 3
Push, Pop, Top, Empty operations Input: tickets = [2,3,2], k = 2 Output: [3,2,1,4,5]
Using only queue operations Output: 6
Solution Approach:
Solution Approach: Solution Approach: Use a stack to reverse the first k elements: dequeue k
Use a queue to store elements. For push: add element to Calculate time by considering each person's ticket needs. elements and push onto stack, then pop from stack and
queue, then rotate the queue by moving all previous People before k need min(tickets[i], tickets[k]) time. People enqueue. Finally, dequeue and enqueue the remaining n-k
elements to the end to maintain stack order. after k need min(tickets[i], tickets[k]-1) time. elements.
Time: O(n) push, O(1) others Space: O(n) Time: O(n) Space: O(1) Time: O(n) Space: O(k)
def dequeue(self):
if not self.is_empty():
return self.items.popleft()
def peek(self):
if not self.is_empty():
return self.items[0]
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
9 / 20
Binary Tree Problems
Hierarchical data structures with recursive traversal patterns
4 5 6 7
Find the average value of nodes on each level. Find the maximum depth (height) of a binary tree. Check if two binary trees are identical.
Use BFS to process nodes level by level, calculating the Recursively find max depth of left and right subtrees, add 1 Recursively compare corresponding nodes of both trees.
average at each level. for current level. O(n) O(h)
O(n) O(n) O(n) O(h)
Find the length of the longest path between any two Mirror a binary tree by swapping left and right Find the lowest common ancestor of two nodes.
nodes. children.
Input: root=[3,5,1,6,2,0,8], p=5, q=1
Input: [1,2,3,4,5] Input: [4,2,7,1,3,6,9] Output: 3
Output: 3 Output: [4,7,2,9,6,3,1]
Recursively search for p and q. If found in different subtrees,
At each node, calculate diameter as sum of left and right Recursively swap left and right children at each node. current node is LCA.
heights. Track maximum diameter. O(n) O(h) O(n) O(h)
O(n) O(h)
10 / 20
Binary Search Tree Problems
Ordered binary trees with efficient search operations
8
What is a Binary Search Tree?
A special type of binary tree where for each node:
All nodes in left subtree have values < node's value 3 10
All nodes in right subtree have values > node's value
This ordering property enables efficient O(log n) search, insert, and delete operations.
1 6 14
BST Property:
1 < 3 < 6 < 8 < 10 < 14
Inorder traversal gives sorted output
Find a node with given value in a BST. Insert a new node while maintaining BST properties. Create a height-balanced BST from sorted array.
Use BST property: If target < node, go left; if target > node, Traverse to find insertion point: If val < node.val, go left; if Recursively use the middle element as root, left half as left
go right; otherwise found. val > node.val, go right; until null found. subtree, right half as right subtree.
O(h) O(1) O(h) O(1) O(n) O(log n)
Find if two nodes sum to the target value. Delete a node while maintaining BST properties. Find the kth smallest element in a BST.
Use a hash set to store visited values while traversing. For Three cases: 1) No children - remove node; 2) One child - Perform inorder traversal (which visits nodes in ascending
each node, check if (k - node.val) exists in set. replace with child; 3) Two children - replace with successor. order) and stop at the kth node.
O(n) O(n) O(h) O(1) O(h+k) O(h)
11 / 20
Heap Problems
Priority queue implementations for efficient element ordering
9
What is a Heap?
A specialized tree-based data structure that satisfies the heap property:
7 8
Max Heap: Parent node is greater than or equal to its children
Min Heap: Parent node is less than or equal to its children
5 6 3 4
Efficiently supports finding and removing the maximum/minimum element.
Find the kth largest element in an unsorted array. Find the k closest points to the origin (0,0) in a 2D plane.
Time: O(n log k) Space: O(k) Time: O(n log k) Space: O(k)
Find the k most frequent elements in an array. Schedule tasks with cooling time between same tasks.
Time: O(n log k) Space: O(n) Time: O(n log n) Space: O(n)
# Create a heap
heap = []
12 / 20
Graph Problems
Solving complex network and connectivity challenges
What is a Graph?
A collection of nodes (vertices) connected by edges. Graphs can be: A
Directed/Undirected: Edges have direction or not
Weighted/Unweighted: Edges have values or not
B C
Connected/Disconnected: All nodes can reach each other or not
Cyclic/Acyclic: Contains cycles or not
D E
A 2D array where matrix[i][j] indicates if there is an edge from node i to node j. A collection of lists/arrays where the index represents a vertex and the values are its
adjacent vertices.
A B C D E
A [0, 1, 1, 0, 0] A: [B, C]
B [1, 0, 0, 1, 0] B: [A, D]
C [1, 0, 0, 0, 1] C: [A, E]
D [0, 1, 0, 0, 1] D: [B, E]
E [0, 0, 1, 1, 0] E: [C, D]
+ O(1) edge lookup O(V²) space + O(V+E) space efficient O(degree) edge lookup
Uses a queue to explore neighbors before moving to next level Uses a stack (or recursion) to explore as far as possible along a branch
Good for finding shortest path in unweighted graphs Good for topological sorting, cycle detection
Time: O(V+E), Space: O(V) Time: O(V+E), Space: O(V)
Create a deep copy of an undirected graph. Find cheapest price from src to dst with at most K Determine if it's possible to finish all courses given
stops. prerequisites.
Use BFS or DFS to traverse the graph, maintaining a
hashmap of original nodes to their clones. Use modified Bellman-Ford algorithm to relax edges k+1 Use DFS to detect cycles in the directed graph. If a cycle
O(V+E) O(V) times, tracking min cost at each iteration. exists, it's impossible to complete all courses.
O(K*E) O(V) O(V+E) O(V+E)
13 / 20
Advanced Graph Algorithms
Specialized techniques for solving complex graph problems
When to Use:
4 3
MST algorithms are useful for network design problems (connecting cities, designing
A2 1
B 5
C circuit layouts) with minimal total weight.
D E
Linear ordering of vertices such that for every directed edge (u,v), u Maximal subgraphs where every vertex is reachable from every other
comes before v in the ordering. vertex within the subgraph.
Kosaraju's Algorithm
Applications:
Finds all SCCs in a directed graph using two passes of DFS.
Task scheduling with dependencies (as in Course Schedule problem)
Build systems determining compilation order
Time: O(V+E) Space: O(V)
while queue:
node = queue.pop(0)
result.append(node)
for neighbor in graph[node]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)
14 / 20
Common Algorithmic Patterns and Strategies
Recognizing patterns to improve problem-solving efficiency
Backtracking
Two Pointers
Build solutions incrementally, abandoning paths that cannot lead to
Use two pointers to iterate through data structures from opposite valid solutions.
ends or at different speeds. Examples: N-Queens, Permutations, Subsets, Letter Combinations
Examples: Two Sum II, Reverse Linked List, Linked List Cycle
1 2 3 4 5
Identify Pattern Consider Edge Cases Start Simple Trace Examples Optimize & Refine
Recognize which common pattern Empty input, single element, Begin with brute force, then Walk through small examples by Improve time/space complexity
fits the problem duplicates, etc. optimize hand with patterns
15 / 20
Optimizing Your Problem Solving Approach
Techniques to improve efficiency and effectiveness
Trading space for time with maps/sets for O(1) Cache results of expensive function calls to avoid Calculate values once upfront instead of repeatedly.
lookups. recalculation.
prefix_sum = [0]
seen = set() # O(1) lookups @functools.lru_cache for x in nums:
if x in seen: # vs. O(n) list search def fib(n): # Only calculates once prefix_sum.append(prefix_sum[-1] + x)
16 / 20
Effective LeetCode Practice Strategies
Maximizing learning and interview preparation
Timed Practice
Set a timer for 20-45 minutes when solving problems. This simulates Study Solutions Thoroughly
interview conditions and improves your ability to solve problems under Don't just glance at the solution - understand it deeply. Read multiple
pressure. solutions, understand the trade-offs, and identify the patterns being applied.
17 / 20