Mastering DSA Patterns_ the Smart Way
Mastering DSA Patterns_ the Smart Way
1. Two Pointers
Concept: Use two pointers to scan from both ends of an array or string.
Use Cases: Palindrome check, reverse string, pair sum in sorted array.
Time Complexity: Best/Worst/Optimal - O(n)
Space Complexity: O(1)
Example Problems:
- Reverse String (LeetCode 344)
- Valid Palindrome (LeetCode 125)
- Two Sum II - Input Array Is Sorted (LeetCode 167)
- Remove Duplicates from Sorted Array (LeetCode 26)
- Squares of a Sorted Array (LeetCode 977)
2. Sliding Window
Concept: Fixed/variable size window moves over data to track max/min/sum, etc.
Use Cases: Max sum subarray, longest substring, etc.
Time Complexity: O(n)
Space Complexity: O(1) or O(k) depending on problem
Example Problems:
- Maximum Sum Subarray of Size K
- Longest Substring Without Repeating Characters
- Minimum Window Substring
4. Merge Intervals
Concept: Sort intervals then merge overlapping ones.
Use Cases: Calendar scheduling, interval management.
Time Complexity: O(n log n)
Space Complexity: O(n) (due to sorting or output list)
Example Problems:
- Merge Intervals
- Insert Interval
- Meeting Rooms
5. Cyclic Sort
Concept: Place each element at its correct index.
Use Cases: Missing numbers, duplicates, index positioning.
Time Complexity: O(n)
Space Complexity: O(1)
Example Problems:
- Missing Number
- Find All Duplicates in an Array
- First Missing Positive
8. DFS/BFS on Graphs
Concept: Traverse unstructured data using queue/stack/recursion.
Use Cases: Connectivity, path finding, islands.
Time Complexity: O(V + E)
Space Complexity: O(V)
Example Problems:
- Number of Islands
- Clone Graph
- Pacific Atlantic Water Flow
9. Backtracking
Concept: Explore all paths and backtrack if needed.
Use Cases: Combinations, permutations, constraint satisfaction.
Time Complexity: O(2^n) or more (varies)
Space Complexity: O(n) for recursion stack
Example Problems:
- Subsets
- Permutations
- N-Queens
- Sudoku Solver
12. Greedy
Concept: Make locally optimal choices hoping for global optimum.
Use Cases: Scheduling, path minimizing.
Time Complexity: Varies (typically O(n log n))
Space Complexity: O(1) or O(n)
Example Problems:
- Activity Selection
- Fractional Knapsack
- Jump Game