NeetCode 150

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Top K Frequent Elements

Arrays & Hashing Count frequencies with HashMap, then insert into a Priority Queue with custom comparator Queue<Integer> pq = new PriorityQueue<>( (a,b) -> freq.get(b) - freq.get(a)); Add keys from keySet() into the queue

N-Queens The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.

Backtracking HashSet<Integer> column = new HashSet<>(); HashSet<Integer> upDiagonal = new HashSet<>(); HashSet<Integer> downDiagonal = new HashSet<>(); char[][] board = new char[n][n]; if (row >= n) { addresult } for (int i = 0; i < n; i++) { if (!column.contains(i) && !upDiagonal.contains(row+i) && !downDiagonal.contains(row-i)) { board[row][i] = 'Q'; column.add(i); upDiagonal.add(row+i); downDiagonal.add(row-i); dfs(n, result, board, column, upDiagonal, downDiagonal, row+1); board[row][i] = '.'; column.remove(i); upDiagonal.remove(row+i); downDiagonal.remove(row-i); } }

Letter Combinations of a Phone Number Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters

Backtracking String[] mapping = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; public void dfs(String digits, List<String> result, String[] mappings, StringBuilder sb, int index) { if (index >= digits.length()) { result.add(sb.toString()); return; } String curr = mappings[digits.charAt(index)-'0']; for (int i = 0; i < curr.length(); i++) { sb.append(curr.charAt(i)); dfs(digits, result, mappings, sb, index+1); sb.deleteCharAt(sb.length()-1); } }

Subsets Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.

Backtracking if (i == nums.length) { result.add(new ArrayList<Integer>(current)); return; } dfs(result, current, nums, i+1); current.add(nums[i]); dfs(result, current, nums, i+1); current.remove(current.size()-1);

Combination Sum Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

Backtracking if (i >= candidates.length || target<0) { return; } if (target==0) { result.add(new ArrayList<Integer>(curr)); return; } //2 paths: we use nums[i], we don't use nums[i] curr.add(candidates[i]); dfs(candidates, target-candidates[i], result, curr, i); curr.remove(curr.size()-1); dfs(candidates, target, result, curr, i+1);

Permutations Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Backtracking if (index == curr.size()) { result.add(new ArrayList<Integer>(curr)); return; } for (int i = index; i < curr.size(); i++) { Collections.swap(curr, index, i); dfs(result, curr, index+1); Collections.swap(curr, index, i); }

Word Search Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Backtracking if (index == word.length()) { return true; } if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || visited[i][j] || board[i][j]!=word.charAt(index)) { return false; } visited[i][j] = true; if (search(board, word, i+1, j, visited, index+1) || search(board, word, i-1, j, visited, index+1) || search(board, word, i, j+1, visited, index+1) || search(board, word, i, j-1, visited, index+1)) { return true; } visited[i][j] = false; return false;

Palindrome Partitioning Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. A palindrome string is a string that reads the same backward as forward.

Backtracking void dfs(int start, List<List<String>> result, List<String> currentList, String s) { if (start >= s.length()) result.add(new ArrayList<String>(currentList)); for (int end = start; end < s.length(); end++) { if (isPalindrome(s, start, end)) { // add current substring in the currentList currentList.add(s.substring(start, end + 1)); dfs(end + 1, result, currentList, s); // backtrack and remove the current substring from currentList currentList.remove(currentList.size() - 1); } } }

Subsets II Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.

Backtracking, avoid duplicates if (index == nums.length) { result.add(new ArrayList<Integer>(curr)); return; } curr.add(nums[index]); dfs(nums, result, curr, index+1); curr.remove(curr.size()-1); while (index+1 < nums.length && nums[index] == nums[index+1]) { index++; } dfs(nums, result, curr, index+1);

Combination Sum II Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations.

Backtracking, avoid duplicates if (target == 0) { result.add(new ArrayList<Integer>(curr)); return; } if (target < 0) { return; } int prev = -1; for (int i = index; i < candidates.length; i++) { if (candidates[i] == prev) { continue; } curr.add(candidates[i]); dfs(candidates, target - candidates[i], result, curr, i+1); curr.remove(curr.size()-1); prev = candidates[i]; }

Maximum Product Subarray

DP for (int i = 1; i < nums.length; i++) { int curr = nums[i]; int temp_max = Math.max(curr, Math.max(max_so_far * curr, min_so_far * curr)); min_so_far = Math.min(curr, Math.min(max_so_far * curr, min_so_far * curr)); max_so_far = temp_max; result = Math.max(max_so_far, result); }

Longest Increasing Subsequence Given an integer array nums, return the length of the longest strictly increasing subsequence.

DP for (int i = nums.length-1; i >= 0; i--) { for (int j = i+1; j < nums.length; j++) { if (nums[i] < nums[j]) { dp[i] = Math.max(dp[i], dp[j]+1); longest = Math.max(longest, dp[i]); } } }

Word Break Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation.

DP if (index >= s.length()) { return true; } if (memo[index] != null) { return memo[index]; } for (int i = index+1; i <= s.length(); i++) { if (dict.contains(s.substring(index, i)) && isValid(s, dict, memo, i)) { return memo[index] = true; } } return memo[index] = false;

Partition Equal Subset Sum Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

DP, Knapsack Problem // Base Cases if (subSetSum == 0) return true; if (n == 0 || subSetSum < 0) return false; // check if subSetSum for given n is already computed and stored in memo if (memo[n][subSetSum] != null) return memo[n][subSetSum]; boolean result = dfs(nums, n - 1, subSetSum - nums[n - 1], memo) || dfs(nums, n - 1, subSetSum, memo); // store the result in memo memo[n][subSetSum] = result; return result;

Course Schedule II There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.

Graph, DFS, Topological Sort, Kahn's Algorithm Same as course schedule, detect cycle DFS but add the node to the ordering if there is no prerequisite. Kahn's Algorithm: for each node in Nodes indegree[node] = 0; for each edge(src, dest) in Edges indegree[dest]++ Algorithm: Steps involved in finding the topological ordering of a DAG: Step-1: Compute in-degree (number of incoming edges) for each of the vertex present in the DAG and initialize the count of visited nodes as 0. Step-2: Pick all the vertices with in-degree as 0 and add them into a queue (Enqueue operation) Step-3: Remove a vertex from the queue (Dequeue operation) and then. Increment the count of visited nodes by 1. Decrease in-degree by 1 for all its neighbouring nodes. If the in-degree of neighbouring nodes is reduced to zero, then add it to the queue. Step 4: Repeat Step 3 until the queue is empty. Step 5: If the count of visited nodes is not equal to the number of nodes in the graph then the topological sort is not possible for the given graph.

Course Schedule There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. Return true if you can finish all courses. Otherwise, return false.

Graph, Topological Ordering Brute force: backtracking Optimized: set the Prereqs HashMap to empty at the end. Create graph HashMap<Integer, List<Integer>> if (visited[course]) { return true; } if (prereqs.get(course).size() == 0) { return false; } visited[course] = true; for (int i = 0; i < prereqs.get(course).size(); i++) { if (containsCycle(prereqs.get(course).get(i), prereqs, visited)) { return true; } } prereqs.put(course, new ArrayList<Integer>()); visited[course] = false; return false;

Clone Graph Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. class Node { public int val; public List<Node> neighbors; }

Graphs, DFS public Node cloneGraph(Node node) { if (node == null) { return node; } if (visited.containsKey(node)) { return visited.get(node); } Node cloneNode = new Node(node.val, new ArrayList()); visited.put(node, cloneNode); for (Node neighbor: node.neighbors) { cloneNode.neighbors.add(cloneGraph(neighbor)); } return cloneNode; }


Ensembles d'études connexes

12, 13 and 14 Lecture Assignment

View Set

NCLEX -silversteri -physiological integrity first 100 qs

View Set

Chapter 2, Section 2: Chemical Bonds

View Set