Skip to content

All of the patterns to solve problems in coding interview which i came up while preparing for my interview

License

Notifications You must be signed in to change notification settings

partho-maple/coding-interview-patterns

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 

Repository files navigation


GitHub last commit GitHub repo size in bytes Contributors Forks Stargazers Issues MIT License LinkedIn

Top 30 patterns that can be used to solve most of the coding interview questions, with matching leetcode questions

Show your support by giving it a STAR

PatternsReferences



About

To Write

Topics

  • ...

My other related repos



1. Sliding Window

Detailed explanations with leetcode examples

The Sliding Window pattern is used to perform a required operation on a specific window size of a given array or linked list, such as finding the longest subarray containing all 1s. Sliding Windows start from the 1st element and keep shifting right by one element and adjust the length of the window according to the problem that you are solving. In some cases, the window size remains constant and in other cases the sizes grows or shrinks.

alt text

📌 Following are some ways you can identify that the given problem might require a sliding window:

  • The problem input is a linear data structure such as a linked list, array, or string
  • You’re asked to find the longest/shortest substring, subarray, or a desired value

📌 Following are some properties of sliding window:

  • Time complexity should not be more than O(N)
  • Increasing the "windowEnd" pointer should increase the result/condition, and decreasing "windowStart" pointer should decrease the result/condition.

📌 Common problems you use the sliding window pattern with:

  • Maximum sum subarray of size ‘K’ (easy)
  • Longest substring with ‘K’ distinct characters (medium)
  • String anagrams (hard)

📌 Some important links:

# Title Solution Tutorial Level Remarks
01 904. Fruit Into Baskets Python Article, Video 1, Video 2 Medium Sliding Window, Two Pointer
02 3. Longest Substring Without Repeating Characters Python Vid 1, Vid 2 Medium 📌 Sliding window, Two pointer
03 340. Longest Substring with At Most K Distinct Characters Python Vid 1, Art 1, Art 2 Hard 📌 Sliding window, Two pointer
04 159. Longest Substring with At Most Two Distinct Characters Python Vid 1 Hard 📌 Sliding window, Two pointer
05 424. Longest Repeating Character Replacement Python Vid 1, Vid 2, Art 1, Art 2, Art 3, Art 4 Medium 📌 Sliding window, Very important
06 76. Minimum Window Substring Python Vid 1, Vid 2, Vid 3 Hard 📌 Sliding window, Very important
07 727. Minimum Window Subsequence Python Vid 1, Art 1, Art 2 Hard 📌 Sliding window and DP
08 438. Find All Anagrams in a String Python Must, Art 1 Medium 📌 Sliding window
09 567. Permutation in String Python Must Medium 📌 Sliding window
10 1358. Number of Substrings Containing All Three Characters Python, Swift Art 1 Medium Sliding Window
11 209. Minimum Size Subarray Sum Python, Swift --- Medium Sliding window and Binary Search
12 862. Shortest Subarray with Sum at Least K Python, Swift Art 1, Art 2, Art 3, Art 4 Hard Learned Monotonic Queue. Very interesting problem
13 683. K Empty Slots Python, Swift Art 1, Art 2, Art 3 Hard TODO: Check monotonic queue approach. Solved it with sliding widow

2. Two Pointers or Iterators

Detailed explanations with leetcode examples

Two Pointers is a pattern where two pointers iterate through the data structure in tandem until one or both of the pointers hit a certain condition. Two Pointers is often useful when searching pairs in a sorted array or linked list; for example, when you have to compare each element of an array to its other elements.

Two pointers are needed because with just pointer, you would have to continually loop back through the array to find the answer. This back and forth with a single iterator is inefficient for time and space complexity — a concept referred to as asymptotic analysis. While the brute force or naive solution with 1 pointer would work, it will produce something along the lines of O(n²). In many cases, two pointers can help you find a solution with better space or runtime complexity.

alt text

📌 Ways to identify when to use the Two Pointer method:

  • It will feature problems where you deal with sorted arrays (or Linked Lists) and need to find a set of elements that fulfill certain constraints
  • The set of elements in the array is a pair, a triplet, or even a subarray

📌 Here are some problems that feature the Two Pointer pattern:

  • Squaring a sorted array (easy)
  • Triplets that sum to zero (medium)
  • Comparing strings that contain backspaces (medium)

📌 Some important links:

# Title Solution Tutorial Level Remarks
01 167. Two Sum II - Input array is sorted Python --- Easy 📌 Two pointer basics
02 1099. Two Sum Less Than K Python --- Easy 📌 Two pointer basics
03 26. Remove Duplicates from Sorted Array Python --- Easy Two pointer basics
04 977. Squares of a Sorted Array Python --- Easy Two pointer basics
05 15. 3Sum Python --- Medium 📌 Two pointer basics
06 16. 3Sum Closest Python --- Medium 📌 Two pointer basics
07 259. 3Sum Smaller Python --- Medium 📌 Two pointer basics
09 713. Subarray Product Less Than K Python --- Medium Two pointer ad Sliding Window
10 75. Sort Colors Python Vid 1 Medium Two pointer
11 18. 4Sum Python --- Medium Two pointer
12 844. Backspace String Compare Python --- Medium 📌 Two Pointer
13 11. Container With Most Water Python --- Medium Two pointer
14 42. Trapping Rain Water Python Article 01 Hard 📌 Two pointers

3. Prefix Sum

Detailed explanations with leetcode examples

Prefix Sum is a variation of Dynamic Programming. Prefix sum is the cumulative sum of a sequence of numbers a0, a1, ... . It is itself a sequence of numbers b0, b1, ... such that

PreSum0 = a0 PreSum1 = a0 + a1 = PreSum0 + a1 PreSum2 = a0 + a1 + a2 = PreSum1 + a2 . . . . . . . . . PreSumn=PreSumn-1+an

Prefix sum operations can be generalized to any binary operator ⊕. Prefix sum operation takes a sequence of n elements [a0, a1, ..., an] and returns a sequence [a0, (a0 ⊕ a1) , ... , (a0 ⊕ a1 ⊕ a2 ... ⊕ an) ] containing the prefix sums.

For example:

A[] = {1,3,4,5,2,7,8,11} The prefix sums corresponding to A will be PreSum[] = {1,4,8,13,15,22,30,41}

Pseudocode for calculating prefix sums:

A is a sequence containing n elements

PreSum[0]=A[0]

for i=1 to n-1
    PreSum[i]=PreSum[i-1]+A[i]

Prefix sums can be used to calculate the sum of elements in a given range. If we wish to find out the sum of values between [L..R] we can obtain the sum by subtracting the prefix sum PreSum[R] by PreSum[L-1].

Sum[L..R] = PreSum[R]-PreSum[L-1] { If L!=0 } Sum[L..R] = PreSum[R] { If L=0 }

📌 How do you identify when to use the Prefix Sum pattern?

  • You will be asked to find the sum of a range in a array
  • If the problem askes to find the contigious sub array of something and the original array isn't sorted and containg negative numbers.

📌 When should I use it over the Two Pointer method mentioned above?

  • When the array contains negative numbers.

📌 Problems featuring the PreFix Sum pattern:

  • Range Sum Query (Easy)
  • Subarray Sum Equals K (medium)
  • Number of Submatrices That Sum to Target (hard)

📌 Some important links:

# Title Solution Tutorial Level Remarks
01 303. Range Sum Query - Immutable Python Vid 1 Easy ---
02 560. Subarray Sum Equals K Python Art 1, Art 2, Art 3, Art 4, Art 5, Art 6 Medium Very tricky and persuasive with Sliding Window but it's not. This is a classic running sum problem
03 325. Maximum Size Subarray Sum Equals k Python Art 1 Medium Very tricky and persuasive with Sliding Window but it's not. This is a classic running sum problem
04 1074. Number of Submatrices That Sum to Target Python Art 1, Art 2, Art 3, Art 4 Extremely Hard Very tricky and hard, check again. Also DP
05 437. Path Sum III Python Educative.io, Art 1, Art 2 Medium 📌 A good example of Prefix Sum and DFS. Very Important
06 528. Random Pick with Weight Python Vid 1, Art 1 Medium Very tricky
07 363. Max Sum of Rectangle No Larger Than K Python, Swift Vid 1, Vid 2, Art 1, Art 2, Art 3 Hard DP and BS. Disn't understand S part. TODO: Check again
08 862. Shortest Subarray with Sum at Least K Python, Swift Art 1, Art 2, Art 3, Art 4 Hard Learned Monotonic Queue. Very interesting problem

4. Fast and Slow Pointers or Iterators

Detailed explanations with leetcode examples

The Fast and Slow pointer approach, also known as the Hare & Tortoise algorithm, is a pointer algorithm that uses two pointers which move through the array (or sequence/linked list) at different speeds. This approach is quite useful when dealing with cyclic linked lists or arrays.

By moving at different speeds (say, in a cyclic linked list), the algorithm proves that the two pointers are bound to meet. The fast pointer should catch the slow pointer once both the pointers are in a cyclic loop.

alt text

📌 How do you identify when to use the Fast and Slow pattern?

  • The problem will deal with a loop in a linked list or array
  • When you need to know the position of a certain element or the overall length of the linked list.

📌 When should I use it over the Two Pointer method mentioned above?

  • There are some cases where you shouldn’t use the Two Pointer approach such as in a singly linked list where you can’t move in a backwards direction. An example of when to use the Fast and Slow pattern is when you’re trying to determine if a linked list is a palindrome.

📌 Problems featuring the fast and slow pointers pattern:

  • Linked List Cycle (easy)
  • Palindrome Linked List (medium)
  • Cycle in a Circular Array (hard)
# Title Solution Tutorial Level Remarks
01 141. Linked List Cycle Python --- Easy Fast pointer Slow pointer
02 142. Linked List Cycle II Python Art 1, Art 2, AlgoExpert.io Medium Fast pointer Slow pointer
03 202. Happy Number Python Art 1 Easy Fast pointer Slow pointer
04 876. Middle of the Linked List Python --- Easy Fast pointer Slow pointer
05 234. Palindrome Linked List Python --- Easy Fast pointer Slow pointer
06 143. Reorder List Python --- Medium Fast pointer Slow pointer
07 457. Circular Array Loop Python --- Medium Fast pointer Slow pointer. Check again
08 19. Remove Nth Node From End of List Python --- Medium Fast pointer Slow pointer
09 283. Move Zeroes Python, Swift --- Easy Not so easy and intuitive. Uses fast and slow pointer

5. Merge Intervals

Detailed explanations with leetcode examples

The Merge Intervals pattern is an efficient technique to deal with overlapping intervals. In a lot of problems involving intervals, you either need to find overlapping intervals or merge intervals if they overlap. The pattern works like this:

Given two intervals (‘a’ and ‘b’), there will be six different ways the two intervals can relate to each other:

Understanding and recognizing these six cases will help you help you solve a wide range of problems from inserting intervals to optimizing interval merges.

alt text

📌 How do you identify when to use the Merge Intervals pattern?

  • If you’re asked to produce a list with only mutually exclusive intervals
  • If you hear the term “overlapping intervals”.

📌 Merge interval problem patterns:

  • Intervals Intersection (medium)
  • Maximum CPU Load (hard)
# Title Solution Tutorial Level Remarks
01 56. Merge Intervals Python Article
02 57. Insert Interval Python Must Hard Greedy and Merge interval
03 986. Interval List Intersections Python --- Medium Greedy and Two Pointer
04 252. Meeting Rooms Python Official Easy Greedy and uses heap
05 253. Meeting Rooms II Python Official Medium Greedy and uses heap
06 621. Task Scheduler Python Ex 1, Ex 2, Vid 1, Vid 2, Vid 3, Vid 4 Medium 📌 Extremely tricky. Classic problem
07 435. Non-overlapping Intervals Python Vid 1, Art 1 Medium Classic problem
08 759. Employee Free Time Python Educative.io Hard Greedy and uses heap. Not done. Check again
09 616. Add Bold Tag in String Python, Swift --- Medium Merge intervals(hidden)
10 731. My Calendar II Python, Swift Medium Merge interval

6. Cyclic sort

Detailed explanations with leetcode examples

This pattern describes an interesting approach to deal with problems involving arrays containing numbers in a given range. The Cyclic Sort pattern iterates over the array one number at a time, and if the current number you are iterating is not at the correct index, you swap it with the number at its correct index. You could try placing the number in its correct index, but this will produce a complexity of O(n^2) which is not optimal, hence the Cyclic Sort pattern.

alt text

📌 How do I identify this pattern?

  • They will be problems involving a sorted array with numbers in a given range
  • If the problem asks you to find the missing/duplicate/smallest number in an sorted/rotated array
  • There will be a certain relation between the array indexxes and it's actual associated values

📌 Problems featuring cyclic sort pattern:

  • Find the Missing Number (easy)
  • Find the Smallest Missing Positive Number (medium)

📌 Some important links:

# Title Solution Tutorial Level Remarks
01 268. Missing Number Python Official Easy 📌 Also check Bit manipulation where I learned few very important binary logic properties
02 448. Find All Numbers Disappeared in an Array Python --- Easy Cyclic Sort
03 287. Find the Duplicate Number Python --- Medium Cyclic Sort. TODO: Check all other approaches
04 442. Find All Duplicates in an Array Python --- Medium Cyclic Sort TODO: Check all other approaches
05 41. First Missing Positive Python --- Hard Cyclic Sort, Very important

7. In-place reversal of linked list

Detailed explanations with leetcode examples

In a lot of problems, you may be asked to reverse the links between a set of nodes of a linked list. Often, the constraint is that you need to do this in-place, i.e., using the existing node objects and without using extra memory. This is where the above mentioned pattern is useful.

This pattern reverses one node at a time starting with one variable (current) pointing to the head of the linked list, and one variable (previous) will point to the previous node that you have processed. In a lock-step manner, you will reverse the current node by pointing it to the previous before moving on to the next node. Also, you will update the variable “previous” to always point to the previous node that you have processed. alt text

📌 How do I identify when to use this pattern:

  • If you’re asked to reverse a linked list without using extra memory

📌 Problems featuring in-place reversal of linked list pattern:

  • Reverse a Sub-list (medium)
  • Reverse every K-element Sub-list (medium)
# Title Solution Tutorial Level Remarks
01 206. Reverse Linked List Python Vid 1, Vid 2 Easy Fundamental
02 92. Reverse Linked List II Python educative.io, Art 2 Medium Fundamental and very important
03 25. Reverse Nodes in k-Group Python educative.io, Art 1, Art 2 Hard Fundamental. TODO: Check again
04 24. Swap Nodes in Pairs Python educative.io Medium Fundamental
05 61. Rotate List Python educative.io Medium Fundamental
06 328. Odd Even Linked List Python Art 1 Medium Fundamental
07 21. Merge Two Sorted Lists Python Algoexpert.io, Vid 1 Easy Fundamental and very very important
08 148. Sort List Python Vid 1, Vid 2, Vid 3, Art 1 Medium Fundamental
09 23. Merge k Sorted Lists Python Art 1 Hard Very important
10 160. Intersection of Two Linked Lists Python Art 1, Art 2 Easy ---
11 138. Copy List with Random Pointer Python Vid 1, Art 1 Medium TODO: Check again. Very important. Learned a lot of things
12 430. Flatten a Multilevel Doubly Linked List Python codinginterviewclass.com, Vid 1, Art 1 Medium TODO: Check again. Very important. Learned a lot of things
13 146. LRU Cache Python Vid 1, backtobackswe.com, algoexpert.io Medium TODO: Check again. Very important. Learned a lot of things

8. Tree BFS

Detailed explanations with leetcode examples

This pattern is based on the Breadth First Search (BFS) technique to traverse a tree and uses a queue to keep track of all the nodes of a level before jumping onto the next level. Any problem involving the traversal of a tree in a level-by-level order can be efficiently solved using this approach.

The Tree BFS pattern works by pushing the root node to the queue and then continually iterating until the queue is empty. For each iteration, we remove the node at the head of the queue and “visit” that node. After removing each node from the queue, we also insert all of its children into the queue.

📌 How to identify the Tree BFS pattern:

  • If you’re asked to traverse a tree in a level-by-level fashion (or level order traversal)

📌 Problems featuring Tree BFS pattern:

  • Binary Tree Level Order Traversal (easy)
  • Zigzag Traversal (medium)
# Title Solution Tutorial Level Remarks
01 102. Binary Tree Level Order Traversal Python --- Medium 📌
02 107. Binary Tree Level Order Traversal II Python --- Easy 📌
03 103. Binary Tree Zigzag Level Order Traversal Python --- Medium 📌
04 111. Minimum Depth of Binary Tree Python Educative.io Easy ---
05 116. Populating Next Right Pointers in Each Node Python Must, Art 1, Art 2, Art 3 Medium BFS/DFS, Level order traversal
06 117. Populating Next Right Pointers in Each Node II Python Vid 1, Vid 2 Medium Very tricky, check again
07 429. N-ary Tree Level Order Traversal Python
08 559. Maximum Depth of N-ary Tree Python
09 199. Binary Tree Right Side View Python --- Medium ---
10 863. All Nodes Distance K in Binary Tree Python Vid 1, Art 1, Art 2 Medium A combination of graph and tree. TODO: Check again. Very important
11 301. Remove Invalid Parentheses Python Vid 1, Vid 2, Art 2 Hard TODO: Not done, Check again. Very important. FS and DFS
12 1197. Minimum Knight Moves Python Art 1 Medium TODO: Check AGain. Important.

9. Tree DFS

Detailed explanations with leetcode examples

Tree DFS is based on the Depth First Search (DFS) technique to traverse a tree.

You can use recursion (or a stack for the iterative approach) to keep track of all the previous (parent) nodes while traversing.

The Tree DFS pattern works by starting at the root of the tree, if the node is not a leaf you need to do three things:

Decide whether to process the current node now (pre-order), or between processing two children (in-order) or after processing both children (post-order). Make two recursive calls for both the children of the current node to process them.

📌 How to identify the Tree DFS pattern:

  • If you’re asked to traverse a tree with in-order, preorder, or postorder DFS
  • If the problem requires searching for something where the node is closer to a leaf

📌 Problems featuring Tree DFS pattern:

  • Sum of Path Numbers (medium)
  • All Paths for a Sum (medium)
# Title Solution Tutorial Level Remarks
01 112. Path Sum Python Art 1 Easy ---
02 113. Path Sum II Python Art 1, Art 2 Medium ---
03 437. Path Sum III Python Educative.io, Art 1, Art 2 Medium 📌 A good example of Prefix Sum and DFS. Very Important
04 543. Diameter of Binary Tree Python Educative.io, Art 1 Medium 📌 Important
05 124. Binary Tree Maximum Path Sum Python Art 1, Art 2, Vid 1, AlgoExpert Very Hard Very important and tricky

10. Two Heaps

Detailed explanations with leetcode examples

In many problems, we are given a set of elements such that we can divide them into two parts. To solve the problem, we are interested in knowing the smallest element in one part and the biggest element in the other part. This pattern is an efficient approach to solve such problems.

This pattern uses two heaps; A Min Heap to find the smallest element and a Max Heap to find the biggest element. The pattern works by storing the first half of numbers in a Max Heap, this is because you want to find the largest number in the first half. You then store the second half of numbers in a Min Heap, as you want to find the smallest number in the second half. At any time, the median of the current list of numbers can be calculated from the top element of the two heaps.

📌 Ways to identify the Two Heaps pattern:

  • Useful in situations like Priority Queue, Scheduling
  • If the problem states that you need to find the smallest/largest/median elements of a set
  • Sometimes, useful in problems featuring a binary tree data structure

📌 Problems featuring

  • Find the Median of a Number Stream (medium)
# Title Solution Tutorial Level Remarks
01 295. Find Median from Data Stream Python algoexpert.io, educative.io, codinginterviewclass.com, Official, FollowUp 1 Hard 📌 Very Tricky and important. TODO: Check again
02 480. Sliding Window Median Python educative.io, Vid 1 Hard 📌 Sliding window with 2 heap. very important
03 4. Median of Two Sorted Arrays Python Article 01, Art 2 Video 1 Hard 📌 Classic problem

11. Subsets

Detailed explanations with leetcode examples

A huge number of coding interview problems involve dealing with Permutations and Combinations of a given set of elements. The pattern Subsets describes an efficient Breadth First Search (BFS) approach to handle all these problems.

📌 The pattern looks like this:

Given a set of [1, 5, 3]

  • Start with an empty set: [[]]
  • Add the first number (1) to all the existing subsets to create new subsets: [[], [1]];
  • Add the second number (5) to all the existing subsets: [[], [1], [5], [1,5]];
  • Add the third number (3) to all the existing subsets: [[], [1], [5], [1,5], [3], [1,3], [5,3], [1,5,3]].
  • Here is a visual representation of the Subsets pattern: alt text

📌 How to identify the Subsets pattern:

  • Problems where you need to find the combinations or permutations of a given set

📌 Problems featuring Subsets pattern:

  • Subsets With Duplicates (easy)
  • String Permutations by changing case (medium)
# Title Solution Tutorial Level Remarks
01 78. Subsets Python Video 1, Video 2, Video 3, Article 1, educative.io Medium 📌 TODO: check bit manipulation
02 90. Subsets II Python Video 1, Video 2, Video 3, Article 1, educative.io Medium 📌
03 46. Permutations Python codinginterviewclass.com, algoexpert.io, educative.io, Article 1, Article 2 Medium Backtracking Fundamentals
04 47. Permutations II Python codinginterviewclass.com, algoexpert.io, educative.io, Article 1 Medium Backtracking Fundamentals
05 31. Next Permutation Python codinginterviewclass.com, Vid 1, Art 1 Medium Backtracking
06 77. Combinations Python codinginterviewclass.com Medium Backtracking
07 39. Combination Sum Python Article 1, Article 2 Medium Backtracking Fundamentals
08 40. Combination Sum II Python --- Medium Backtracking Fundamentals
09 17. Letter Combinations of a Phone Number Python Video 1, Video 2 - paid course, Article 1 Medium Backtracking Fundamentals
10 22. Generate Parentheses Python educative.io, Video 1, Article 1 Medium Backtracking Fundamentals
11 96. Unique Binary Search Trees Python educative.io, Vid 1, Art 1, Vid 2, Vis 3 Medium 📌 Fundamentals
12 95. Unique Binary Search Trees II Python educative.io Medium ---

12. Modified Binary Search

Detailed explanations with leetcode examples

Whenever you are given a sorted array, or matrix, and are asked to find a certain element, the best algorithm you can use is the Binary Search. This pattern describes an efficient way to handle all problems involving Binary Search.

📌 The patterns looks like this for an ascending order set:

  • First, find the middle of start and end. An easy way to find the middle would be: middle = (start + end) / 2. But this has a good chance of producing an integer overflow so it’s recommended that you represent the middle as: middle = start + (end — start) / 2
  • If the key is equal to the number at index middle then return middle
  • If ‘key’ isn’t equal to the index middle:
  • Check if key < arr[middle]. If it is reduce your search to end = middle — 1
  • Check if key > arr[middle]. If it is reduce your search to start = middle + 1

Here is a visual representation of the Modified Binary Search pattern: alt text

📌 Problems featuring the Modified Binary Search pattern:

  • Order-agnostic Binary Search (easy)
  • Search in a Sorted Infinite Array (medium)
# Title Solution Tutorial Level Remarks
01 704. Binary Search Python --- Easy Basics
02 702. Search in a Sorted Array of Unknown Size Python Educative.io Medium 📌 Binary Search Template I
03 69. Sqrt(x) Python --- Easy 📌 Binary Search Template I
04 374. Guess Number Higher or Lower Python --- Easy 📌 Binary Search Template I
05 33. Search in Rotated Sorted Array Python Educative.io Medium 📌 Binary Search Template I, very important, not done
06 81. Search in Rotated Sorted Array II Python --- Medium 📌 Binary Search Template I, very important
07 278. First Bad Version Python --- Easy 📌 Binary Search Template II
08 162. Find Peak Element Python --- Medium 📌 Binary Search Template II
09 153. Find Minimum in Rotated Sorted Array Python --- Medium 📌 Binary Search Template II
10 154. Find Minimum in Rotated Sorted Array II Python --- Hard 📌 Binary Search Template II, not done
11 34. Find First and Last Position of Element in Sorted Array Python Vid 1, Educative.io Medium 📌 Binary Search Template III
12 658. Find K Closest Elements Python Vid 1 Medium 📌 Binary Search Template III
13 410. Split Array Largest Sum Python Article 01 Hard 📌 Not done
14 1231. Divide Chocolate Python Art 1, Art 2, Art 3, Vid 1 Hard 📌 Not done. Check again. Solve all similar question
15 410. Split Array Largest Sum Python Vid 1, Art 1, Art 2 Hard 📌 TODO: Check again. It's a fucking difficult and interesting and important
16 1231. Divide Chocolate Python, Swift Art 1, Art 2, Art 3 Hard I loved this problem. Very important

13. Bitwise XOR

Detailed explanations with leetcode examples

XOR is a logical bitwise operator that returns 0 (false) if both bits are the same and returns 1 (true) otherwise. In other words, it only returns 1 if exactly one bit is set to 1 out of the two bits in comparison.

A B A xor B
0 0 0
0 1 1
1 0 1
1 1 0

It is surprising to know the approaches that the XOR operator enables us to solve certain problems.

📌 Please check thefollowing and go through to understand this patter a it more details.

# Title Solution Tutorial Level Remarks
01 268. Missing Number Python Educative.io, Official Easy 📌 Learned few very important binary logic properties. Also check cyclic sort technique
02 136. Single Number Python Educative.io Easy 📌 The key here is to practice bit operation, i ignore any other attempts
03 137. Single Number II Python 1, 2, 3, Check discussion Medium ⭐ 😭 Didn't understand, check again
04 260. Single Number III Python Educative.io Medium ⭐ 😭 Check again, very important
05 476. Number Complement Python Educative.io Easy ⭐ Check again
06 832. Flipping an Image Python Educative.io Easy ⭐ Check again

14. Top K Elements

Detailed explanations with leetcode examples

Any problem that asks us to find the top/smallest/frequent ‘K’ elements among a given set falls under this pattern.

The best data structure to keep track of ‘K’ elements is Heap. This pattern will make use of the Heap to solve multiple problems dealing with ‘K’ elements at a time from a set of given elements.

📌 The pattern looks like this:

  1. Insert ‘K’ elements into the min-heap or max-heap based on the problem.
  2. Iterate through the remaining numbers and if you find one that is larger than what you have in the heap, then remove that number and insert the larger one.

alt text

There is no need for a sorting algorithm because the heap will keep track of the elements for you.

📌 How to identify the Top ‘K’ Elements pattern:

  • If you’re asked to find the top/smallest/frequent ‘K’ elements of a given set
  • If you’re asked to sort an array to find an exact element

📌 Problems featuring Top ‘K’ Elements pattern:

  • Top ‘K’ Numbers (easy)
  • Top ‘K’ Frequent Numbers (medium)
# Title Solution Tutorial Level Remarks
01 215. Kth Largest Element in an Array Python Art 01, Algoexpert.io, educative.io Medium 📌 Also check Quickselect method.
02 973. K Closest Points to Origin Python Algoexpert.io, educative.io, Vid 1 Medium 📌 Also check Quickselect and heap method
03 347. Top K Frequent Elements Python educative.io, Helper 1, Helper 2, heapq, Counter Medium ---
04 451. Sort Characters By Frequency Python Algoexpert.io, educative.io Medium 📌 Also check Quickselect and heap method
05 692. Top K Frequent Words Python Algoexpert.io, educative.io Medium 📌 Also check Quickselect and heap method
06 703. Kth Largest Element in a Stream Python educative.io Medium 📌 ---
07 658. Find K Closest Elements Python Vid 1, educative.io Medium 📌 Binary Search Template III. TODO: Check Heap approach which is not done
08 358. Rearrange String k Distance Apart Python Educative.io, Educative.io 2 Hard 📌 Similar to 621. Task Scheduler. Very Important. TODO: Check Heap approach
09 295. Find Median from Data Stream Python algoexpert.io, educative.io, educative.io 2, codinginterviewclass.com, Official, FollowUp 1 Hard 📌 Very Tricky and important. TODO: Check again
10 895. Maximum Frequency Stack Python educative.io Hard 📌 TODO: Check again

15. K-way Merge

Detailed explanations with leetcode examples

K-way Merge helps you solve problems that involve a set of sorted arrays.

Whenever we are given ‘K’ sorted arrays, we can use a Heap to efficiently perform a sorted traversal of all the elements of all arrays. We can push the smallest (first) element of each sorted array in a Min Heap to get the overall minimum. While inserting elements to the Min Heap we keep track of which array the element came from. We can, then, remove the top element from the heap to get the smallest element and push the next element from the same array, to which this smallest element belonged, to the heap. We can repeat this process to make a sorted traversal of all elements.

alt text

📌 The pattern looks like this:

  • Insert the first element of each array in a Min Heap.
  • After this, take out the smallest (top) element from the heap and add it to the merged list.
  • After removing the smallest element from the heap, insert the next element of the same list into the heap.
  • Repeat steps 2 and 3 to populate the merged list in sorted order.

📌 How to identify the K-way Merge pattern:

  • The problem will feature sorted arrays, lists, or a matrix
  • If the problem asks you to merge sorted lists, find the smallest element in a sorted list.

📌 Problems featuring the K-way Merge pattern:

  • Merge K Sorted Lists (medium)
  • K Pairs with Largest Sums (Hard)
# Title Solution Tutorial Level Remarks
01 23. Merge k Sorted Lists Python educative.io, Art 1 Hard Very important. TODO: Check heap approach
02 378. Kth Smallest Element in a Sorted Matrix Python educative.io Hard 📌 TODO: Check again the Binary Search approach. Very important
03 632. Smallest Range Covering Elements from K Lists Python educative.io Hard 📌 TODO: Check again. Very important
04 373. Find K Pairs with Smallest Sums Python educative.io Hard 📌 TODO: Check again.

16. Topological Sort (Graph Theory)

Detailed explanations with leetcode examples

Topological Sort is used to find a linear ordering of elements that have dependencies on each other. For example, if event ‘B’ is dependent on event ‘A’, ‘A’ comes before ‘B’ in topological ordering.

This pattern defines an easy way to understand the technique for performing topological sorting of a set of elements.

📌 The pattern works like this:

  • Initialization
    • a) Store the graph in adjacency lists by using a HashMap
    • b) To find all sources, use a HashMap to keep the count of in-degrees
  • Build the graph and find in-degrees of all vertices
    • a) Build the graph from the input and populate the in-degrees HashMap.

alt text

  • Find all sources
    • a) All vertices with ‘0’ in-degrees will be sources and are stored in a Queue.
  • Sort
    • a) For each source, do the following things:

        1. Add it to the sorted list.   - 2) Get all of its children from the graph.   - 3) Decrement the in-degree of each child by 1.
        1. If a child’s in-degree becomes ‘0’, add it to the sources Queue.
    • b) Repeat (a), until the source Queue is empty.

📌 How to identify the Topological Sort pattern:

  • The problem will deal with graphs that have no directed cycles
  • If you’re asked to update all objects in a sorted order
  • If you have a class of objects that follow a particular order

📌 Problems featuring the Topological Sort pattern:

  • Task scheduling (medium)
  • Minimum height of a tree (hard)

📌 Some importanr referrences and further study materials

# Title Solution Tutorial Level Remarks
01 207. Course Schedule Python educative.io Medium 📌 Very Important. Check again. BFS, Topological Sort
02 210. Course Schedule II Python educative.io Medium 📌 Very Important. Check again. BFS, Topological Sort
03 269. Alien Dictionary Python educative.io, Vid 1, Vid 2, Vid 3 Hard 📌 Very Important. Check again. BFS, Topological Sort
04 444. Sequence Reconstruction Python educative.io Medium/Hard 📌 Check again. BFS, Topological Sort
05 310. Minimum Height Trees Python educative.io Hard 📌 TODO: Check again, very hard, didn't get the intuition. BFS, Topological Sort
06 329. Longest Increasing Path in a Matrix Python Official, Art 1, Art 2 Hard ** 📌 TODO: Not Done, very hard and important. DP, Topological Sort **
07 1203. Sort Items by Groups Respecting Dependencies Python Hard 📌 TODO: Not Done, very hard, didn't get the intuition. BFS, Topological Sort
08 1136. Parallel Courses Python, Swift --- Hard 📌 Topological sort.

17. Union Find (Graph Theory)

Detailed explanations with leetcode examples

📌 What is Union Find(Disjoint-set) data structure?

  • Represents a mathematics concept Set.
  • A disjoint-set data structure, also called a union–find data structure or merge–find set.
  • A disjoint-set data structure that keeps track of a set of elements partitioned into a number of disjoint or non-overlapping subsets.
  • It provides near-constant-time operations to add new sets, to merge existing sets, and to determine whether elements are in the same set.
  • Plays a key role in Kruskal’s algorithm for finding the minimum spanning tree of a graph.
  • This can also be used to detect cycle in the graph.

📌 How Disjoint Set is constructed:

  • A disjoint-set forest consists of a number of elements each of which stores an id, a parent pointer
  • The parent pointers of elements are arranged to form one or more trees, each representing a set.
  • If an element’s parent pointer points to no other element, then the element is the root of a tree and is the representative member of its set.
  • A set may consist of only a single element. However, if the element has a parent, the element is part of whatever set is identified by following the chain of parents upwards until a representative element (one without a parent) is reached at the root of the tree.

alt text

📌 Disjoint Set Operations:

  • MakeSet(X): This operation makes a new set by creating a new element with a parent pointer to itself. The parent pointer to itself indicates that the element is the representative member of its own set. The MakeSet operation has O(1) time complexity.

  • Find(X): follows the chain of parent pointers from x upwards through the tree until an element is reached whose parent is itself. This element is the root of the tree and is the representative member of the set to which x belongs, and may be x itself.

  • Union(x,y): Uses Find to determine the roots of the trees x and y belong to. If the roots are distinct, the trees are combined by attaching the root of one to the root of the other. If this is done naively, such as by always making x a child of y, the height of the trees can grow as O(n).

📌 Some important referrences and further study materials

# Title Solution Tutorial Level Remarks
01 200. Number of Islands Python Algoexpert.io - DFS, Union Find Medium DFS + DFS, Union Find
02 305. Number of Islands II Python Union Find, Art 0, Art 1, Art 2, Art 3, Art 4, Art 5 Hard Union Find
03 947. Most Stones Removed with Same Row or Column Python, Swift Vid 1, Art 1, Vid 2, Art 2, Art 3 Medium 📌 DFS and Union FInd
# Solve at least 10 more problems form this list using Uion Find --- --- --- ---

18. Few Common Algorithms on Graph (Graph Theory)

Detailed explanations with leetcode examples

# Title Solution Tutorial Level Remarks
01 332. Reconstruct Itinerary Python Vid 1, Vid 2, Art 1, Art 2, Art 3, Art 4 Medium Important, Learned new things. Directed Graph. Eulerian path and top Sort
02 743. Network Delay Time Python Official, Dijkstra 1, Dijkstra 2, Vid 1, Art 1, Art 2, Art 3, Art 4 Medium TODO: Check again. Very Important. Learned (Dijkstra, Bellman, Floyed). Check references section
03 1168. Optimize Water Distribution in a Village Python Art 1, Art 2, Art 3, Art 4 Hard TODO: Check AGain. Prim's and Kruskal's algorithm. Important.
04 1066. Campus Bikes II Python Vid 1, Art 1 Medium 📌 TODO: CHECK Dijkstra approach again. Backtracking solution is getting TLE. Solve it and implement it with DP also. Very important
05 1192. Critical Connections in a Network Python, Swift Art 1, Art 2, Art 3, Art 4, Vid 1, Vid 2, Vid 3 Hard 📌 Important, Learned new things.Tarjans SCCs algorithm. Check again

19. 0/1 Knapsack (Dynamic Programing)

Detailed explanations with leetcode examples

Introduction

Given the weights and profits of N items, we are asked to put these items in a knapsack which has a capacity C. The goal is to get the maximum profit from the items in the knapsack. Each item can only be selected once, as we don’t have multiple quantities of any item.

Let’s take the example of Merry, who wants to carry some fruits in the knapsack to get maximum profit. Here are the weights and profits of the fruits:

Items: { Apple, Orange, Banana, Melon }
Weights: { 2, 3, 1, 4 }
Profits: { 4, 5, 3, 7 }
Knapsack capacity: 5

Let’s try to put different combinations of fruits in the knapsack, such that their total weight is not more than 5:

Apple + Orange (total weight 5) => 9 profit
Apple + Banana (total weight 3) => 7 profit
Orange + Banana (total weight 4) => 8 profit
Banana + Melon (total weight 5) => 10 profit

This shows that Banana + Melon is the best combination, as it gives us the maximum profit and the total weight does not exceed the capacity.

Problem Statement

Given two integer arrays to represent weights and profits of N items, we need to find a subset of these items which will give us maximum profit such that their cumulative weight is not more than a given number C. Each item can only be selected once, which means either we put an item in the knapsack or we skip it.

📌 Some very importanr referrences and further study materials

# Title Solution Tutorial Level Remarks
01 416. Partition Equal Subset Sum Python educative.io, Art 1, Vid 1, Vid 2, Vid 3, Vid 4 Medium 0/1 Knapsack, Very important
02 494. Target Sum Python educative.io, MUST MUST READ Medium 0/1 Knapsack, Very important. TODO: Not DOne. Check again

20. Unbounded Knapsack (Dynamic Programing)

Detailed explanations with leetcode examples

Introduction

Given the weights and profits of N items, we are asked to put these items in a knapsack which has a capacity C. The goal is to get the maximum profit from the items in the knapsack. The only difference between the 0/1 Knapsack problem and this problem is that we are allowed to use an unlimited quantity of an item.

Let’s take the example of Merry, who wants to carry some fruits in the knapsack to get maximum profit. Here are the weights and profits of the fruits:

Items: { Apple, Orange, Melon }
Weights: { 1, 2, 3 }
Profits: { 15, 20, 50 }
Knapsack capacity: 5

Let’s try to put different combinations of fruits in the knapsack, such that their total weight is not more than 5.

5 Apples (total weight 5) => 75 profit
1 Apple + 2 Oranges (total weight 5) => 55 profit
2 Apples + 1 Melon (total weight 5) => 80 profit
1 Orange + 1 Melon (total weight 5) => 70 profit

This shows that 2 apples + 1 melon is the best combination, as it gives us the maximum profit and the total weight does not exceed the capacity.

Problem Statement

Given two integer arrays to represent weights and profits of N items, we need to find a subset of these items which will give us maximum profit such that their cumulative weight is not more than a given number C. We can assume an infinite supply of item quantities; therefore, each item can be selected multiple times.

📌 Some very importanr referrences and further study materials

# Title Solution Tutorial Level Remarks
01 518. Coin Change 2 Python educative.io, Vid 1, codinginterviewclass.com, Algoexpert.io Medium Unbounded Knapsack
02 322. Coin Change Python educative.io, Vid 1, Algoexpert.io Medium Unbounded Knapsack
03 343. Integer Break Python Art 1, Art 2 Medium Unbounded Knapsack. TODO: Not Done. Check again

21. Fibonacci Numbers (Dynamic Programing)

Detailed explanations with leetcode examples

Problem Statement

Write a function to calculate the nth Fibonacci number.

Fibonacci numbers are a series of numbers in which each number is the sum of the two preceding numbers. First few Fibonacci numbers are: 0, 1, 1, 2, 3, 5, 8, …

Mathematically we can define the Fibonacci numbers as:

    Fib(n) = Fib(n-1) + Fib(n-2), for n > 1
 
    Given that: Fib(0) = 0, and Fib(1) = 1

The time complexity of the above algorithm is exponential O(2^n) as we are making two recursive calls in the same function. The space complexity is O(n) which is used to store the recursion stack.

Let’s visually draw the recursion for CalculateFibonacci(4) to see the overlapping subproblems:

alt text

We can clearly see the overlapping subproblem pattern: fib(2) has been called twice and fib(1) has been called thrice. We can optimize this using memoization to store the results for subproblems.

📌 Some very importanr referrences and further study materials

# Title Solution Tutorial Level Remarks
01 70. Climbing Stairs Python educative.io Easy Fibonacci sequence pattern
02 55. Jump Game Python Official , Art 1 Medium 📌 Must Check. Learned a lot
03 45. Jump Game II Python educative.io, Vid 1, Vid 2, Vid 3, Art 1 Hard 📌
04 198. House Robber Python Must, educative.io Easy A Gold Mine
05 213. House Robber II Python Art 1, Art 2 Medium ---
06 337. House Robber III Python Art 1 Medium Another gold mine, hidden greedy and DFS
07 279. Perfect Squares Python Must, Vid 1, Vis 2 Medium TODO: Check again. Very Important. Very analytical and tricky to come up with

22. Palindromic Subsequence (Dynamic Programing on Strings)

Detailed explanations with leetcode examples

There are some problems that deals with Longest/Minimum Common/Increasing/Bitonic/Repeating/Alterating Subsequence/Substring on Palindrome which are generally solved using DP.

General problem statement for this pattern can vary but most of the time you are given one string where length of that string is not big

Statement

Given one strings s1, return some result.

Approach

Most of the problems on this pattern requires a solution that can be accepted in O(n^2) complexity.

for (int l = 1; l < n; ++l) {
   for (int i = 0; i < n-l; ++i) {
       int j = i + l;
       if (s[i] == s[j]) {
           dp[i][j] = /*code*/;
       } else {
           dp[i][j] = /*code*/;
       }
   }
}
# Title Solution Tutorial Level Remarks
01 516. Longest Palindromic Subsequence Python educative.io, Vid 1, Vid 2 Medium ---
02 5. Longest Palindromic Substring Python educative.io, algoexpert.io, Vid 1 Medium 📌 Classic DP
03 647. Palindromic Substrings Python educative.io Medium ---
04 680. Valid Palindrome II Python educative.io, Art 1, Art 2 Medium ---
05 1312. Minimum Insertion Steps to Make a String Palindrome Python educative.io Hard ---
06 132. Palindrome Partitioning II Python educative.io, algoexpert.io, Vid 1, Vid 2 Hard TODO: Check again. Very difficult and important

23. Longest Common Subsequence (Dynamic Programing on Strings)

Detailed explanations with leetcode examples

There are some problems that deals with Longest/Minimum Common/Increasing/Bitonic/Repeating/Alterating Subsequence/Substring which are generally solved using DP.

General problem statement for this pattern can vary but most of the time you are given two strings where lengths of those strings are not big

Statement

Given two strings s1 and s2, return some result.

Approach

Most of the problems on this pattern requires a solution that can be accepted in O(n^2) complexity.

// i - indexing string s1
// j - indexing string s2
for (int i = 1; i <= n; ++i) {
   for (int j = 1; j <= m; ++j) {
       if (s1[i-1] == s2[j-1]) {
           dp[i][j] = /*code*/;
       } else {
           dp[i][j] = /*code*/;
       }
   }
}
# Title Solution Tutorial Level Remarks
01 718. Maximum Length of Repeated Subarray Python educative.io Medium Longest Common Substring variation
02 1143. Longest Common Subsequence Python educative.io, algoexpert.io Medium 📌 Classic DP
03 583. Delete Operation for Two Strings Python educative.io Medium ---
04 300. Longest Increasing Subsequence Python educative.io, codinginterviewclass.com, algoexpert.io, Vid 01, Vid 2 Medium 📌 Need to check Binary Search approach, which is a lot harder
05 334. Increasing Triplet Subsequence Python educative.io, codinginterviewclass.com, algoexpert.io, Vid 01, Vid 2 Medium ---
06 1092. Shortest Common Supersequence Python educative.io, Art 1 Hard TODO: Not Done
07 115. Distinct Subsequences Python educative.io Hard TODO: Check again
08 97. Interleaving String Python educative.io, Vid 1 Hard TODO: Check again. Very difficult and tricky to understand
09 72. Edit Distance Python educative.com, algoexpert.io, codinginterviewclass.com, Vid 1, Vid 2 Hard TODO: Check again. Very important and classic. Levenshtein Distance

24. Minimum (Maximum) Path to Reach a Target (Dynamic Programing)

Detailed explanations with leetcode examples

Statement

Given a target find minimum (maximum) cost / path / sum to reach the target.

Approach

Choose minimum (maximum) path among all possible paths before the current state, then add value for the current state. routes[i] = min(routes[i-1], routes[i-2], ... , routes[i-k]) + cost[i]

Generate optimal solutions for all values in the target and return the value for the target.

for (int i = 1; i <= target; ++i) {
   for (int j = 0; j < ways.size(); ++j) {
       if (ways[j] <= i) {
           dp[i] = min(dp[i], dp[i - ways[j]]) + cost / path / sum;
       }
   }
}
 
return dp[target]
# Title Solution Tutorial Level Remarks

25. Distinct Ways (Dynamic Programing)

Detailed explanations with leetcode examples

Statement

Given a target find a number of distinct ways to reach the target.

Approach

Sum all possible ways to reach the current state. routes[i] = routes[i-1] + routes[i-2], ... , + routes[i-k]

Generate sum for all values in the target and return the value for the target.

for (int i = 1; i <= target; ++i) {
   for (int j = 0; j < ways.size(); ++j) {
       if (ways[j] <= i) {
           dp[i] += dp[i - ways[j]];
       }
   }
}
 
return dp[target]

Notes

  • Some questions point out the number of repetitions, in that case, add one more loop to simulate every repetition.
# Title Solution Tutorial Level Remarks

26. Merging Intervals (Dynamic Programing)

Detailed explanations with leetcode examples

Statement

Given a set of numbers find an optimal solution for a problem considering the current number and the best you can get from the left and right sides.

Approach

Find all optimal solutions for every interval and return the best possible answer.

// from i to j
dp[i][j] = dp[i][k] + result[k] + dp[k+1][j]

Get the best from the left and right sides and add a solution for the current position.

for(int l = 1; l<n; l++) {
   for(int i = 0; i<n-l; i++) {
       int j = i+l;
       for(int k = i; k<j; k++) {
           dp[i][j] = max(dp[i][j], dp[i][k] + result[k] + dp[k+1][j]);
       }
   }
}
 
return dp[0][n-1]

Notes

  • Some questions point out the number of repetitions, in that case, add one more loop to simulate every repetition.
# Title Solution Tutorial Level Remarks

27. Decision Making (Dynamic Programing)

Detailed explanations with leetcode examples

The general problem statement for this pattern is forgiven situation decide whether to use or not to use the current state. So, the problem requires you to make a decision at a current state.

Statement

Given a set of values find an answer with an option to choose or ignore the current value.

Approach

If you decide to choose the current value use the previous result where the value was ignored; vice-versa, if you decide to ignore the current value use previous result where value was used.

// i - indexing a set of values
// j - options to ignore j values
for (int i = 1; i < n; ++i) {
   for (int j = 1; j <= k; ++j) {
       dp[i][j] = max({dp[i][j], dp[i-1][j] + arr[i], dp[i-1][j-1]});
       dp[i][j-1] = max({dp[i][j-1], dp[i-1][j-1] + arr[i], arr[i]});
   }
}

198. House Robber

for (int i = 1; i < n; ++i) {
   dp[i][1] = max(dp[i-1][0] + nums[i], dp[i-1][1]);
   dp[i][0] = dp[i-1][1];
}
# Title Solution Tutorial Level Remarks
01 121. Best Time to Buy and Sell Stock Python Vid 1 Easy Fundamental
02 122. Best Time to Buy and Sell Stock II Python Video 01 Easy More like Greedy
03 123. Best Time to Buy and Sell Stock III Python Vid 1, Vid 2 Hard Fundamental
04 188. Best Time to Buy and Sell Stock IV Python Vid 1, Vid 2 Hard Getting "Memory Limit Exceeded"
05 309. Best Time to Buy and Sell Stock with Cooldown Python Must, Art0, Art1, Must 2 , Art 2, Art 3 Medium Very tricky, must check again. Couldn't solve
06 714. Best Time to Buy and Sell Stock with Transaction Fee Python Must Read , Art 2 Medium More like Greedy, but DP
07 198. House Robber Python Must, educative.io Easy A Gold Mine
08 213. House Robber II Python Art 1, Art 2 Medium ---
09 337. House Robber III Python Art 1 Medium Another gold mine, hidden greedy and DFS

28. List Iterator DS Design

Detailed explanations with leetcode examples

Statement

Given ssome kinds of nested list of of some kinds of data, implement an iterator to iterate through the give data.

Approach

An iterator shouldn't copy and modify the entire data but just iterate over the original data structure. And shuld return the data on the fly. Also there should't be any internal dependency among the methods of iterator.

Notes

  • Some questions point out the number of repetitions, in that case, add one more loop to simulate every repetition.
# Title Solution Tutorial Level Remarks
01 284. Peeking Iterator Python, Swift Art 1 Medium MUST read
02 341. Flatten Nested List Iterator Python, Swift Vid 1, Art 1, Art 2, Art 3, Art 4, Art 5 Medium TODO: Check again. Very Important. Learned new things
03 173. Binary Search Tree Iterator Python, Swift Vid 1, Art 1 Medium TODO: Check again. Very Important. Learned new things
04 281. Zigzag Iterator Python, Swift Art 1 Medium ---

Detailed explanations with leetcode examples

Statement

Read this wiki article first.

In computational geometry, a sweep line algorithm or plane sweep algorithm is an algorithmic paradigm that uses a conceptual sweep line or sweep surface to solve various problems in Euclidean space. It is one of the key techniques in computational geometry. The idea behind algorithms of this type is to imagine that a line (often a vertical line) is swept or moved across the plane, stopping at some points. Geometric operations are restricted to geometric objects that either intersect or are in the immediate vicinity of the sweep line whenever it stops, and the complete solution is available once the line has passed over all objects.

alt text

Approach

Sweep line algorithms are used in solving planar problems. The basic outline of a sweep line algorithm is as follows:

  1. Sweep a line across problem plane.

  2. As the line sweeps across the plane, events of interest occur, keep track of these events.

  3. Deal with events that occur at the line leaving a solved problem behind.

Notes

  • [To be written]

Links

  1. Sweep Line Algorithm
  2. Line Sweep Technique
  3. Lecture 1 - Sweep Line Algorithms
# Title Solution Tutorial Level Remarks
01 1272. Remove Interval Python Art 1 Medium Line Swap
02 1288. Remove Covered Intervals Python Art 1 Medium Line Swap with Greedy. A must read solution. A gold mie, learned a lot
03 1229. Meeting Scheduler Python Art 1 Medium Line Swap, learned a lot
04 850. Rectangle Area II Python Art 1, Vid 1, Art 2 Hard Line Swap using heap and Segmet Tree. TODO: Solve it using Segment Tree



References

About

All of the patterns to solve problems in coding interview which i came up while preparing for my interview

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published