0% found this document useful (0 votes)
13 views3 pages

Coding Interview Cheatsheet: DSA Edition

The document outlines various strategies and algorithms for solving common programming problems, categorized into sections such as Search/Lookup, Sorting/Ordering, Graphs/Traversal, Dynamic Programming, Sliding Window, Trees, Backtracking, Greedy Algorithms, Strings, and Math/Bit Manipulation. Each category includes specific techniques, their average-case complexities, and brief explanations of their applications. The document serves as a quick reference for selecting appropriate algorithms based on problem types.

Uploaded by

Vivek
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)
13 views3 pages

Coding Interview Cheatsheet: DSA Edition

The document outlines various strategies and algorithms for solving common programming problems, categorized into sections such as Search/Lookup, Sorting/Ordering, Graphs/Traversal, Dynamic Programming, Sliding Window, Trees, Backtracking, Greedy Algorithms, Strings, and Math/Bit Manipulation. Each category includes specific techniques, their average-case complexities, and brief explanations of their applications. The document serves as a quick reference for selecting appropriate algorithms based on problem types.

Uploaded by

Vivek
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

Search / Lookup

- Fast lookup / membership test


Strategy: HashSet / HashMap
Note: O(1) average-case lookup
Explanation: Hash tables allow constant-time key access; use [Link](x) or map[x].
- Frequency count
Strategy: HashMap
Note: Count items or characters
Explanation: Map each item to its count: map[char]++ in loops.
- Finding duplicates
Strategy: HashSet
Note: Add each item, check if exists
Explanation: If already in set, it's a duplicate.
- Prefix/suffix search
Strategy: Trie
Note: For string problems with many prefixes
Explanation: Tree structure where each node is a char; enables fast prefix queries like autocomplete.

Sorting / Ordering
- Kth largest/smallest
Strategy: Heap (PriorityQueue)
Note: Efficient top-K access
Explanation: Use min-heap for kth largest in stream; max-heap for kth smallest.
- Custom sort
Strategy: Comparator / Sort
Note: Sort by custom logic
Explanation: Define how to compare items, e.g. by frequency, length, etc.
- Real-time median
Strategy: Two Heaps
Note: MinHeap and MaxHeap
Explanation: Max-heap for left half, min-heap for right half; maintain balance.

Graphs / Traversal
- Shortest path (unweighted)
Strategy: BFS
Note: Explore level-by-level
Explanation: Use a queue to explore neighbors first (shortest in steps).
- Shortest path (weighted)
Strategy: Dijkstra / A*
Note: Use priority queue
Explanation: Greedy: explore cheapest path first with cost tracking.
- Traverse all options
Strategy: DFS / BFS
Note: Based on need
Explanation: DFS for deep path search, BFS for shortest path or layer-wise search.
- Detect cycles / components
Strategy: Union-Find (DSU)
Note: Dynamic connectivity
Explanation: Merge/find root of components; useful in Kruskals or cycle detection.
- Topological sort
Strategy: DFS or Kahns Algo
Note: For DAGs
Explanation: Order of tasks with dependencies. Kahn uses indegree; DFS uses post-order.

Dynamic Programming (DP)


- Optimal substructure
Strategy: DP (memo/table)
Note: Store overlapping results
Explanation: Reuse results of subproblems to avoid recomputation.
- Ways to reach target
Strategy: DP (1D/2D)
Note: Count possibilities
Explanation: Ex: Number of ways to climb stairs = dp[i] = dp[i-1] + dp[i-2].
- Max/min cost, length, etc.
Strategy: Bottom-up DP
Note: Fill table iteratively
Explanation: Tabulation instead of recursion. Often faster and avoids stack overflow.

Sliding Window / Two Pointers


- Subarray with property
Strategy: Sliding Window
Note: Expand/shrink window
Explanation: Keep track of a range of indices that meet a condition (like sum, chars).
- Pairs/triplets with sum
Strategy: Two Pointers
Note: Use sorted array
Explanation: Start from both ends, move inward based on sum comparison.
- Min/max in window
Strategy: Deque / Monotonic Queue
Note: Efficient in O(n)
Explanation: Keep deque of indices in increasing/decreasing order.

Trees / Binary Trees


- Tree traversal
Strategy: DFS (recursive or stack)
Note: Pre/In/Post-order
Explanation: Pre: NodeLeftRight, In: LeftNodeRight, Post: LeftRightNode. Implement with recursion or a stack.
- Path sums, subtree sizes
Strategy: DFS with return value
Note: Pass info up
Explanation: Recursively return sums, depths, etc. from children to parent.
- Balanced BST
Strategy: Binary Search Tree
Note: Divide/search logic
Explanation: Recursive or iterative binary search on a tree structure.

Backtracking / Recursion
- All permutations/combinations
Strategy: Backtracking
Note: Try backtrack
Explanation: Choose, explore, undo. Often involves recursion.
- Puzzle solver
Strategy: Backtracking with pruning
Note: Cut invalid branches
Explanation: Add constraints to eliminate impossible paths early.
- Subset/partition problems
Strategy: Recursion + memo
Note: Explore and cache
Explanation: Store (index, current sum) results to avoid recomputation.

Greedy Algorithms
- Max profit / min cost
Strategy: Greedy + Sort
Note: Pick best each time
Explanation: Make locally optimal choice; sort if needed for order.
- Interval scheduling
Strategy: Greedy + Sort
Note: Based on end/start
Explanation: Sort by end time to select most compatible intervals.
- Resource allocation
Strategy: Priority Queue
Note: Track available resources
Explanation: Ex: Meeting rooms, where ending earliest room is reused.

Strings / Parsing
- Palindromes
Strategy: Two Pointers / DP
Note: Expand from center
Explanation: Check equal characters moving inward; or use DP to cache results.
- Longest substring
Strategy: Sliding Window + HashMap
Note: Track seen chars
Explanation: Move left/right bounds of window to maintain uniqueness.
- Regex-style parsing
Strategy: Stack / Recursion
Note: Handle nested patterns
Explanation: Push/pop on brackets or recurse into patterns like (a|b)*.

Math / Bit Manipulation


- Prime numbers
Strategy: Sieve of Eratosthenes
Note: Precompute efficiently
Explanation: Mark non-primes in range; O(n log log n).
- GCD / Power / Modulo
Strategy: Euclidean algo, fast pow
Note: Efficient math ops
Explanation: GCD: gcd(a, b) = gcd(b, a % b). Fast pow: square and reduce.
- Odd-count / single number
Strategy: Bitwise XOR
Note: A^A = 0
Explanation: Use a ^ a = 0, 0 ^ b = b to cancel out duplicates.

Common questions

Powered by AI

DFS can be used for detecting cycles in a graph by maintaining a recursive call stack along with a visited array. By marking all nodes visited and checking for back edges, DFS can indicate a cycle exists if it revisits a node currently in the recursion stack. Cycle detection is crucial for applications where understanding the presence of loops can prevent issues such as infinite loops or erroneous dependencies in systems like task scheduling or deadlock detection in operating systems .

Backtracking optimizes solving permutation problems by incrementally building candidate solutions and abandoning them ('backtracking') when they fail to meet the criteria, thus reducing the search space and avoiding futile computations. This allows only valid paths to be pursued, enhancing computational efficiency by pruning large sections of potential search trees early on, particularly in combinatorial generation or constraint satisfaction problems such as puzzle solving or route planning .

A Trie is preferable for string operations involving many prefix searches, such as autocomplete or dictionary implementations. This is because a Trie organizes data in a tree structure where each node represents a character, enabling efficient storage and retrieval of strings based on their prefixes. Tries allow for quick checks of whether a string with a particular prefix exists, which is more efficient than using other structures like arrays or binary trees when dealing with extensive string collections and prefix queries .

The Union-Find algorithm is effective for cycle detection because it efficiently manages and queries connectivity between components in a dynamic fashion through union and find operations. By identifying the root of components and merging nodes efficiently, it quickly determines and tests connectivity, revealing cycles when two nodes in the same component are joined. This is crucial for algorithms like Kruskal’s for constructing minimal spanning trees, as it prevents cycles, thus maintaining the tree property .

A binary search tree is optimal for scenarios where data needs to be dynamically maintained in order with efficient search, insertion, and deletion operations. By maintaining the BST properties, where each node's value is greater than all values in its left subtree and less than all in its right, these operations are performed with logarithmic complexity, O(log n), assuming the tree is balanced. This makes BST especially efficient for applications such as real-time indexing, database storage, and implementing associative arrays .

The Sieve of Eratosthenes is a process that iteratively marks the multiples of each prime number starting from 2, progressively marking non-prime numbers by setting them to false. It is important because it provides a highly efficient method (O(n log log n) complexity) for finding all prime numbers in a specified range, leveraging the fact that non-prime numbers can be represented as multiples of smaller primes. This efficiency is crucial for large-scale computations where knowing prime numbers is essential, such as cryptography and number theory .

Using a heap for the kth largest element problem involves maintaining a min-heap of k elements for efficient retrieval of the k-largest item from a data stream. This provides an average time complexity of O(n log k), which is more efficient than the O(n log n) complexity required by sorting the entire array and then selecting the kth element. The heap approach is particularly advantageously compact in memory and improves on performance when dealing with large datasets where real-time processing or space constraints are critical factors .

A hash table allows fast lookup operations due to its average-case constant time complexity, O(1), for accessing a key. This efficiency is achieved because hash tables distribute keys across an array through a hash function, making retrieval operations quick as it accesses elements directly through their indices .

The sliding window strategy involves maintaining a moving subset of contiguous elements (or indices) to efficiently study or examine a property within this window. This technique is advantageous in scenarios where the condition involves a continuous segment, such as finding the maximum sum of a subarray, since it avoids recalculating the elements’ property for every possible subarray. The sliding window manages this by adjusting one or both ends of the window, ensuring that the condition is met without needing to recompute the entire subarray, resulting in a linear time complexity, O(n).

Dynamic programming optimizes recursive solutions by identifying overlapping subproblems and storing their results, typically using a table (memoization), to avoid redundant computations. Problems with optimal substructure and repetitive calculations, such as the Fibonacci sequence, knapsack, or pathfinding in grids, benefit significantly from this approach as it reduces the time complexity from exponential (typical in naive recursion) to polynomial, allowing for efficient computation even for large inputs .

You might also like