Landing a job at top tech companies like Google, Amazon, Microsoft, Facebook (Meta), Apple, Netflix, or startups requires mastering specific Data Structures and Algorithms (DSA) patterns. This comprehensive guide covers all the essential patterns with real Java examples from actual interviews and direct LeetCode links.
Table of Contents
- Two Pointers Pattern
- Sliding Window Pattern
- Fast & Slow Pointers Pattern
- Merge Intervals Pattern
- Cyclic Sort Pattern
- In-place Reversal of LinkedList
- Tree Breadth-First Search (BFS)
- Tree Depth-First Search (DFS)
- Two Heaps Pattern
- Subsets Pattern
- Modified Binary Search
- Bitwise XOR Pattern
- Top K Elements
- K-way Merge
- Dynamic Programming Patterns
- Topological Sort
- Graph Algorithms
- Trie Pattern
- Union Find (Disjoint Set)
- Backtracking Pattern
1. Two Pointers Pattern
When to use: When dealing with sorted arrays, palindromes, or when you need to find pairs/triplets with specific conditions.
Time Complexity: Usually O(n) or O(n²)
Space Complexity: O(1)
Key Problems & Companies:
Two Sum II - Input Array Is Sorted
- Companies: Google, Amazon, Microsoft, Apple, Facebook
- Difficulty: Easy
- Interview Frequency: Very High
- LeetCode: 167. Two Sum II - Input Array Is Sorted
public int[] twoSum(int[] numbers, int target) {
int left = 0, right = numbers.length - 1;
while (left < right) {
int sum = numbers[left] + numbers[right];
if (sum == target) {
return new int[]{left + 1, right + 1};
} else if (sum < target) {
left++;
} else {
right--;
}
}
return new int[]{-1, -1};
}
3Sum
- Companies: Amazon, Google, Microsoft, Facebook, Apple, Uber, LinkedIn
- Difficulty: Medium
- Interview Frequency: Very High
- LeetCode: 15. 3Sum
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}
Container With Most Water
- Companies: Amazon, Google, Facebook, Apple, Microsoft
- Difficulty: Medium
- LeetCode: 11. Container With Most Water
Valid Palindrome
- Companies: Facebook, Microsoft, Amazon, Google, Apple
- Difficulty: Easy
- LeetCode: 125. Valid Palindrome
More Two Pointers Problems:
- Trapping Rain Water (Amazon, Google, Facebook, Apple) - 42. Trapping Rain Water
- 4Sum (Google, Amazon, Microsoft) - 18. 4Sum
- Remove Duplicates from Sorted Array (Google, Amazon, Microsoft) - 26. Remove Duplicates from Sorted Array
- Sort Colors (Google, Microsoft, Facebook) - 75. Sort Colors
- Squares of a Sorted Array (Facebook, Amazon, Google) - 977. Squares of a Sorted Array
2. Sliding Window Pattern
When to use: When dealing with subarrays/substrings with specific conditions (max/min length, sum, distinct characters).
Time Complexity: O(n)
Space Complexity: O(1) to O(k)
Key Problems & Companies:
Longest Substring Without Repeating Characters
- Companies: Amazon, Google, Microsoft, Facebook, Apple, Netflix, Uber
- Difficulty: Medium
- Interview Frequency: Very High
- LeetCode: 3. Longest Substring Without Repeating Characters
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> charMap = new HashMap<>();
int left = 0, maxLength = 0;
for (int right = 0; right < s.length(); right++) {
char rightChar = s.charAt(right);
if (charMap.containsKey(rightChar) && charMap.get(rightChar) >= left) {
left = charMap.get(rightChar) + 1;
}
charMap.put(rightChar, right);
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
Minimum Window Substring
- Companies: Google, Facebook, Amazon, Microsoft, Uber, LinkedIn
- Difficulty: Hard
- Interview Frequency: High
- LeetCode: 76. Minimum Window Substring
public String minWindow(String s, String t) {
if (s.length() == 0 || t.length() == 0) return "";
Map<Character, Integer> dictT = new HashMap<>();
for (char c : t.toCharArray()) {
dictT.put(c, dictT.getOrDefault(c, 0) + 1);
}
int required = dictT.size();
int left = 0, right = 0;
int formed = 0;
Map<Character, Integer> windowCounts = new HashMap<>();
int[] ans = {-1, 0, 0}; // length, left, right
while (right < s.length()) {
char character = s.charAt(right);
windowCounts.put(character, windowCounts.getOrDefault(character, 0) + 1);
if (dictT.containsKey(character) &&
windowCounts.get(character).intValue() == dictT.get(character).intValue()) {
formed++;
}
while (left <= right && formed == required) {
character = s.charAt(left);
if (ans[0] == -1 || right - left + 1 < ans[0]) {
ans[0] = right - left + 1;
ans[1] = left;
ans[2] = right;
}
windowCounts.put(character, windowCounts.get(character) - 1);
if (dictT.containsKey(character) &&
windowCounts.get(character) < dictT.get(character)) {
formed--;
}
left++;
}
right++;
}
return ans[0] == -1 ? "" : s.substring(ans[1], ans[2] + 1);
}
Sliding Window Maximum
- Companies: Amazon, Google, Microsoft, Facebook
- Difficulty: Hard
- LeetCode: 239. Sliding Window Maximum
More Sliding Window Problems:
- Longest Repeating Character Replacement (Amazon, Google, Microsoft) - 424. Longest Repeating Character Replacement
- Find All Anagrams in a String (Amazon, Facebook, Google) - 438. Find All Anagrams in a String
- Permutation in String (Microsoft, Facebook, Amazon) - 567. Permutation in String
- Maximum Sum Subarray of Size K (Common in interviews)
- Fruit Into Baskets (Amazon, Google) - 904. Fruit Into Baskets
3. Fast & Slow Pointers Pattern
When to use: Detecting cycles in linked lists, finding middle elements, or problems involving circular arrays.
Time Complexity: O(n)
Space Complexity: O(1)
Key Problems & Companies:
Linked List Cycle
- Companies: Amazon, Google, Microsoft, Facebook, Apple
- Difficulty: Easy
- Interview Frequency: Very High
- LeetCode: 141. Linked List Cycle
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) return false;
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
Middle of the Linked List
- Companies: Amazon, Microsoft, Google, Facebook
- Difficulty: Easy
- LeetCode: 876. Middle of the Linked List
Linked List Cycle II
- Companies: Amazon, Google, Microsoft, Facebook
- Difficulty: Medium
- LeetCode: 142. Linked List Cycle II
More Fast & Slow Pointers Problems:
- Happy Number (Google, Amazon, Microsoft) - 202. Happy Number
- Find the Duplicate Number (Amazon, Google, Microsoft) - 287. Find the Duplicate Number
- Palindrome Linked List (Facebook, Amazon, Google) - 234. Palindrome Linked List
4. Merge Intervals Pattern
When to use: When dealing with overlapping intervals, scheduling problems, or interval merging.
Time Complexity: O(n log n)
Space Complexity: O(n)
Key Problems & Companies:
Merge Intervals
- Companies: Amazon, Google, Microsoft, Facebook, Apple, Bloomberg
- Difficulty: Medium
- Interview Frequency: Very High
- LeetCode: 56. Merge Intervals
public int[][] merge(int[][] intervals) {
if (intervals.length <= 1) return intervals;
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> result = new ArrayList<>();
int[] currentInterval = intervals[0];
result.add(currentInterval);
for (int[] interval : intervals) {
int currentEnd = currentInterval[1];
int nextBegin = interval[0];
int nextEnd = interval[1];
if (currentEnd >= nextBegin) {
currentInterval[1] = Math.max(currentEnd, nextEnd);
} else {
currentInterval = interval;
result.add(currentInterval);
}
}
return result.toArray(new int[result.size()][]);
}
Insert Interval
- Companies: Google, Amazon, Facebook, Microsoft
- Difficulty: Medium
- LeetCode: 57. Insert Interval
Meeting Rooms
- Companies: Google, Facebook, Amazon, Microsoft, Uber
- Difficulty: Easy
- LeetCode: 252. Meeting Rooms (Premium)
More Merge Intervals Problems:
- Meeting Rooms II (Google, Facebook, Amazon, Microsoft) - 253. Meeting Rooms II (Premium)
- Non-overlapping Intervals (Amazon, Google, Microsoft) - 435. Non-overlapping Intervals
- Minimum Number of Arrows to Burst Balloons (Amazon, Google) - 452. Minimum Number of Arrows to Burst Balloons
5. Cyclic Sort Pattern
When to use: When dealing with arrays containing numbers in a given range (usually 1 to n).
Time Complexity: O(n)
Space Complexity: O(1)
Key Problems & Companies:
Missing Number
- Companies: Amazon, Google, Microsoft, Facebook
- Difficulty: Easy
- LeetCode: 268. Missing Number
public int missingNumber(int[] nums) {
int i = 0;
int n = nums.length;
while (i < n) {
if (nums[i] < n && nums[i] != nums[nums[i]]) {
swap(nums, i, nums[i]);
} else {
i++;
}
}
for (i = 0; i < n; i++) {
if (nums[i] != i) {
return i;
}
}
return n;
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
Find All Numbers Disappeared in an Array
- Companies: Google, Amazon, Facebook
- Difficulty: Easy
- LeetCode: 448. Find All Numbers Disappeared in an Array
More Cyclic Sort Problems:
- Find the Duplicate Number (Amazon, Google, Microsoft) - 287. Find the Duplicate Number
- Find All Duplicates in an Array (Amazon, Google, Facebook) - 442. Find All Duplicates in an Array
- Set Mismatch (Amazon, Google) - 645. Set Mismatch
6. In-place Reversal of LinkedList
When to use: When you need to reverse a linked list or parts of it without using extra space.
Time Complexity: O(n)
Space Complexity: O(1)
Key Problems & Companies:
Reverse Linked List
- Companies: Amazon, Google, Microsoft, Facebook, Apple, Netflix
- Difficulty: Easy
- Interview Frequency: Very High
- LeetCode: 206. Reverse Linked List
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode current = head;
while (current != null) {
ListNode nextTemp = current.next;
current.next = prev;
prev = current;
current = nextTemp;
}
return prev;
}
Reverse Nodes in k-Group
- Companies: Amazon, Google, Microsoft, Facebook
- Difficulty: Hard
- LeetCode: 25. Reverse Nodes in k-Group
More LinkedList Reversal Problems:
- Reverse Linked List II (Amazon, Google, Microsoft) - 92. Reverse Linked List II
- Swap Nodes in Pairs (Amazon, Google, Microsoft) - 24. Swap Nodes in Pairs
7. Tree Breadth-First Search (BFS)
When to use: When you need to traverse tree level by level or find shortest path in trees.
Time Complexity: O(n)
Space Complexity: O(w) where w is maximum width
Key Problems & Companies:
Binary Tree Level Order Traversal
- Companies: Amazon, Google, Microsoft, Facebook, Apple
- Difficulty: Medium
- LeetCode: 102. Binary Tree Level Order Traversal
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
List<Integer> currentLevel = new ArrayList<>();
for (int i = 0; i < levelSize; i++) {
TreeNode currentNode = queue.poll();
currentLevel.add(currentNode.val);
if (currentNode.left != null) {
queue.offer(currentNode.left);
}
if (currentNode.right != null) {
queue.offer(currentNode.right);
}
}
result.add(currentLevel);
}
return result;
}
Binary Tree Zigzag Level Order Traversal
- Companies: Amazon, Google, Microsoft, Facebook
- Difficulty: Medium
- LeetCode: 103. Binary Tree Zigzag Level Order Traversal
More Tree BFS Problems:
- Binary Tree Right Side View (Amazon, Google, Facebook) - 199. Binary Tree Right Side View
- Average of Levels in Binary Tree (Amazon, Facebook) - 637. Average of Levels in Binary Tree
- Minimum Depth of Binary Tree (Amazon, Google, Microsoft) - 111. Minimum Depth of Binary Tree
8. Tree Depth-First Search (DFS)
When to use: When you need to explore tree paths, find sums, or perform recursive tree operations.
Time Complexity: O(n)
Space Complexity: O(h) where h is height
Key Problems & Companies:
Path Sum
- Companies: Amazon, Google, Microsoft, Facebook
- Difficulty: Easy
- LeetCode: 112. Path Sum
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
if (root.left == null && root.right == null) {
return targetSum == root.val;
}
return hasPathSum(root.left, targetSum - root.val) ||
hasPathSum(root.right, targetSum - root.val);
}
Binary Tree Paths
- Companies: Google, Amazon, Facebook
- Difficulty: Easy
- LeetCode: 257. Binary Tree Paths
More Tree DFS Problems:
- Path Sum II (Amazon, Google, Microsoft) - 113. Path Sum II
- Maximum Depth of Binary Tree (Amazon, Google, Microsoft) - 104. Maximum Depth of Binary Tree
- Diameter of Binary Tree (Amazon, Google, Facebook) - 543. Diameter of Binary Tree
9. Two Heaps Pattern
When to use: When you need to find medians, or divide elements into two parts.
Time Complexity: O(log n) for insertion, O(1) for median
Space Complexity: O(n)
Key Problems & Companies:
Find Median from Data Stream
- Companies: Google, Amazon, Facebook, Microsoft, Apple
- Difficulty: Hard
- LeetCode: 295. Find Median from Data Stream
class MedianFinder {
private PriorityQueue<Integer> maxHeap;
private PriorityQueue<Integer> minHeap;
public MedianFinder() {
maxHeap = new PriorityQueue<>(Collections.reverseOrder());
minHeap = new PriorityQueue<>();
}
public void addNum(int num) {
if (maxHeap.isEmpty() || num <= maxHeap.peek()) {
maxHeap.offer(num);
} else {
minHeap.offer(num);
}
if (maxHeap.size() > minHeap.size() + 1) {
minHeap.offer(maxHeap.poll());
} else if (minHeap.size() > maxHeap.size() + 1) {
maxHeap.offer(minHeap.poll());
}
}
public double findMedian() {
if (maxHeap.size() == minHeap.size()) {
return (maxHeap.peek() + minHeap.peek()) / 2.0;
} else {
return maxHeap.size() > minHeap.size() ? maxHeap.peek() : minHeap.peek();
}
}
}
More Two Heaps Problems:
- Sliding Window Median (Google, Amazon) - 480. Sliding Window Median
- IPO (Google, Amazon) - 502. IPO
10. Subsets Pattern
When to use: When you need to generate all combinations, permutations, or subsets.
Time Complexity: O(2^n) for subsets, O(n!) for permutations
Space Complexity: O(n)
Key Problems & Companies:
Subsets
- Companies: Amazon, Google, Microsoft, Facebook
- Difficulty: Medium
- LeetCode: 78. Subsets
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backtrack(result, new ArrayList<>(), nums, 0);
return result;
}
private void backtrack(List<List<Integer>> result, List<Integer> tempList,
int[] nums, int start) {
result.add(new ArrayList<>(tempList));
for (int i = start; i < nums.length; i++) {
tempList.add(nums[i]);
backtrack(result, tempList, nums, i + 1);
tempList.remove(tempList.size() - 1);
}
}
Permutations
- Companies: Amazon, Google, Microsoft, Facebook, Apple
- Difficulty: Medium
- LeetCode: 46. Permutations
More Subsets Problems:
- Subsets II (Amazon, Google, Facebook) - 90. Subsets II
- Permutations II (Amazon, Google, Microsoft) - 47. Permutations II
- Combinations (Google, Amazon) - 77. Combinations
11. Modified Binary Search
When to use: When dealing with sorted arrays with modifications or rotations.
Time Complexity: O(log n)
Space Complexity: O(1)
Key Problems & Companies:
Search in Rotated Sorted Array
- Companies: Amazon, Google, Microsoft, Facebook, Apple
- Difficulty: Medium
- Interview Frequency: Very High
- LeetCode: 33. Search in Rotated Sorted Array
public int search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) return mid;
if (nums[left] <= nums[mid]) {
if (target >= nums[left] && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else {
if (target > nums[mid] && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
Find Minimum in Rotated Sorted Array
- Companies: Amazon, Google, Microsoft, Facebook
- Difficulty: Medium
- LeetCode: 153. Find Minimum in Rotated Sorted Array
More Modified Binary Search Problems:
- Search a 2D Matrix (Amazon, Google, Microsoft) - 74. Search a 2D Matrix
- Find Peak Element (Google, Amazon, Microsoft) - 162. Find Peak Element
- First Bad Version (Facebook, Amazon, Google) - 278. First Bad Version
12. Bitwise XOR Pattern
When to use: When dealing with problems involving finding unique elements or bit manipulations.
Time Complexity: O(n)
Space Complexity: O(1)
Key Problems & Companies:
Single Number
- Companies: Amazon, Google, Microsoft, Facebook
- Difficulty: Easy
- LeetCode: 136. Single Number
public int singleNumber(int[] nums) {
int result = 0;
for (int num : nums) {
result ^= num;
}
return result;
}
More Bitwise XOR Problems:
- Single Number II (Amazon, Google) - 137. Single Number II
- Single Number III (Amazon, Google) - 260. Single Number III
- Missing Number (Amazon, Google, Microsoft) - 268. Missing Number
13. Top K Elements
When to use: When you need to find the K largest/smallest elements or K most frequent elements.
Time Complexity: O(n log k)
Space Complexity: O(k)
Key Problems & Companies:
Kth Largest Element in an Array
- Companies: Amazon, Google, Microsoft, Facebook, Apple
- Difficulty: Medium
- LeetCode: 215. Kth Largest Element in an Array
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>();
for (int num : nums) {
heap.offer(num);
if (heap.size() > k) {
heap.poll();
}
}
return heap.peek();
}
Top K Frequent Elements
- Companies: Amazon, Google, Facebook, Microsoft, Apple
- Difficulty: Medium
- LeetCode: 347. Top K Frequent Elements
More Top K Problems:
- K Closest Points to Origin (Amazon, Google, Facebook) - 973. K Closest Points to Origin
- Kth Smallest Element in a Sorted Matrix (Google, Amazon) - 378. Kth Smallest Element in a Sorted Matrix
14. K-way Merge
When to use: When you need to merge K sorted arrays or lists.
Time Complexity: O(n log k)
Space Complexity: O(k)
Key Problems & Companies:
Merge k Sorted Lists
- Companies: Amazon, Google, Microsoft, Facebook, Apple
- Difficulty: Hard
- LeetCode: 23. Merge k Sorted Lists
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
PriorityQueue<ListNode> heap = new PriorityQueue<>((a, b) -> a.val - b.val);
for (ListNode list : lists) {
if (list != null) {
heap.offer(list);
}
}
ListNode dummy = new ListNode(0);
ListNode current = dummy;
while (!heap.isEmpty()) {
ListNode node = heap.poll();
current.next = node;
current = current.next;
if (node.next != null) {
heap.offer(node.next);
}
}
return dummy.next;
}
More K-way Merge Problems:
- Find K Pairs with Smallest Sums (Google, Amazon) - 373. Find K Pairs with Smallest Sums
- Smallest Range Covering Elements from K Lists (Google, Amazon) - 632. Smallest Range Covering Elements from K Lists
15. Dynamic Programming Patterns
When to use: When problems have optimal substructure and overlapping subproblems.
Time Complexity: Varies (usually O(n²) to O(n³))
Space Complexity: O(n) to O(n²)
Key DP Patterns:
1. Linear DP
Climbing Stairs
- Companies: Amazon, Google, Microsoft, Facebook, Apple
- Difficulty: Easy
- LeetCode: 70. Climbing Stairs
public int climbStairs(int n) {
if (n <= 2) return n;
int prev2 = 1, prev1 = 2;
for (int i = 3; i <= n; i++) {
int current = prev1 + prev2;
prev2 = prev1;
prev1 = current;
}
return prev1;
}
House Robber
- Companies: Amazon, Google, Microsoft, Facebook
- Difficulty: Medium
- LeetCode: 198. House Robber
public int rob(int[] nums) {
if (nums.length == 0) return 0;
if (nums.length == 1) return nums[0];
int prev2 = nums[0];
int prev1 = Math.max(nums[0], nums[1]);
for (int i = 2; i < nums.length; i++) {
int current = Math.max(prev1, prev2 + nums[i]);
prev2 = prev1;
prev1 = current;
}
return prev1;
}
2. 2D DP
Unique Paths
- Companies: Amazon, Google, Microsoft, Facebook
- Difficulty: Medium
- LeetCode: 62. Unique Paths
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
for (int i = 0; i < m; i++) {
dp[i][0] = 1;
}
for (int j = 0; j < n; j++) {
dp[0][j] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m-1][n-1];
}
Longest Common Subsequence
- Companies: Google, Amazon, Microsoft, Facebook
- Difficulty: Medium
- LeetCode: 1143. Longest Common Subsequence
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length(), n = text2.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
3. Knapsack Pattern
0/1 Knapsack
- Companies: Amazon, Google, Microsoft
- Difficulty: Medium
public int knapsack(int[] weights, int[] values, int capacity) {
int n = weights.length;
int[][] dp = new int[n + 1][capacity + 1];
for (int i = 1; i <= n; i++) {
for (int w = 1; w <= capacity; w++) {
if (weights[i - 1] <= w) {
dp[i][w] = Math.max(dp[i - 1][w],
dp[i - 1][w - weights[i - 1]] + values[i - 1]);
} else {
dp[i][w] = dp[i - 1][w];
}
}
}
return dp[n][capacity];
}
Coin Change
- Companies: Amazon, Google, Microsoft, Facebook
- Difficulty: Medium
- LeetCode: 322. Coin Change
More DP Problems:
- Maximum Subarray (Amazon, Google, Microsoft) - 53. Maximum Subarray
- Word Break (Google, Amazon, Facebook) - 139. Word Break
- Palindromic Substrings (Amazon, Facebook, Google) - 647. Palindromic Substrings
- Edit Distance (Google, Amazon, Microsoft) - 72. Edit Distance
16. Topological Sort
When to use: When dealing with directed acyclic graphs (DAG) and dependency resolution.
Time Complexity: O(V + E)
Space Complexity: O(V)
Key Problems & Companies:
Course Schedule
- Companies: Amazon, Google, Microsoft, Facebook
- Difficulty: Medium
- LeetCode: 207. Course Schedule
public boolean canFinish(int numCourses, int[][] prerequisites) {
int[] indegree = new int[numCourses];
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < numCourses; i++) {
adj.add(new ArrayList<>());
}
for (int[] prerequisite : prerequisites) {
adj.get(prerequisite[1]).add(prerequisite[0]);
indegree[prerequisite[0]]++;
}
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) {
queue.offer(i);
}
}
int count = 0;
while (!queue.isEmpty()) {
int course = queue.poll();
count++;
for (int neighbor : adj.get(course)) {
indegree[neighbor]--;
if (indegree[neighbor] == 0) {
queue.offer(neighbor);
}
}
}
return count == numCourses;
}
Course Schedule II
- Companies: Amazon, Google, Microsoft, Facebook
- Difficulty: Medium
- LeetCode: 210. Course Schedule II
More Topological Sort Problems:
- Alien Dictionary (Google, Facebook, Amazon) - 269. Alien Dictionary (Premium)
- Minimum Height Trees (Google, Amazon) - 310. Minimum Height Trees
17. Graph Algorithms
When to use: When dealing with graph traversal, shortest paths, or connectivity problems.
Key Graph Patterns:
1. DFS/BFS Traversal
Number of Islands
- Companies: Amazon, Google, Microsoft, Facebook, Apple
- Difficulty: Medium
- LeetCode: 200. Number of Islands
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) return 0;
int count = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
dfs(grid, i, j);
count++;
}
}
}
return count;
}
private void dfs(char[][] grid, int i, int j) {
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length ||
grid[i][j] == '0') {
return;
}
grid[i][j] = '0';
dfs(grid, i + 1, j);
dfs(grid, i - 1, j);
dfs(grid, i, j + 1);
dfs(grid, i, j - 1);
}
Clone Graph
- Companies: Google, Amazon, Facebook, Microsoft
- Difficulty: Medium
- LeetCode: 133. Clone Graph
2. Shortest Path
Word Ladder
- Companies: Amazon, Google, Microsoft, Facebook
- Difficulty: Hard
- LeetCode: 127. Word Ladder
More Graph Problems:
- Pacific Atlantic Water Flow (Google, Amazon, Facebook) - 417. Pacific Atlantic Water Flow
- Surrounded Regions (Amazon, Google, Microsoft) - 130. Surrounded Regions
- Graph Valid Tree (Google, Facebook, Amazon) - 261. Graph Valid Tree (Premium)
18. Trie Pattern
When to use: When dealing with prefix matching, word search, or autocomplete features.
Time Complexity: O(m) where m is word length
Space Complexity: O(ALPHABET_SIZE * N * M)
Key Problems & Companies:
Implement Trie (Prefix Tree)
- Companies: Google, Amazon, Microsoft, Facebook
- Difficulty: Medium
- LeetCode: 208. Implement Trie (Prefix Tree)
class Trie {
class TrieNode {
TrieNode[] children;
boolean isEndOfWord;
public TrieNode() {
children = new TrieNode[26];
isEndOfWord = false;
}
}
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode current = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (current.children[index] == null) {
current.children[index] = new TrieNode();
}
current = current.children[index];
}
current.isEndOfWord = true;
}
public boolean search(String word) {
TrieNode current = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (current.children[index] == null) {
return false;
}
current = current.children[index];
}
return current.isEndOfWord;
}
public boolean startsWith(String prefix) {
TrieNode current = root;
for (char c : prefix.toCharArray()) {
int index = c - 'a';
if (current.children[index] == null) {
return false;
}
current = current.children[index];
}
return true;
}
}
Word Search II
- Companies: Google, Amazon, Microsoft, Facebook
- Difficulty: Hard
- LeetCode: 212. Word Search II
More Trie Problems:
- Design Add and Search Words Data Structure (Facebook, Amazon, Google) - 211. Design Add and Search Words Data Structure
- Replace Words (Amazon, Google) - 648. Replace Words
19. Union Find (Disjoint Set)
When to use: When dealing with connectivity, grouping, or cycle detection in undirected graphs.
Time Complexity: O(α(n)) amortized
Space Complexity: O(n)
Key Problems & Companies:
Number of Connected Components in an Undirected Graph
- Companies: Google, Facebook, Amazon, Microsoft
- Difficulty: Medium
- LeetCode: 323. Number of Connected Components in an Undirected Graph (Premium)
class UnionFind {
private int[] parent;
private int[] rank;
private int components;
public UnionFind(int n) {
parent = new int[n];
rank = new int[n];
components = n;
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 1;
}
}
public int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]); // Path compression
}
return parent[x];
}
public boolean union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY) return false;
// Union by rank
if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
components--;
return true;
}
public int getComponents() {
return components;
}
}
public int countComponents(int n, int[][] edges) {
UnionFind uf = new UnionFind(n);
for (int[] edge : edges) {
uf.union(edge[0], edge[1]);
}
return uf.getComponents();
}
More Union Find Problems:
- Redundant Connection (Google, Amazon) - 684. Redundant Connection
- Accounts Merge (Google, Facebook, Amazon) - 721. Accounts Merge
- Most Stones Removed with Same Row or Column (Google, Amazon) - 947. Most Stones Removed with Same Row or Column
20. Backtracking Pattern
When to use: When you need to explore all possible solutions and backtrack when constraints are violated.
Time Complexity: Exponential (varies by problem)
Space Complexity: O(depth of recursion)
Key Problems & Companies:
Generate Parentheses
- Companies: Google, Amazon, Microsoft, Facebook, Apple
- Difficulty: Medium
- LeetCode: 22. Generate Parentheses
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
backtrack(result, "", 0, 0, n);
return result;
}
private void backtrack(List<String> result, String current,
int open, int close, int max) {
if (current.length() == max * 2) {
result.add(current);
return;
}
if (open < max) {
backtrack(result, current + "(", open + 1, close, max);
}
if (close < open) {
backtrack(result, current + ")", open, close + 1, max);
}
}
Word Search
- Companies: Amazon, Google, Microsoft, Facebook
- Difficulty: Medium
- LeetCode: 79. Word Search
public boolean exist(char[][] board, String word) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (dfs(board, word, i, j, 0)) {
return true;
}
}
}
return false;
}
private boolean dfs(char[][] board, String word, int i, int j, int index) {
if (index == word.length()) return true;
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length ||
board[i][j] != word.charAt(index)) {
return false;
}
char temp = board[i][j];
board[i][j] = '#'; // Mark as visited
boolean found = dfs(board, word, i + 1, j, index + 1) ||
dfs(board, word, i - 1, j, index + 1) ||
dfs(board, word, i, j + 1, index + 1) ||
dfs(board, word, i, j - 1, index + 1);
board[i][j] = temp; // Backtrack
return found;
}
N-Queens
- Companies: Google, Amazon, Microsoft, Facebook
- Difficulty: Hard
- LeetCode: 51. N-Queens
More Backtracking Problems:
- Letter Combinations of a Phone Number (Amazon, Google, Facebook) - 17. Letter Combinations of a Phone Number
- Palindrome Partitioning (Google, Amazon, Facebook) - 131. Palindrome Partitioning
- Sudoku Solver (Google, Amazon, Microsoft) - 37. Sudoku Solver
- Combination Sum (Amazon, Google, Facebook) - 39. Combination Sum
Interview Preparation Strategy
1. Study Pattern by Pattern
- Master one pattern completely before moving to the next
- Practice 5-10 problems per pattern
- Focus on understanding the underlying technique
2. Company-Specific Preparation
- Google: Focus on hard algorithmic problems, system design
- Amazon: Leadership principles + coding (medium difficulty)
- Microsoft: Balanced approach, good for beginners
- Facebook/Meta: Product sense + challenging coding problems
- Apple: Focus on fundamentals and clean code
3. Time Management
- Easy problems: 10-15 minutes
- Medium problems: 20-30 minutes
- Hard problems: 35-45 minutes
4. Common Mistakes to Avoid
- Not clarifying requirements
- Jumping into coding without planning
- Not testing with edge cases
- Poor time management
- Not communicating thought process
5. Mock Interview Practice
- Use platforms like Pramp, InterviewBit, or LeetCode Mock
- Practice explaining your solution clearly
- Get comfortable with live coding
Conclusion
Mastering these 20 patterns will give you a strong foundation for tackling most coding interview problems. Remember:
- Pattern Recognition is key - identify which pattern applies
- Practice Consistently - solve problems daily
- Understand Trade-offs - know time/space complexities
- Mock Interviews - practice under pressure
- System Design - don't neglect this for senior roles
The key to success is consistent practice and understanding the underlying patterns rather than memorizing solutions. Focus on building problem-solving intuition that will help you tackle new problems during interviews.
Good luck with your interview preparation! 🚀
Top comments (0)