0% found this document useful (0 votes)
13 views

LeetCode_15_Patterns

The document outlines common algorithms and patterns used in LeetCode problems, serving as tools to assist in problem-solving. It includes sections on various techniques such as Prefix Sum, Two Pointers, Sliding Window, and more, each accompanied by code examples and problem descriptions. The document emphasizes that these patterns may need to be modified to fit specific problems.

Uploaded by

jlinreborn000
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

LeetCode_15_Patterns

The document outlines common algorithms and patterns used in LeetCode problems, serving as tools to assist in problem-solving. It includes sections on various techniques such as Prefix Sum, Two Pointers, Sliding Window, and more, each accompanied by code examples and problem descriptions. The document emphasizes that these patterns may need to be modified to fit specific problems.

Uploaded by

jlinreborn000
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

LeetCode 15 Patterns

These are common algorithms found in LeetCode problems.


These are TOOLS to HELP you solve the LeetCode problems.
These are NOT 100% specific to your LeetCode problem.
You will have to MODIFY them to solve the LeetCode problems.

Contents
1) Prefix Sum:........................................................................................................................................................ 4
Code.................................................................................................................................................................. 4
Problems........................................................................................................................................................... 4
303e Range Sum Query – Immutable:...........................................................................................................4
525m contiguous Array..................................................................................................................................5
560m Subarray Sum equals K........................................................................................................................ 5
2) Two Pointers...................................................................................................................................................... 6
Code.................................................................................................................................................................. 6
Problems........................................................................................................................................................... 7
167m Two Sum II - Input Array Is Sorted....................................................................................................... 7
15m............................................................................................................................................................... 8
11m............................................................................................................................................................... 8
3) Sliding Window.................................................................................................................................................. 9
Code.................................................................................................................................................................. 9
Python........................................................................................................................................................... 9
Java................................................................................................................................................................ 9
Problems......................................................................................................................................................... 10
643e Maximum Average Subarray I.............................................................................................................10
3m............................................................................................................................................................... 11
76h.............................................................................................................................................................. 11
4) Fast and Slow Pointers.....................................................................................................................................12
Problems......................................................................................................................................................... 12
141e Linked List Cycle.................................................................................................................................. 12
202e............................................................................................................................................................. 13
287m........................................................................................................................................................... 13
5) Linked List In-Place Reversal............................................................................................................................ 14
Code................................................................................................................................................................ 14
Python......................................................................................................................................................... 14
Java.............................................................................................................................................................. 14
Problems......................................................................................................................................................... 14
24m............................................................................................................................................................. 14
206e............................................................................................................................................................. 14
92m............................................................................................................................................................. 14
6) Monotonic Stack............................................................................................................................................. 15
Code................................................................................................................................................................ 15
Python......................................................................................................................................................... 15
Problems......................................................................................................................................................... 15
496e............................................................................................................................................................. 15
739m........................................................................................................................................................... 15
84h.............................................................................................................................................................. 15
7) Top K elements problem..................................................................................................................................16
Problems......................................................................................................................................................... 16
215m........................................................................................................................................................... 16
347m........................................................................................................................................................... 16
373m........................................................................................................................................................... 16
8) Overlapping Intervals...................................................................................................................................... 17
Problems......................................................................................................................................................... 17
56m............................................................................................................................................................. 17
57m............................................................................................................................................................. 17
435m........................................................................................................................................................... 17
9) Modified Binary Search Pattern.......................................................................................................................18
Code:............................................................................................................................................................... 18
Python......................................................................................................................................................... 18
Problems:........................................................................................................................................................ 18
10) Binary Tree Traversal..................................................................................................................................... 19
Code................................................................................................................................................................ 19
Python......................................................................................................................................................... 19
Problems......................................................................................................................................................... 20
Pre Order..................................................................................................................................................... 20
257e............................................................................................................................................................. 20
In Order....................................................................................................................................................... 20
230m........................................................................................................................................................... 20
Post Order................................................................................................................................................... 20
124h............................................................................................................................................................ 20
Level order................................................................................................................................................... 20
107m........................................................................................................................................................... 20
11) Depth First Search (DFS)................................................................................................................................ 21
Code................................................................................................................................................................ 21
Python......................................................................................................................................................... 21
Problems......................................................................................................................................................... 22
133m........................................................................................................................................................... 22
113m........................................................................................................................................................... 22
210m........................................................................................................................................................... 22
12) Breadth-First Search (BFS)............................................................................................................................. 23
Code................................................................................................................................................................ 23
Python......................................................................................................................................................... 23
Problems......................................................................................................................................................... 23
102m........................................................................................................................................................... 23
994m........................................................................................................................................................... 23
127h............................................................................................................................................................ 23
13) Matrix Traversal............................................................................................................................................. 24
Problems......................................................................................................................................................... 24
733e............................................................................................................................................................. 24
200m........................................................................................................................................................... 24
130m........................................................................................................................................................... 24
14. Backtracking.................................................................................................................................................. 25
Problems......................................................................................................................................................... 25
46m............................................................................................................................................................. 25
78m............................................................................................................................................................. 25
51h.............................................................................................................................................................. 25
15. Dynamic Programming.................................................................................................................................. 26
Problems......................................................................................................................................................... 26
70e............................................................................................................................................................... 26
300m........................................................................................................................................................... 26
322m........................................................................................................................................................... 26
416m........................................................................................................................................................... 26
1143m......................................................................................................................................................... 26
312h............................................................................................................................................................ 26

1) Prefix Sum:
Common problems:
- Query sum of elements in a subarray

Code
Python:
def create_prefix_sum(arr):
for i in range(1, len(arr)):
arr[i] += arr[i - 1]
return arr

Java:
public static int[] createPrefixSum(int[] arr) {
for (int i = 1; i < arr.length; i++) {
arr[i] += arr[i - 1];
}
return arr;
}

Problems
303e Range Sum Query – Immutable

Given an integer array nums, handle multiple queries of the following type:

Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.
Implement the NumArray class:
- NumArray(int[] nums) Initializes the object with the integer array nums.
- int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and
right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).

Example 1:

Input:
["NumArray", "sumRange", "sumRange", "sumRange"]
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
Output:
[null, 1, -1, -3]

Explanation:
NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1
numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1
numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3

Solution:
1. We have to initialize the nums array
2. Create the preSum array using the nums array

We can use the PreSums Pattern


This will create this array
[-2, -2, 1, -4, -2, -3]
So SumRange from
- (0, 2): we need to get 1
1 is in the newArray [2], meaning newArray[rightRange].
We can give the answer as:
if leftRange = 0, then answer is newArray[rightRange] ------------------

- (2, 5): We need to get -1


Without changing anything we have
newArray[rightRange] - newArray[leftRange-1] -------------
-3 – (-2) = -1

- (0, 5): -3
If we use the same process as above
if leftRange = 0, then answer is newArray[rightRange]
This will give us -3

FINAL CODE:
class NumArray {
int preSumArr[];
public NumArray(int[] nums) {
preSumArr = nums;
for (int i=1;i<preSumArr.length;i++){
preSumArr[i]+=preSumArr[i-1];
}
}

public int sumRange(int left, int right) {


int sum = 0;
if (left == 0){
sum = preSumArr[right];
} else {
sum = preSumArr[right] - preSumArr[left-1];
}
return sum;
}
}

525m contiguous Array


560m Subarray Sum equals K
2) Two Pointers
Given a string and check if it is a palindrome
Running time to O(n)
Code
Python:
Def is_palindrome(string):
Start = 0
End = len(string) -1

While start < end:


If string[start] != string [end]:
Return false
Start += 1
End -= 1
Return True

Java:
public class PalindromeChecker {

public static boolean isPalindrome(String str) {


int start = 0; //arrays index starts from 0
int end = str.length() - 1; //arrays start from 0. Need -1 from array length to get true array size

while (start < end) { //while start pointer is less than end. Before they meet
if (str.charAt(start) != str.charAt(end)) { // check if endpointer and startpointer are the same
return false; //if they are not then the string is not a palindrome
}
start++; //move start pointer closer to the center
end--; // move end pointer closer to the center
}

return true; //return true meaning the string is a palindrome


}

public static void main(String[] args) {


String testString = "radar";
boolean result = isPalindrome(testString);

System.out.println("Is the string \"" + testString + "\" a palindrome? " + result);


}
}
Problems
167m Two Sum II - Input Array Is Sorted
Description:
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers
such that they add up to a specific target number. Let these two numbers be numbers[index1] and
numbers[index2] where 1 <= index1 < index2 <= numbers.length.

Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2]
of length 2.

The tests are generated such that there is exactly one solution. You may not use the same element twice.

Your solution must use only constant extra space.

Example 1:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
Example 2:
Input: numbers = [2,3,4], target = 6
Output: [1,3]
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
Example 3:
Input: numbers = [-1,0], target = -1
Output: [1,2]
Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].

Constraints:
 2 <= numbers.length <= 3 * 104
 -1000 <= numbers[i] <= 1000
 numbers is sorted in non-decreasing order.
 -1000 <= target <= 1000
 The tests are generated such that there is exactly one solution.

Solution:

Using the 2 pointer method:


One pointer will move from the start of the array and another will move from the end of the array
- startPointer
- endPointer
1-D Array will be given
Elements of the array are in NON-DECREASING ORDER meaning [1,2,3,4]
We must find the sum of a specific number by adding 2 elements from the array
Eg) Sum: 7
We have 3 and 4.
The index for 3 and 4 is 2 and 3. However we have to add those index by ONE according to the description.

class Solution {
public int[] twoSum(int[] numbers, int target) {
int testArray[]=numbers; //not needed but using it for practice java coding
int ans[] = new Int[2]; //creating this array to store and return the answer

int startPointer = 0;
int endPointer = testArray.length -1; // using -1 because array index starts from 0 instead of 1.
Because array.length give you the true length of any array. Need array.length-1 to get the correct indices

For (int I = 0; i<testArray.length; i++){ //can also use “while (startPointer < endPointer)”.
int testSum = testArray.length[startPointer] + testArray[endPointer]; // add together the
elements from the elements based on the indices
if (testSum == target){ //if sum = target then return the answer
Ans[0] = startPointer +1; //adding +1 bc of rules above
Ans[1] = endPointer +1; //adding +1 bc of rules above
return ans;
}

If (testSum > targest){ //meaning the testSum is too big


endPointer --; //move endPointer closer to smaller elements
} else
startPointer ++;
}
Return ans; // this will return [0,0]
}
}

15m
11m
3) Sliding Window
Helps us find subarrays / sub strings that meets a specific criterion
Eg)
Find subarray of size ‘K’ with maximum sum
K=3.
Array = [3,2,7,5,9,6,2]
1st iteration
Window_sum=3+2+7=12
Max_sum=12
2nd iteration
window_sum=12-3+5=14
max_Sum=14

Code
Python
Def max_subarray_sum_sliding_window(arr, k):
N = len(arr)
Window_sum = sum(arr:k)
Max_sum = window_sum
Max_start_index = 0
For I in range(n-k):
Window_sum = window_sum – arr[i] + arr[I +k]
If window_sum > max_sum;
Max_sum = window_sum
Max_start_index = i+1
Return arr[max_start_index:max_start_index+k], max_sum

Java

public static double findMaxAverage(int[] nums, int k) {


//find the currentSum of length k = 4
double currentSum = 0; //storing the calculated sum of the sliding window
double newSum = 0; //storing only the max Sum

//the for loop calculates the elements from 0 to k-1.


//This is done first to get the sum of the 1st iteration of the sliding window technique
for (int i = 0; i < k; i++){
currentSum += nums[i]; //Add the elements from 0 to k-1
}

newSum = currentSum; //store the sum in newSum

//This for loop start by using the sum from the above for loop to subtract from the element of index 0 and
adding the index 4. Saving this new value to currentSum
//then the next iteration is subtracting the eleindex of 0+=1 and adding index of k+1
//stops until j < nums.length
for (int j = k; j < nums.length; j++){
currentSum = currentSum - nums[j-k] + nums[j];
System.out.println(currentSum + " - " + nums[j-k] + " + " + nums[j]);
if (currentSum > newSum ){
newSum = currentSum;
}
}
return newSum;
}

Problems
643e Maximum Average Subarray I
You are given an integer array nums consisting of n elements, and an integer k.
Find a contiguous subarray whose length is equal to k that has the maximum average value and return this
value. Any answer with a calculation error less than 10-5 will be accepted.

Example 1:
Input: nums = [1,12,-5,-6,50,3], k = 4
Output: 12.75000
Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
Example 2:
Input: nums = [5], k = 1
Output: 5.00000

Constraints:
 n == nums.length
 1 <= k <= n <= 105
 -104 <= nums[i] <= 104

Solution:
Using the Sliding window technique:
We need a temp variable to store the sum and newSum to compare which one is greater:
- newSum
- sum
We need to calculate the sum of the array’s elements of length k.
The total of the first 4 elements:
1 + 12 + -5 + -6 = 2

For (int I =0; I < k; i++){


Sum = array[i];
};

Then we need to “slide” by doing:


Sum = sum – array[j-k] + array[j]

public double findMaxAverage(int[] nums, int k) {


double currentSum = 0; //temp to hold sum of elements
double newSum = 0; //temp to hold MAX sum of elements
for(int I=0; I < k; i++){ // get the sum of elements of array length k
currentSum = nums[i]; //save it to the currentSum
}

newSum = currentSum; //save it to the newSum from currentSum

for(int j=0; j < nums.length; j++){ //need to traverse to the next set of elements by “Sliding”
if (currentSum > newSum){ //if the currentSum is greater than the newSum
newSum = currentSum; //then overwrite newSum with the new total
}
currentSum = currentSum – array [j-k] + array[j]; //slide the k length array
}

Return newSum/k; //return only the average of the max sum


}

3m
76h
4) Fast and Slow Pointers
Involves in finding cycles
Moving two pointers at different speeds
Check if linked list is a cycle
Find middle node of a linked list
- When the fast pointer reaches the end, the slow pointer will be at the middle node of the list

Problems
141e Linked List Cycle
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously
following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is
connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.

Example 1:

Input: head = [3,2,0,-4], pos = 1


Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Example 2:

Input: head = [1,2], pos = 0


Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
Example 3:

Input: head = [1], pos = -1


Output: false
Explanation: There is no cycle in the linked list.

Constraints:
 The number of the nodes in the list is in the range [0, 104].
 -105 <= Node.val <= 105
 pos is -1 or a valid index in the linked-list.

Follow up: Can you solve it using O(1) (i.e. constant) memory?
Solution:
This is similar to a LinkedList or Doubly LinkedList:

We are checking if the LinkedList is a cycle meaning:


if one of the node’s point to an existing node in the LinkedList.
For example:
Node D’s next pointer points to node A instead of Null
If it does then it is a cycle, else it is not a cycle

First we check that the head we are given is not null


Head != null && head.next != null

We want to traverse the LinkedList by moving with two pointers.


- Slow Pointer
- Fast Pointer, this will be ahead of slow pointer by 2 nodes
If slowPointer == fastPointer then it is a cycle.

Public Boolean hasCycle(ListNode head){


ListNode slow = head; //set the slow pointer to the head of the node
ListNode fast = head; //set the fast pointer to the head of the node

while(fast != null && fast.next != null){ //while fast pointer and next fast pointer is not null
fast = fast.next.next; // move fast pointer ahead by two
slow = slow.next; // move slow pointer ahead by one
if(fast == slow){ // if fast pointer catches up to slow pointer meaning
return true; // fast pointer and slow pointer are pointing to the same node
} // return true
}
Return false; //otherwise LinkedList is not a cycle
}

202e
287m
5) Linked List In-Place Reversal
Use 3 pointers to reverse the linked list order
Use this technique to rearrange the links between nodes of a linked list
Eg)
1,3,5,7,9
st
1 iteration
Set pre=null
Current = head
Use while loop until current = null
Next = current.next
2nd iteration
Next = current.next
Set prev = current
Current = next

Code
Python
Def reverse_linked_list(head)
Prev = none
Current = head
While current is not None:
Next = current.next
Current.next = prev
Pre = current
Current = next
Return pre
Java

public ListNode swapPairs(ListNode head) {


ListNode prev = null; //define a ListNode prev to point to null
ListNode current = head; //define a ListNode current and set the current to point to head
while (current != null){ //while current is not null
//point next to the next element
ListNode Next = current.next; //define a new node containing the current.next pointer
current.next = prev; //set the current.next pointer to prev node
prev = current; //set current node to prev node
current = Next; //set Next node to current node
}
return prev;
}

Problems
24m
206e
92m
6) Monotonic Stack
Use to find the next greater or the next smaller element in an array
Eg)
For find the next greater element:
Given an array, find the next greater element for each item. If there isn’t one, output -1
create an array of the same length
for each element
check if it is greater than the element at the top of the stack
if it is pop from the stack and set the result for that index to the current element
push the current element on to the stack
for finding the next smaller element:
keep them in increasing order

Code
Python
Def next_greater_element(arr):
N = len(arr)
Stack = []
Result = [-1] * n
For I in range(n):
While stack and arr[i] > arr[stack[-1]]:
Result[stack.pop()] = arr[i]

Stack.append(i)
Return result

Problems
496e
739m
84h
7) Top K elements problem
Finding the k largest/smallest/most frequent in a data set
K largest -> use min-heap
K smallest -> use max-heap

Eg)
Finding the 3 largest element in an array
[1,5,11,9,7,2]
Use Min-Heap
Start by putting the 1st 3 largest elements in a min-heap
After that for every element we compare it with the top heap element
If the current array element is bigger, pop the top heap element and
push the new element onto the heap
in the end the heap will contain the 3 largest elements in an array

Problems
215m
347m
373m
8) Overlapping Intervals
Involves intervals or ranges that may overlap
Eg)
- Merging intervals
[[1,3],[2,6],[8,10],[15,18]] -> [[1,6],[8,10],[15,18]]
- Interval intersection
Combine [[0,2],[5,10],[13,23],[24,25]] and [[1,5],[8,12],[15,24],[25,26]] together:
[[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
- Insert Interval
Add [4,8] into existing interval [[1,2],[3,5],[6,7],[8,10],[12,16]]:
[[1,2],[3,10],[12,16]]

Finding the minimum meeting rooms or merge all overlapping intervals


[[2,6],[1,3],[8,10],[15,18]]
Start by sorting the intervals by their start times
[[1,3],[2,6],[8,10],[15,18]]
Iterate through the sorted interval and
check if it overlaps with the last interval in the merged list
if it does, merge the intervals by updating the end time of the last interval in merged
if it does not over lap, add the current interval to the merged list
Merged = [[1,3]]

Problems
56m
57m
435m
9) Modified Binary Search Pattern
Used to solve problems where the array is not sorted:
Searching in a nearly sorted array
Searching in a rotated sorted array
Searching in a list with unknown length
Searching in an array with Duplicates
Find the first/last occurrence of an element
Finding the square root of a number
Finding a peak element

Code:
Python
Def search_rotated_array(nums, target):
Left,right = 0, len(nums)-1

While left <=right


Mid = (left + right)//2
If nums[mid] == target:
Return mid
If nums[left] <= nums[mid]: #additional check to determine which half of the array sorted)
If nums[left] <= target < nums[mid] #then we check if the target is w/in the range of the
sorted half
Right = mid -1 #if it is within the sorted half, then we search this half)
Else:
Left = mid +1 #otherwise we search the other half)
Else:
If nums[mid] < target <= nums[right]:
Left = mid+1
Else:
Right = mid – 1
Return -1

Problems:
33m
153m
240m
10) Binary Tree Traversal
Determine which traversal order is the best:
PreOrder: root -> left -> right
- Create copy of a tree/serialization
InOrder: left -> root -> right
- To retrieve the values of bst in sorted order
PostOrder: left -> right -> root
- When you want to process child nodes before the parent
LevelOrder: Level by level
- When you want to explore all nodes at current level before next

Code
Python
Def preorder_traversal(self,node):
If node:
Print(node.val, end = ‘’)
self.preorder_traversal(node.left)
self.preorder_traversal(node.right)

Def inorder_traversal(self, node):


If node:
Self.inorder_traversal(node.left)
Print(node.val, end= ‘’)
Self.inorder_traversal(node.right)

Def postorder_traversal(self,node):
If node:
Self.postorder_traversal(node.left)
self.postorder_traversal(node.right)
print(node.val, end = ‘’)

Level Order Traversal


Uses queues
From collections import dequeue
Def levelOrder_traversal(root):
If not root:
Return[]
Result = []
Queue = dequeue([root])
While queue:
Level_size = len(queue)
Current_level = []
For _ in range (level_size):
Node = queue.popleft()
Current_level.append(node.val)
If node.left:
Queue.append(node.left)
If node.right:
Queue.append(node.right)
Result.append(current_level)
Return result

Problems
Pre Order
257e
In Order
230m
Post Order
124h
Level order
107m
11) Depth First Search (DFS)
Used to explore all paths of graphs or trees to solve problems like:
- Finding a path btw 2 nodes
- Checking if a graph contains a cycle
- Finding a topological order in a directed acyclic graph
- Counting the num of connected components in a graph

Code
Python
Recursive method:
Def dfs_recursive(self, v, visited):
Visited.add(v)
Print(v, end = ‘’)

For neighbor in self.graph[v]:


If neighbor not in visted:
Self.dfs_recursive(neighbor, visited)
Iterative method:
Def dfs_iterative(self,v):
Visited = set()
Stack = [v]

While stack:
Vertex = stack.pop()
If vertex not in visited:
Visited.add(vertex)
Print(vertex, end= ‘’)

For neighbor in revered(self.graph[vertex]):


If neighbor not in visited:
Stack.append(neighbor)

Generic Approach:
Def dfs_recursive(self, v, visited):
Visited.add(v) #keep track of visited nodes to avoid cycles
Print(v, end = ‘’) #perform the required operations on the current node

For neighbor in self.graph[v]:


If neighbor not in visted: # explore unvisited neighbors
Self.dfs_recursive(neighbor, visited) #continue until all required nodes are visited
Visited = set() #keep track of visited nodes
Dfs_resursive(1, visited) #choose a starting point
Problems
133m
113m
210m
12) Breadth-First Search (BFS)
Useful in
- Finding the shorted path btw 2 nodes
- Printing all nodes of a tree level by level
- Finding all connected components in a graph
- Finding the shorted transformation sequence from one word to another

Code
Python
Def bfs(self,start):
Visited = set()
Queue = dequeue([start]) #add the starting node to the queue

Visited.add(start) #setup visited set or array to track processed nodes

While queue: #continue while the queue is not empty. Continue until queue is empty
Vertex = queue.popleft() #dequeue a node
Print(vertex, end = ‘’) #process a node

For neighbor in self.graph[vertex]


If neighbor not in visited:
Visited.add(neighbor) #add process nodes to the visited set/array
Queue.append(neighbor) #enqueue unvisited neighbors

Problems
102m
994m
127h
13) Matrix Traversal
2d array where nodes are cells from
where you can reach to adjacent cells horizontally, vertically, or diagonally
depending on the problem
you can use the same algorithms in DFS and BFS to solve it
- Finding the shortest path in a grid
- Island count problem
o 1 is land and 0 is water
o Need to return the number of islands
o Can use dfs or bfs to solve the problem
 DFS
Def count_islands(grid):
If not grid or not grid[0]:
Return 0
Rows, cols = len(grid), len(grid[0])
Islands = 0

Def dfs(I,j);
If I < 0 or I >= rows or j < 0 or j >=cols or grid[i][j] != ‘1’:
Return
# Marked as Visited
Grid[i][j] = ‘0’ #4.Marking all connected land cells as visited

dfs(i+1,j) #down
dfs(i-1,j) #up
dfs(i,j+1) #right
dfs(i,j-1) #left

for I in range(rows): #1. iterate through each cell in the grid


for j in range(cols): #6. Continue until we checked all cells
if grid[i][j] == ‘1’: #2. if we find a land cell, we found a new island
dfs(i,j) #3.explore this island using DFS
islands += 1 #5.increment our island count
return islands

Problems
733e
200m
130m
14. Backtracking
Solve problems:
Involving all potential solution paths and backtracking the paths that do not lead to a valid solution
Eg)
- Generate all possible permutations combinations of a given set of elements
[1,2,3] ->
Permutations:
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Combinations:
[[],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]
- Solve puzzles like sudoku or n-queens problem
- Find all possible paths from start to end in a graph or a maze
- Generate all valid parentheses of a given length
N = 6 ->
[“((()))”, “(()())”, “(())()”, “()(())”, “()()()”]

Problems
46m
78m
51h
15. Dynamic Programming
Solving optimization problems by breaking them down into smaller sub-problems and storing their solutions to
avoid repetitive work
Eg)
- Overlapping subproblems
- Optimal substructure
- Maximize/minimize a certain value
- Count number of ways to achieve a certain goal
Common patterns to help:
- Fibonacci numbers
- 0/1 Knapsack
- Longest common sequence (LCS)
- Longest Increasing Sequence (LIS)
- Subset Sum
- Matrix Chain Multiplication

Problems
70e
300m
322m
416m
1143m
312h

You might also like