0% found this document useful (0 votes)
1K views10 pages

127 DSA Patterns for Interview Prep

Uploaded by

princessofd90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views10 pages

127 DSA Patterns for Interview Prep

Uploaded by

princessofd90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

127 Core DSA Patterns - Complete Interview Preparation Guide

Table of Contents
1. Arrays & Hashing
2. Two Pointers

3. Sliding Window
4. Stack

5. Binary Search
6. Linked List

7. Trees

8. Tries

9. Heap/Priority Queue

10. Backtracking
11. Graphs
12. Advanced Graphs

13. Dynamic Programming


14. Greedy

15. Intervals

16. Math & Geometry

17. Bit Manipulation

Arrays & Hashing (12 Questions)

Easy (4)
1. Two Sum - Find two numbers that add up to target
2. Valid Anagram - Check if two strings are anagrams

3. Contains Duplicate - Check if array contains any duplicates


4. Replace Elements with Greatest Element on Right Side - Replace each element with greatest
element on its right

Medium (6)
5. Group Anagrams - Group strings that are anagrams of each other
6. Top K Frequent Elements - Find k most frequent elements

7. Product of Array Except Self - Return array where each element is product of all others
8. Valid Sudoku - Check if 9x9 Sudoku board is valid
9. Encode and Decode Strings - Design algorithm to encode/decode list of strings

10. Longest Consecutive Sequence - Find length of longest consecutive elements sequence

Hard (2)
11. Subarray Sum Equals K - Count number of continuous subarrays whose sum equals k

12. Largest Rectangle in Histogram - Find area of largest rectangle in histogram

Two Pointers (8 Questions)

Easy (3)
13. Valid Palindrome - Check if string is palindrome (alphanumeric only)
14. Two Sum II - Input Array Is Sorted - Two sum on sorted array

15. Move Zeroes - Move all zeros to end while maintaining relative order

Medium (4)
16. 3Sum - Find all unique triplets that sum to zero

17. Container With Most Water - Find two lines that contain most water

18. Remove Duplicates from Sorted Array II - Allow at most 2 duplicates


19. Sort Colors - Sort array with 3 colors in-place

Hard (1)
20. Trapping Rain Water - Calculate trapped rainwater after raining

Sliding Window (7 Questions)

Easy (2)
21. Best Time to Buy and Sell Stock - Find maximum profit from single buy/sell

22. Maximum Average Subarray I - Find contiguous subarray with maximum average

Medium (4)
23. Longest Substring Without Repeating Characters - Find length of longest substring without
repeating chars

24. Longest Repeating Character Replacement - Longest substring with same chars after k
replacements

25. Permutation in String - Check if s2 contains permutation of s1


26. Minimum Window Substring - Find minimum window containing all chars of pattern
Hard (1)
27. Sliding Window Maximum - Find maximum in all subarrays of size k

Stack (8 Questions)

Easy (3)
28. Valid Parentheses - Check if brackets are properly closed

29. Min Stack - Design stack with min() operation in O(1)

30. Implement Queue using Stacks - Design queue using two stacks

Medium (4)
31. Evaluate Reverse Polish Notation - Evaluate RPN expression

32. Generate Parentheses - Generate all valid parentheses combinations


33. Daily Temperatures - Find next warmer temperature for each day

34. Car Fleet - Calculate number of car fleets reaching destination

Hard (1)
35. Basic Calculator - Implement basic calculator with +, -, (, )

Binary Search (8 Questions)

Easy (3)
36. Binary Search - Classic binary search implementation

37. Search Insert Position - Find position to insert target in sorted array

38. First Bad Version - Find first bad version using version API

Medium (4)
39. Find Minimum in Rotated Sorted Array - Find minimum in rotated sorted array

40. Search in Rotated Sorted Array - Search target in rotated sorted array

41. Time Based Key-Value Store - Design time-based key-value store

42. Koko Eating Bananas - Find minimum eating speed to finish all bananas

Hard (1)
43. Median of Two Sorted Arrays - Find median of two sorted arrays in O(log(min(m,n)))

Linked List (9 Questions)


Easy (4)

44. Reverse Linked List - Reverse a singly linked list


45. Merge Two Sorted Lists - Merge two sorted linked lists

46. Linked List Cycle - Detect if linked list has cycle


47. Remove Duplicates from Sorted List - Remove duplicates from sorted list

Medium (4)
48. Add Two Numbers - Add two numbers represented as linked lists

49. Remove Nth Node From End of List - Remove nth node from end
50. Reorder List - Reorder list to L0→Ln→L1→Ln-1→L2→Ln-2→...

51. Copy List with Random Pointer - Deep copy linked list with random pointers

Hard (1)
52. Merge k Sorted Lists - Merge k sorted linked lists

Trees (12 Questions)

Easy (4)
53. Invert Binary Tree - Invert/flip binary tree

54. Maximum Depth of Binary Tree - Find maximum depth


55. Same Tree - Check if two trees are identical

56. Subtree of Another Tree - Check if tree is subtree of another

Medium (6)
57. Lowest Common Ancestor of BST - Find LCA in binary search tree

58. Binary Tree Level Order Traversal - Level order traversal of binary tree

59. Binary Tree Right Side View - Return values of nodes seen from right side

60. Count Good Nodes in Binary Tree - Count nodes where path from root has no greater values

61. Validate Binary Search Tree - Check if tree is valid BST


62. Kth Smallest Element in a BST - Find kth smallest element in BST

Hard (2)
63. Binary Tree Maximum Path Sum - Find maximum path sum between any two nodes

64. Serialize and Deserialize Binary Tree - Design algorithm to serialize/deserialize binary tree
Tries (3 Questions)

Medium (3)
65. Implement Trie (Prefix Tree) - Implement trie data structure
66. Design Add and Search Words Data Structure - Support adding words and searching with
wildcards

67. Word Search II - Find all words from dictionary that can be formed on board

Heap/Priority Queue (6 Questions)

Easy (1)
68. Kth Largest Element in a Stream - Design class to find kth largest element in stream

Medium (4)
69. Last Stone Weight - Simulate stone smashing process

70. K Closest Points to Origin - Find k closest points to origin

71. Kth Largest Element in an Array - Find kth largest element

72. Task Scheduler - Find minimum time to execute all tasks with cooling period

Hard (1)
73. Find Median from Data Stream - Design data structure to find median in stream

Backtracking (7 Questions)

Medium (6)
74. Subsets - Generate all possible subsets

75. Combination Sum - Find combinations that sum to target

76. Permutations - Generate all permutations of array

77. Subsets II - Generate subsets with duplicate handling

78. Combination Sum II - Combination sum with duplicate handling


79. Word Search - Find if word exists in 2D board

Hard (1)
80. N-Queens - Place n queens on n×n chessboard

Graphs (10 Questions)


Easy (2)
81. Number of Islands - Count number of islands in 2D grid

82. Clone Graph - Deep clone undirected graph

Medium (6)
83. Max Area of Island - Find maximum area of island

84. Pacific Atlantic Water Flow - Find cells where water can flow to both oceans

85. Surrounded Regions - Capture surrounded regions on board

86. Rotting Oranges - Find minimum time for all oranges to rot
87. Course Schedule - Check if you can finish all courses (cycle detection)

88. Course Schedule II - Return ordering of courses to finish all

Hard (2)
89. Word Ladder - Find shortest transformation sequence from start to end word

90. Minimum Cost to Connect All Points - Find minimum cost to connect all points (MST)

Advanced Graphs (3 Questions)

Hard (3)
91. Reconstruct Itinerary - Reconstruct itinerary from airline tickets
92. Min Cost to Connect All Points - Advanced MST implementation

93. Network Delay Time - Find minimum time for signal to reach all nodes (Dijkstra)

Dynamic Programming (16 Questions)

Easy (3)
94. Climbing Stairs - Find number of ways to climb n stairs

95. Min Cost Climbing Stairs - Find minimum cost to reach top
96. House Robber - Maximum money you can rob without robbing adjacent houses

Medium (10)
97. House Robber II - Houses arranged in circle

98. Longest Palindromic Substring - Find longest palindromic substring


99. Palindromic Substrings - Count palindromic substrings

100. Decode Ways - Number of ways to decode string


101. Coin Change - Minimum coins to make amount
102. Maximum Product Subarray - Find contiguous subarray with maximum product

103. Word Break - Check if string can be segmented into dictionary words
104. Longest Increasing Subsequence - Find length of longest increasing subsequence

105. Partition Equal Subset Sum - Check if array can be partitioned into two equal sum subsets
106. Unique Paths - Number of unique paths from top-left to bottom-right

Hard (3)
107. Edit Distance - Minimum operations to convert word1 to word2

108. Regular Expression Matching - Implement regex matching with '.' and '*'
109. Longest Valid Parentheses - Find length of longest valid parentheses substring

Greedy (5 Questions)

Easy (1)
110. Maximum Subarray - Find contiguous subarray with maximum sum

Medium (3)
111. Jump Game - Check if you can reach last index
112. Jump Game II - Minimum jumps to reach last index

113. Gas Station - Find starting gas station to complete circuit

Hard (1)
114. Candy - Minimum candies to distribute to children

Intervals (5 Questions)

Easy (1)
115. Meeting Rooms - Check if person can attend all meetings

Medium (4)
116. Merge Intervals - Merge overlapping intervals

117. Insert Interval - Insert interval into sorted non-overlapping intervals


118. Non-overlapping Intervals - Minimum intervals to remove to make non-overlapping

119. Meeting Rooms II - Minimum meeting rooms required


Math & Geometry (5 Questions)

Easy (2)
120. Happy Number - Determine if number is happy
121. Plus One - Add one to number represented as array

Medium (2)
122. Rotate Image - Rotate n×n matrix 90 degrees clockwise

123. Spiral Matrix - Return elements of matrix in spiral order

Hard (1)
124. Valid Number - Check if string is valid number

Bit Manipulation (3 Questions)

Easy (2)
125. Single Number - Find single number in array where every other appears twice

126. Number of 1 Bits - Count number of 1 bits in integer

Medium (1)
127. Counting Bits - Count number of 1 bits for numbers 0 to n

Study Strategy

Phase 1: Foundation (Weeks 1-2)


Master Arrays & Hashing, Two Pointers, and Sliding Window

Focus on easy and medium problems


Build strong problem-solving intuition

Phase 2: Core Data Structures (Weeks 3-4)


Stack, Binary Search, Linked List, and Trees

Practice implementation and traversal techniques


Understand time and space complexities

Phase 3: Advanced Patterns (Weeks 5-6)


Tries, Heap, Backtracking, and Graphs

Focus on algorithmic thinking and optimization


Practice explaining solutions clearly

Phase 4: Dynamic Programming & Advanced Topics (Weeks 7-8)


Dynamic Programming, Greedy, Intervals

Math & Geometry, Bit Manipulation

Advanced graph algorithms

Phase 5: Integration & Practice (Weeks 9-10)


Mixed problem sets
Timed practice sessions

Mock interviews and code reviews

Tips for Success


1. Understand Patterns: Don't just memorize solutions, understand the underlying patterns
2. Practice Regularly: Solve 2-3 problems daily consistently

3. Time Management: Practice with time constraints (20-30 minutes per problem)
4. Explain Solutions: Practice explaining your approach and code

5. Edge Cases: Always consider edge cases and test your solutions

6. Optimize: Start with brute force, then optimize step by step

7. Review Mistakes: Learn from incorrect approaches and implementations

Company-Specific Focus

FAANG (Facebook, Apple, Amazon, Netflix, Google)


Emphasis on Trees, Graphs, Dynamic Programming

System design for senior roles

Behavioral questions preparation

Microsoft, Adobe, Salesforce


Strong focus on Arrays, Strings, and Data Structures

Problem-solving approach more important than optimal solution

Startups and Mid-tier Companies


Practical coding problems
Focus on clean, readable code

Basic algorithms and data structures


This guide covers all essential patterns needed for technical interviews. Practice consistently and focus on
understanding rather than memorization for best results.

Common questions

Powered by AI

Dynamic Programming (DP) and Greedy algorithms both aim to solve optimization problems but differ fundamentally in approach. DP solves problems by breaking them down into overlapping subproblems, using previous solutions (memoization) to construct a solution for larger problems, ensuring an optimal solution by considering all possible decisions. It requires storing results of smaller subproblems. On the other hand, Greedy algorithms work by making a series of local optimal decisions with the hope of finding a global optimum. Greedy choices are made based on immediate benefit without considering the consequences, which may not always lead to an optimal solution .

A Min Stack is particularly advantageous in scenarios where frequent retrieval of the minimum element in a stack is required alongside standard stack operations such as push and pop, in O(1) time. This is ideal for problems involving dynamic datasets where comparisons and minimum values are a frequent operation. An example application is in financial computations where minimum historical data is needed instantly or in game development where constraints are evaluated continuously for gameplay mechanics requiring minimal values from a dynamic action list .

Dynamic Programming (DP) solves the 'Edit Distance' problem, which determines the minimum number of operations needed to convert one string to another, by utilizing a table to store the results of subproblems. The table is filled systematically where dp[i][j] represents the edit distance between the first i characters of one string and first j characters of the other. Fill the table by evaluating the minimum operations (insert, delete, or replace) required at each stage, building upon previously computed minimum operations for smaller substrings. This bottom-up DP approach efficiently covers all possibilities and ensures optimal solutions with a time complexity of O(m*n), where m and n are the lengths of the two strings, which is vital for applications requiring precise string transformations, such as spell-checking and computational biology .

In a binary search tree (BST), the 'Lowest Common Ancestor' (LCA) of two nodes is the deepest node that is an ancestor to both nodes. The LCA is pivotal in understanding hierarchical relationships among nodes. To find the LCA efficiently, leverage the properties of BSTs where for node values p and q, if both p and q are less than root's value, traverse to the left child. If both are greater, move to the right child. The first node encountered where p ≤ value ≤ q or q ≤ value ≤ p is the LCA. This approach has a time complexity of O(h), where h is the height of the tree, leveraging BST properties .

Applying 'Binary Search' in a 'Time Based Key-Value Store' significantly enhances retrieval efficiency by allowing logarithmic time complexity operations for finding values associated with specific timestamps. In this setup, store timestamps along with values in a sorted order for each key. When querying, use binary search to find the greatest timestamp less than or equal to the given timestamp for effective temporal lookup. This requires O(log n) time for the binary search operation, compared to a linear scan, making it scalable for realtime applications, like retrieving versioned configurations or historical data efficiently .

Backtracking is suitable for the N-Queens problem due to its ability to explore possible arrangements incrementally and efficiently backtrack in case of conflicts. The N-Queens problem's solution space is a large combinatorial space of potential queen placements. Backtracking helps by placing a queen in a row, checking for conflicts along columns, rows, and diagonals, and proceeding if safe. If a conflict occurs, the algorithm backtracks to try a different position. This approach reveals that solution spaces can often be efficiently navigated using recursive depth-first search techniques to prune large sections of invalid solutions, emphasizing solutions' layered and hierarchical structure .

Evaluating an expression in Reverse Polish Notation (RPN) uses a stack data structure to facilitate the process. Operands are pushed onto the stack as they are read. When an operator is encountered, the required number of operands (usually two for binary operators) are popped from the stack, the operation is performed, and the result is pushed back onto the stack. This continues until the end of the expression, and the result of the entire expression evaluation is the single remaining value on the stack. This method is efficient as it directly processes the operands in the order required without the need for parentheses .

The 'Two Pointers' technique can be effectively used to determine if a string is a valid palindrome by setting one pointer at the start of the string and another at the end. The idea is to move both pointers towards the center. At each step, compare the characters at these pointers, ignoring non-alphanumeric characters, and convert characters to the same case (lower or upper). If the characters differ, the string is not a palindrome. If both pointers cross each other without a mismatch, the string is a valid palindrome .

The sliding window technique involves maintaining a window (or region) within a data structure that can shrink or expand depending on the conditions of the problem. For finding the longest substring without repeating characters, maintain a window using two pointers on a string. Start both pointers at the beginning. Move the 'right' pointer to extend the window until a duplicate character is found. Once a duplicate is present, move the 'left' pointer right one position at a time until the duplicate is removed. Track the maximum length of substrings found without duplicates during this process. This approach efficiently keeps track of current unique characters using a set or hash map .

The 'Heap' data structure efficiently facilitates finding the 'Kth Largest Element in a Stream' through its ability to quickly maintain the largest elements seen so far. By using a min-heap of size k, new elements are inserted into the heap, ensuring that it contains only the k largest elements encountered. For each new element in the stream, if it is greater than the minimum element in the heap, the minimum is removed and the new element inserted. Thus, the root of the heap always represents the kth largest element in O(log k) time for insertions, offering a scalable solution to this problem .

You might also like