LeetCode_15_Patterns
LeetCode_15_Patterns
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
- (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];
}
}
Java:
public class PalindromeChecker {
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 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.
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:
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;
}
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
//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 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
}
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:
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:
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
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]]
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
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 postorder_traversal(self,node):
If node:
Self.postorder_traversal(node.left)
self.postorder_traversal(node.right)
print(node.val, end = ‘’)
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 = ‘’)
While stack:
Vertex = stack.pop()
If vertex not in visited:
Visited.add(vertex)
Print(vertex, end= ‘’)
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
Code
Python
Def bfs(self,start):
Visited = set()
Queue = dequeue([start]) #add the starting node to the queue
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
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
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