LeetCode Cheat Sheet - PIRATE KING
LeetCode Cheat Sheet - PIRATE KING
ABOUT
PIRATE KING
LEETCODE
CHEAT SHEET
✔ Patterns
✔ Templates
PATTERNS
Big-O notations indicate the algorithm’s general time complexity
Input is a Matrix/Graph
String Concatenation
- Dummy Node
Privacy - Terms
Recomputing the Same Input
Recursion is Banned
- Stack
Permutations/Combinations/Subsets
- Backtracking
Common Strings
- Map
- Trie
Sort
- Two Heaps
Privacy - Terms
- Store different values in the same pointer
BLOG TECH DEALS LEETCODE FAQ
ABOUT
PIRATE KING
Maximum/Minimum Subarray/Subset/Options
- Dynamic Programming
Map/Set
- Time: O(1)
- Space: O(n)
Deque
TEMPLATES
Binary Search
O(log n)
where n = size(array)
ABOUT
3
# Else,
def
returns the index of where it should be.
binarySearch(nums: List[int], target: int) -> int:
PIRATE KING 2
3
// Else, returns the index of where it should be.
int binarySearch(int[] nums, int target) {
4 l, r = 0, len(nums) 4 int l = 0, r = nums.length;
5 while l < r : 5 while (l < r) {
6 m = (l + r) // 2; 6 int m = (l + r) / 2;
7 if nums[m] < target: 7 if (nums[m] < target) l = m + 1;
8 l = m + 1; 8 else r = m;
9 else: 9 }
10 r = m; 10 return l;
11 return l; 11 }
where n = size(tree)
Python - DFS
ABOUT
1 void preorder(TreeNode root) { 1 PIRATE KING
void inorder(TreeNode root) { 1 void postorder(TreeNode root) {
2 if (root == null) return; 2 if (root == null) return; 2 if (root == null) return;
3 System.out.print(root.val + " "); 3 inorder(root.left); 3 postorder(root.left);
4 preorder(root.left); 4 System.out.print(root.val + " "); 4 postorder(root.right);
5 preorder(root.right); 5 inorder(root.right); 5 System.out.print(root.val + " ");
6 } 6 } 6 }
Privacy - Terms
BLOG TECH DEALS LEETCODE FAQ
Matrix Traversals
PIRATE KING
ABOUT
O(n)
where n = size(grid)
1 dirs = [ [0,1], [0,-1], [1,0], [-1,0] ] 1 int[][] dirs = { {0,1}, {0,-1}, {1,0}, {-1,0} };
2
2 void bfs(char[][] grid, int _i, int _j) {
3 def bfs(grid: List[List[int]], _i: int, _j: int): 3 Deque<int[]> q = new ArrayDeque<>();
4 q = deque([[_i, _j]]) 4 boolean[][] visited = new boolean[grid.length][grid[0].le
5 visited = set([(_i, _j)]) 5 q.addLast(new int[] {_i, _j});
6 6 visited[_i][_j] = true;
7 while q: 7 while (!q.isEmpty()) {
8 cur = q.popleft() 8 int[] cur = q.removeFirst();
9
9 for (int[] dir : dirs) {
10 for dir in dirs: 10 int i = cur[0] + dir[0];
Privacy - Terms
11 i = cur[0] + dir[0] 11 int j = cur[1] + dir[1];
BLOG TECH DEALS LEETCODE
+ dir[1]FAQ
PIRATE KING
12 j = cur[1] 12 if (i < 0 || j < 0 || i >= grid.length ||
ABOUT
13 13 j >= grid[0].length || visited[i][j]) continu
14 if i < 0 or j < 0 or i >= len(grid) or \ 14 visited[i][j] = true;
15 j >= len(grid[0]) or (i, j) in visited: continue 15 q.addLast(new int[] {i, j});
16 16 }
17 visited.add((i, j)) 17 }
18 q.append([i, j]) 18 }
Graph Traversals
O(n)
where n = size(nodes)
1 def dfs(graph: Dict[int, List[int]], cur: int, visited: Set[in 1 void dfs(Map<Integer, List<Integer>> graph, int cur, Set<Integ
2 if cur in visited: return 2 if (visited.contains(cur)) return;
3 3 visited.add(cur);
4 visited.add(cur) 4 System.out.print(cur + " ");
5 print(cur, end = " "); 5 for (int next : graph.get(cur)) {
6 6 dfs(graph, next, visited);
7 for next in graph[cur]: 7 }
8 dfs(graph, next, visited) 8 }
Privacy - Terms
Python - BFS Java - BFS
BLOG TECH DEALS LEETCODE FAQ
ABOUT
1 def bfs(graph: Dict[int, List[int]], node: int): PIRATE KING 1 void bfs(Map<Integer, List<Integer>> graph, int node) {
2 q = deque([node]) 2 Deque<Integer> q = new ArrayDeque<>();
3 visited = set([node]) 3 Set<Integer> visited = new HashSet<>();
4
4 q.addLast(node);
5 while q: 5 visited.add(node);
6 cur = q.popleft() 6
String Concatenation
O(n)
where n = length(string)
ABOUT
3 out_str = "" 3 String str = "";
4 for i in range(n): 4 for (int i = 0; i < n; i++) {
5 out_str += c # O(s) where s = length(out_str) 5 str += c; // O(s) where s = length(str)
6 6 }
7 return out_str 7 return str;
8 8 }
9 # O(n) 9 // O(n)
10 def appendNtimesUsingStringJoin(c: str, n: int) -> str: 10 public void appendNtimesUsingStringBuilder(char c, int n) {
11 list = [] 11 StringBuilder sb = new StringBuilder();
12 for i in range(n): 12 for (int i = 0; i < n; i++) {
13 list.append(c); # O(1) 13 sb.append(c); // O(1)
14 14 }
15 return "".join(list) 15 return sb.toString();
16 16 }
Linked List
O(n)
where n = size(nodes)
Python Java
PIRATE KING
3 if (head == null) return;
3 if not head: return
ABOUT 4 ListNode slow = head, fast = head, dummy = new ListNode(0
4
5 // puts slow in the middle
5 slow, fast, dummy = head, head, ListNode(0, head)
6 while (fast != null && fast.next != null) {
6 # puts slow in the middle
7 slow = slow.next;
7 while fast and fast.next:
8 fast = fast.next.next;
8 slow = slow.next;
9 }
9 fast = fast.next.next;
10 // d h s f
10 # d h s f
11 // after: 0-1-2-3-4-5-6-7
11 # after: 0-1-2-3-4-5-6-7
12 }
12
Merge Sort
O(n log n)
where n = size(array)
Python Java
ABOUT
9 m = (l + r) // 2 9 msort(nums, m + 1, r);
10 i, j = l, m + 1 10 merge(nums, l, r);
11 list = [] 11 }
12 for k in range(r - l + 1): 12 void merge(int[] nums, int l, int r) {
13 if j > r or (i <= m and nums[i] < nums[j]): 13 int m = (l + r) / 2, i = l, j = m + 1;
14 list.append(nums[i]) 14 int[] arr = new int[r - l + 1];
15 i += 1 15 for (int k = 0; k < arr.length; k++) {
16 else: 16 if (j > r || (i <= m && nums[i] < nums[j])) arr[k] =
17 list.append(nums[j]) 17 else arr[k] = nums[j++];
18 j += 1 18 }
19 for k in range(len(list)): 19 for (int k = 0; k < arr.length; k++) {
20 nums[l] = list[k] 20 nums[l++] = arr[k];
21 l += 1 21 }
22 msort_helper(nums, 0, len(nums) - 1) 22 }
Quick Sort
Average: O(n log n)
Worst: O(n²)
where n = size(array)
Python Java
8 qsort(nums, p + 1, r);
9 def partition(nums: List[int], l: int, r: int) -> int:
9 }
10 pivot, p = nums[r], r
10 int partition(int[] nums, int l, int r) {
11
20 }
21 return p
21 return p;
22
22 }
23 qsort_helper(nums, 0, len(nums) - 1)
23 void swap(int[] nums, int a, int b) {
24
24 int tmp = nums[a];
25
25 nums[a] = nums[b];
26
26 nums[b] = tmp;
27
27 }
Privacy - Terms
BLOG TECH DEALS LEETCODE FAQ Quick
PIRATESelect
KING
ABOUT
Average: O(n)
Worst: O(n²)
where n = size(array)
Python Java
1 def findKthLargest(self, nums: List[int], k: int) -> int: 1 public int findKthLargest(int[] nums, int k) {
2 def qselect(nums: List[int], l: int, r: int, k: int) -> N 2 return quickSelect(nums, 0, nums.length - 1, nums.length
3 p = partition(nums, l, r) 3 }
4 4 private int quickSelect(int[] nums, int l, int r, int k) {
5 if p < k: 5 int p = partition(nums, l, r);
6 return qselect(nums, p + 1, r, k) 6 if (p < k) return quickSelect(nums, p + 1, r, k);
7 if p > k: 7 if (p > k) return quickSelect(nums, l, p - 1, k);
8 return qselect(nums, l, p - 1, k) 8 return nums[p];
9 9 }
10 return nums[p] 10 private int partition(int[] nums, int l, int r) {
11
11 int pivot = nums[r];
12 def partition(nums: List[int], l: int, r: int) -> int: 12 int p = r;
13 pivot, p = nums[r], r 13 for (int i = l; i < p; i++) {
14
14 if (nums[i] > pivot) {
15 i = l 15 swap(nums, i, p - 1);
16 while i < p: 16 swap(nums, p, p - 1);
17 if nums[i] > pivot: 17 i--;
18 nums[i], nums[p - 1] = nums[p - 1], nums[i] 18 p--;
19 nums[p], nums[p - 1] = nums[p - 1], nums[p] 19 }
20 i -= 1 20 }
21 p -= 1 21 return p;
22 22 }
23 i += 1 23 private void swap(int[] nums, int a, int b) { Privacy - Terms
24
24 int tmp = nums[a];
BLOG TECH DEALSp LEETCODE FAQ
PIRATE KING
25 return 25 nums[a] = nums[b];
ABOUT
26
26 nums[b] = tmp;
27 return qselect(nums, 0, len(nums) - 1, len(nums) - k) 27 }
Trie
O(n)
where n = length(string)
Python Java
1 class Trie {
1 class TrieNode:
2 private class TrieNode {
2 def __init__(self):
3 public boolean isWord = false
3 self.isWord = False
4 public TrieNode[] nodes = new TrieNode[26];
4 self.nodes = {}
5 }
5
6 TrieNode root = new TrieNode();
6 class Trie:
7 /** Inserts a word into the trie. */
7 def __init__(self):
8 public void insert(String word) {
8 self.root = TrieNode()
9 TrieNode cur = root;
9
Privacy - Terms
BLOG TECH DEALS LEETCODE FAQ
ABOUT
PIRATE KING
Deque
O(1)
Python
Java
Privacy - Terms
BLOG TECH DEALS LEETCODE FAQ Back to Top
ABOUT
PIRATE KING
Subscribe
Email Address
SIGN UP
Privacy Policy
Privacy - Terms