LeetCode2

¡Supera tus tareas y exámenes ahora con Quizwiz!

779. K-th Symbol in Grammar We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10. For example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110. Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows. Input: n = 2, k = 2 Output: 1 Explanation: row 1: 0 row 2: 01

0 => 01, 1 => 10, means that if index is even in next row, the number is the same as parent index. If index in odd in next row, the number is opposite as parent index. parent index is current index // 2 in the previous row. Use dfs to trace back

Image Matching p1. p2 0,0,0,0. 0,0,0,0 1, 1, 1, 1. 1, 1, 1, 1 1, 0,0,0. 1, 0,0,1 0,0,0, 1. 0,0,0,1 p1 have only one matching images because of the lower right corner 1. Write an algorithm to check how many images p1 and p2 are matched

1. 先把所有不一样的spot标记成2 p1. p2 0,0,0,0. 0,0,0,0 1, 1, 1, 1. 1, 1, 1, 1 1, 0,0,2. 1, 0,0,2 0,0,0,0. 0,0,0,0 2. 然后loop thru 每一个cell 1 用dfs,如果遇到2就return false,用一个global的seen set,遇到过的cell就不用再visit了。

1129. Shortest Path with Alternating Colors You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays redEdges and blueEdges where: redEdges[i] = [ai, bi] indicates that there is a directed red edge from node ai to node bi in the graph, and blueEdges[j] = [uj, vj] indicates that there is a directed blue edge from node uj to node vj in the graph. Return an array answer of length n, where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist. Input: n = 3, redEdges = [[0,1],[1,2]], blueEdges = [] Output: [0,1,-1]

BFS

317. Shortest Distance from All Buildings You are given an m x n grid grid of values 0, 1, or 2, where: each 0 marks an empty land that you can pass by freely, each 1 marks a building that you cannot pass through, and each 2 marks an obstacle that you cannot pass through. You want to build a house on an empty land that reaches all buildings in the shortest total travel distance. You can only move up, down, left, and right. Return the shortest travel distance for such a house. If it is not possible to build such a house according to the above rules, return -1. The total travel distance is the sum of the distances between the houses of the friends and the meeting point. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|. Input: grid = [[1,0,2,0,1], [0,0,0,0,0], [0,0,1,0,0]] Output: 7 Explanation: Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2). The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7.

BFS Use hit to record how many times a 0 grid has been reached and use distSum to record the sum of distance from all 1 grids to this 0 grid. A powerful pruning is that during the BFS we use count1 to count how many 1 grids we reached. If count1 < buildings then we know not all 1 grids are connected are we can return -1 immediately, which greatly improved speed (beat 100% submissions).

1339. Maximum Product of Splitted Binary Tree Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7. Note that you need to maximize the answer before taking the mod and not after taking it. Input: root = [1,2,3,4,5,6] Output: 110 Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)

DFS

1029. Two City Scheduling A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti. Return the minimum cost to fly every person to a city such that exactly n people arrive in each city. Input: costs = [[10,20],[30,200],[400,50],[30,20]] Output: 110 Explanation: The first person goes to city A for a cost of 10. The second person goes to city A for a cost of 30. The third person goes to city B for a cost of 50. The fourth person goes to city B for a cost of 20. The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.

DFS + Memo

689. Maximum Sum of 3 Non-Overlapping Subarrays Given an integer array nums and an integer k, find three non-overlapping subarrays of length k with maximum sum and return them. Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one. Input: nums = [1,2,1,2,6,7,5,1], k = 2 Output: [0,3,5] Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5]. We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.

DFS + Memo dfs 的parameter是 index 和 times (目前take过的range的次数) 每一轮,查看是否take 当前index的range, 注意,如果take 的话那下一轮的index就是index+k, 如果不take的话就是index+1 注意比较taken 和not taken的时候,需要让taken 的max sum大于等于 not taken的max sum。why? 因为"If there are multiple answers, return the lexicographically smallest one."。 相当于如果有相等的情况,越早taken越好 每一轮,返回一个tuple (maximum sum, array of taken 过的index).

Currency Exchange Input: currencies = ["USD","CAD","EUR","CNY"]t able = [[1,1.3,1,6.49],[0.72,1,0.9,5.5],[1.1,1.1,1,7.3],[0.18,0.2,0.136,1]] Source: "USD" Target: "CNY" table is a 2D array that represents the currency rate between currency. e.x 1 USD = 6.49 * 1 CNY Find the max amount that source currency can be exchanged to the target currency. Each currency can only be exchanged once

DFS + Memo memo 的key是(index, status) status 是一个binary 的数每一个digit代表一个currency是否被用过

1387. Sort Integers by The Power Value The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps: if x is even then x = x / 2 if x is odd then x = 3 * x + 1 For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1). Given three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order. Return the kth integer in the range [lo, hi] sorted by the power value. Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in a 32-bit signed integer. Input: lo = 12, hi = 15, k = 2 Output: 13 Explanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1) The power of 13 is 9 The power of 14 is 17 The power of 15 is 17 The interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13. Notice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15.

DFS + cache + sort 从low to high, 每一个element都dfs 一遍。 dfs的过程中每一层都cache一下。

331. Verify Preorder Serialization of a Binary Tree One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'. For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where '#' represents a null node. Given a string of comma-separated values preorder, return true if it is a correct preorder traversal serialization of a binary tree. It is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer. You may assume that the input format is always valid. For example, it could never contain two consecutive commas, such as "1,,3". Note: You are not allowed to reconstruct the tree. Input: preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" Output: true Input: preorder = "1,#" Output: false Input: preorder = "9,#,#,1" Output: false

DFS + global index 如果index > len(arr), 说明list 不够长,不能形成完整的tree 遇到 # 说明当前subtree为空,直接返回true 到最后如果index != len(arr) , 说明list 里还有剩余的数,但tree已经形成

Huffman Coding Encode: input: a string that needs to be encoded output: a binary string 1. get a counter a each character, create a node for each of them, and sort them 2. pop the first two chars, create a new node and the children are the two chars. put this new node back to the queue 3. repeat 1~2 4. Marking: traverse each leaf node, if left, append '0', if right append '1', and the result is the encoded value of that char

Decode: Input: encoded string. E.x '0111011' Output: original string Use DFS to traverse down until the leaf node and get the char. Once reach the leaf node, go back to the root and start traverse down again.

88. Merge Sorted Array You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n. Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.

E.x Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 Loop backward. start with i = m - 1, j = n-1 index_to_write = len(nums1) - 1 And then use two pointers start writing backward. the reason we do this is because for nums1, the number in front is important, we don't want to override write them until later

323. Number of Connected Components in an Undirected Graph You have a graph of n nodes. You are given an integer n and an array edges where edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph. Return the number of connected components in the graph. Input: n = 5, edges = [[0,1],[1,2],[3,4]] Output: 2

Easy DFS

718. Maximum Length of Repeated Subarray Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays. Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7] Output: 3 Explanation: The repeated subarray with maximum length is [3,2,1].

Easy DP arrs[i][j] = 1 + arrs[i-1][j-1]

2405. Optimal Partition of String Given a string s, partition the string into one or more substrings such that the characters in each substring are unique. That is, no letter appears in a single substring more than once. Return the minimum number of substrings in such a partition. Note that each character should belong to exactly one substring in a partition. Input: s = "abacaba" Output: 4 Explanation: Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba"). It can be shown that 4 is the minimum number of substrings needed.

Greedy

1653. Minimum Deletions to Make String Balanced You are given a string s consisting only of characters 'a' and 'b'​​​​. You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'. Return the minimum number of deletions needed to make s balanced. Input: s = "aababbab" Output: 2 Explanation: You can either: Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb").

Greedy. Loop through the list. If it's a, either delete the 'a' or delete all 'b' in front of the 'a'

2065. Maximum Path Quality of a Graph There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a 0-indexed integer array values where values[i] is the value of the ith node. You are also given a 0-indexed 2D integer array edges, where each edges[j] = [uj, vj, timej] indicates that there is an undirected edge between the nodes uj and vj, and it takes timej seconds to travel between the two nodes. Finally, you are given an integer maxTime. A valid path in the graph is any path that starts at node 0, ends at node 0, and takes at most maxTime seconds to complete. You may visit the same node multiple times. The quality of a valid path is the sum of the values of the unique nodes visited in the path (each node's value is added at most once to the sum). Return the maximum quality of a valid path. Note: There are at most four edges connected to each node. Input: values = [0,32,10,43], edges = [[0,1,10],[1,2,15],[0,3,10]], maxTime = 49 Output: 75 Explanation: One possible path is 0 -> 1 -> 0 -> 3 -> 0. The total time taken is 10 + 10 + 10 + 10 = 40 <= 49. The nodes visited are 0, 1, and 3, giving a maximal path quality of 0 + 32 + 43 = 75.

Key to success in this problem is to read problem constraints carefully: I spend like 10 minutes before I understand that problem can be solved using very simple dfs. Why? Because it is given that maxTime <= 100 and time_j >= 10. It means that we can make no more than 10 steps in our graph We have at most 10 steps, and it is also given that each node have at most degree 4, so in total we can make no more than 4^10 states. That is why we will not get TLE.

723. Candy Crush This question is about implementing a basic elimination algorithm for Candy Crush. Given an m x n integer array board representing the grid of candy where board[i][j] represents the type of candy. A value of board[i][j] == 0 represents that the cell is empty. The given board represents the state of the game following the player's move. Now, you need to restore the board to a stable state by crushing candies according to the following rules: If three or more candies of the same type are adjacent vertically or horizontally, crush them all at the same time - these positions become empty. After crushing all candies simultaneously, if an empty space on the board has candies on top of itself, then these candies will drop until they hit a candy or bottom at the same time. No new candies will drop outside the top boundary. After the above steps, there may exist more candies that can be crushed. If so, you need to repeat the above steps. If there does not exist more candies that can be crushed (i.e., the board is stable), then return the current board. You need to perform the above rules until the board becomes stable, then return the stable board.

Loop Until nothing to crush: Go thru the board and find all crushable cells. 检查左边连续两个cell,和上面连续两个cell,如果相等,把它们加进to_remove set里 把to_remove里的cells, mark成0 第三步:drop。从左往右, 用two pointers, 从下往上, 更新board。把每个column最上面剩下的cells,mark成0

838. Push Dominoes There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. You are given a string dominoes representing the initial state where: dominoes[i] = 'L', if the ith domino has been pushed to the left, dominoes[i] = 'R', if the ith domino has been pushed to the right, and dominoes[i] = '.', if the ith domino has not been pushed. Return a string representing the final state. Input: dominoes = ".L.R...LR..L.." Output: "LL.RR.LLRRLL.."

Loop from left to right first, count the "right" influence (the distance to the previous right domino) Loop from right to left, count the "left" influence (the distance to the previous left domino) if dist[i] == -1, means no right influence, set it to 'L' if the left and right influence are equal, then it's '.' if left influence greater than right influence, set it to 'L'

692. Top K Frequent Words Given an array of strings words and an integer k, return the k most frequent strings. Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order. Input: words = ["i","love","leetcode","i","love","coding"], k = 2 Output: ["i","love"] Explanation: "i" and "love" are the two most frequent words. Note that "i" comes before "love" due to a lower alphabetical order.

Map + priority queue

772. Basic Calculator III Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, '+', '-', '*', '/' operators, and open '(' and closing parentheses ')'. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval(). Input: s = "2*(5+5*2)/3+(6/2+8)" Output: 21

No DFS needed. Create a accumulate function calculate [1, '+', 1, '*', 2]. The input array has no parenthesis, and consist only sign or number Loop through the string, convert number string to number, and add everything to a stack, except ')'. Once encounter ')', pop stack until '('. and call accumulate function to get the calculation between the "(" and ")". At the end, accumuclate whatever in the stack 1. When calculate -4/ 3. Use int(float(-2) / 3) to get expected result -1 instead of -2 2. Make sure the arr passed into accumulate method consist only integer number (int) and sign (str)

708. Insert into a Sorted Circular Linked List Given a Circular Linked List node, which is sorted in non-descending order, write a function to insert a value insertVal into the list such that it remains a sorted circular list. The given node can be a reference to any single node in the list and may not necessarily be the smallest value in the circular list. If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the circular list should remain sorted. If the list is empty (i.e., the given node is null), you should create a new single circular list and return the reference to that single node. Otherwise, you should return the originally given node. Input: head = [3,4,1], insertVal = 2 Output: [3,4,1,2]

O(N) runtime Loop thru each node, and validate two cases (ascending or descending)

64. Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. Input: grid = [[1,3,1],[1,5,1],[4,2,1]] Output: 7 Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.

Simple BFS + Priority queue

1823. Find the Winner of the Circular Game There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend. The rules of the game are as follows: Start at the 1st friend. Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once. The last friend you counted leaves the circle and loses the game. If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat. Else, the last friend in the circle wins the game. Given the number of friends, n, and an integer k, return the winner of the game. Input: n = 5, k = 2 Output: 3 Explanation: Here are the steps of the game: 1) Start at friend 1. 2) Count 2 friends clockwise, which are friends 1 and 2. 3) Friend 2 leaves the circle. Next start is friend 3. 4) Count 2 friends clockwise, which are friends 3 and 4. 5) Friend 4 leaves the circle. Next start is friend 5. 6) Count 2 friends clockwise, which are friends 5 and 1. 7) Friend 1 leaves the circle. Next start is friend 3. 8) Count 2 friends clockwise, which are friends 3 and 5. 9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.

Simulation list.pop(index) 被pop的index后面的element会补到前面。

797. All Paths From Source to Target Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order. The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]). 0 -> 1 |. | \|/. \|/ 2 -> 3 E.x [[0,2,3], [0,1,3]]

Since this problem is a DAG, meaning no cycle. We can just use BFS without set

20. Valid Parentheses Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Every close bracket has a corresponding open bracket of the same type. Input: s = "()[]{}" Output: true Input: s = "([])" Output: true

Stack

967. Numbers With Same Consecutive Differences Given two integers n and k, return an array of all the integers of length n where the difference between every two consecutive digits is k. You may return the answer in any order. Note that the integers should not have leading zeros. Integers as 02 and 043 are not allowed. Input: n = 3, k = 7 Output: [181,292,707,818,929] Explanation: Note that 070 is not a valid number, because it has leading zeroes.

Straight forward DFS

611. Valid Triangle Number Input: nums = [2,2,3,4] Output: 3 Explanation: Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3

This can be done in O(n^2). Similar to 3 sum. The difference is in 3 sum we need to find nums[i ]+ nums[j] equals to nums[k], here we need to find nums[i ]+ nums[j] > nums[k],. so here we can't use map or set. but we can use two pointers (i, j, k) Go thru all k, and find good i and j: starting with mininum i and maximum j if greater than nums[j], means we can try to shrink j j - i, means i could be any number between i to j (also satisfy conditionif smaller, means we need to increase i

2115. Find All Possible Recipes from Given Supplies You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes. You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order. Note that two recipes may contain each other in their ingredients. Input: recipes = ["bread","sandwich","burger"], ingredients = [["yeast","flour"],["bread","meat"],["sandwich","meat","bread"]], supplies = ["yeast","flour","meat"] Output: ["bread","sandwich","burger"] Explanation: We can create "bread" since we have the ingredients "yeast" and "flour". We can create "sandwich" since we have the ingredient "meat" and can create the ingredient "bread". We can create "burger" since we have the ingredient "meat" and can create the ingredients "bread" and "sandwich".

Topo sort 先go through 每个ingredient, 如果a 的其中一个ingredient 也是是recipe b。 那么a 就 depend on b。 加到topo map里。更新degree 然后就按照拓扑排序的流程走

18. 4Sum Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: 0 <= a, b, c, d < n a, b, c, and d are distinct. nums[a] + nums[b] + nums[c] + nums[d] == target You may return the answer in any order. Input: nums = [1,0,-1,0,-2,2], target = 0 Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

Transform it to 3sum nums.sort() for i in range(len(nums)-3): #deduplicate on first position for j in range(i+1, len(nums)-2): #deduplicate on first position twoSum(i, j, res)

1291. Sequential Digits An integer has sequential digits if and only if each digit in the number is one more than the previous digit. Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits. Input: low = 1000, high = 13000 Output: [1234,2345,3456,4567,5678,6789,12345]

Use BFS to list out all the possible cases and add it to res if satisfy the condition start with queue [1,2,3,4,5,6,7,8,9] each element, add a number after it. E.x, 1 => 12, and append it to the queue. Until the last digit is 9 Runtime: 9+8+7+6+5+4+3+2+1 = O(45) = O(1)

282. Expression Add Operators Given a string num that contains only digits and an integer target, return all possibilities to insert the binary operators '+', '-', and/or '*' between the digits of num so that the resultant expression evaluates to the target value. Note that operands in the returned expressions should not contain leading zeros. Input: num = "123", target = 6 Output: ["1*2*3","1+2+3"] Explanation: Both "1*2*3" and "1+2+3" evaluate to 6. Input: num = "115", target = 16 Output: ["11+5"] Explanation: Both "1*2*3" and "1+2+3" evaluate to 6.

Use DFS Each round, loop through i (index+1 to the end), take num[index:1] as number, append to the path with '+' '-' or '*' To handle '*' case, the new sum is (cur_sum - prev) + prev*n. Basically recalculate because * will be consider first.

221. Maximal Square Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. Input: matrix = [["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"]] Output: 4

Use DP matrix: 1 1 1 1 1 1 1 1 1 memo: 1 1 1 1 2 2 1 2 3 Each memo[i][j] is the max square that has (i,j) as right bottom corner To get memo[i][j], we look at the 3 neibors around it => min(matrix[i-1, j], matrix[1, j-1], matrix[i-1][j-1]) + 1.

827. Making A Large Island You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1. Return the size of the largest island in grid after applying this operation. An island is a 4-directionally connected group of 1s. Input: grid = [[1,0],[0,1]] Output: 3 Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.

Use UnionFind 用parents来记录每个island的size loop thru每个0 cell,把cell的四周的1的所在的island的size全部加起来再 + 1, 这就是新的island的大小。

426. Convert Binary Search Tree to Sorted Doubly Linked List Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place. You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element. We want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list.

Use dfs each recursion return (head, tail) for that subtree

44. Wildcard Matching Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). Input: s = "aa", p = "a" Output: false Explanation: "a" does not match the entire string "aa". Input: s = "aa", p = "*" Output: true Explanation: '*' matches any sequence.

Use dfs + memo 此题跟 10. Regular Expression Matching 类似。可以一起看。Regular Expression Matching 里 '*' Matches zero or more of the preceding element. 而此题是Matches any sequence of characters (including the empty sequence) 此题需要注意'****' 这种特殊的case,可以把连续的'***'压缩成一个。 第一种情况好理解: if s[i] == p[j] or p[j] == '?': dfs(i+1, j+1) 第二种情况: if p[j] == '*': dfs(i+1, j) or dfs(i,j+1) dfs(i+1,j) => Matches any sequence of characters dfs(i,j+1) => match empty sequence

894. All Possible Full Binary Trees Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0. Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order. A full binary tree is a binary tree where each node has exactly 0 or 2 children. Input: n = 7 Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]

Use dfs(i, j) In each level, select any element between [i+1, j-1] as a new node, 然后分别dfs 左边的range 和右边的range。分别得到left options和right options。 再把每个option进行组合。 注意每一层的range是i+1,到j-1。因为要确保左右两边至少有一个node

1274. Number of Ships in a Rectangle Pic in the graph Each ship is located at an integer point on the sea represented by a cartesian plane, and each integer point may contain at most 1 ship. You have a function Sea.hasShips(topRight, bottomLeft) which takes two points as arguments and returns true If there is at least one ship in the rectangle represented by the two points, including on the boundary. Given two points: the top right and bottom left corners of a rectangle, return the number of ships present in that rectangle. It is guaranteed that there are at most 10 ships in that rectangle. Submissions making more than 400 calls to hasShips will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.

Use divide and concur. If the quarter area return as false, which means no ship in this area, we can safely return 0if the quarter area returns as True, we should keep on dividing that area into four parts to further explore.The base case will be the top and bottom points are the same (means it's a point), then we can get the exact result. It is if True, we have one ship, if False, we have zero ship. Be careful!!! thing is in order to have no overlap for these four parts, we need to add a center point by 1. This will also prevent infinite loops

179. Largest Number Given a list of non-negative integers nums, arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer. Input: nums = [10,2] Output: "210"

Use quick sort with special comparision

1472. Design Browser History You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps. Implement the BrowserHistory class: BrowserHistory(string homepage) Initializes the object with the homepage of the browser. void visit(string url) Visits url from the current page. It clears up all the forward history. string back(int steps) Move steps back in history. If you can only return x steps in the history and steps > x, you will return only x steps. Return the current url after moving back in history at most steps. string forward(int steps) Move steps forward in history. If you can only forward x steps in the history and steps > x, you will forward only x steps. Return the current url after forwarding in history at most steps.

Use two stack. Make sure there is always an element in the back_stack. The current site is the last element of back_stack. when 'back', pop back_stack and put it into forward_stack when forward, pop forward_stack and put in into back_stack when visit, append to back_stack, clear forward_stack

261. Graph Valid Tree You have a graph of n nodes labeled from 0 to n - 1. You are given an integer n and a list of edges where edges[i] = [ai, bi] indicates that there is an undirected edge between nodes ai and bi in the graph. Return true if the edges of the given graph make up a valid tree, and false otherwise. Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]] Output: true

Valid Tree: All nodes have only one parent. No cycle Use UnionFind. Make sure when union 2 nodes, their parents are different. Otherwise, it means there is cycle Also make sure there is only one parent for the whole tree

1366. Rank Teams by Votes In a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition. The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter. You are given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above. Return a string of all teams sorted by the ranking system. Input: votes = ["ABC","ACB","ABC","ACB","ACB"] Output: "ACB" Explanation: Team A was ranked first place by 5 voters. No other team was voted as first place, so team A is the first team. Team B was ranked second by 2 voters and ranked third by 3 voters. Team C was ranked second by 3 voters and ranked third by 2 voters. As most of the voters ranked C second, team C is the second team, and team B is the third.

each item will have a ranks. how many people vote for this item in this rank For example, A: [-5, 0, 0], 5 people vote for A at rank 1. If rank 1 is tie, compare the number of people voting the item at rank2 At the end, add item to the end of the ranks so we can take alphabet into consideration if everything else is tied

895. Maximum Frequency Stack Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the FreqStack class: FreqStack() constructs an empty frequency stack. void push(int val) pushes an integer val onto the top of the stack. int pop() removes and returns the most frequent element in the stack.If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned. Input ["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"] [[], [5], [7], [5], [7], [4], [5], [], [], [], []] Output [null, null, null, null, null, null, null, 5, 7, 5, 4] Explanation FreqStack freqStack = new FreqStack(); freqStack.push(5); // The stack is [5] freqStack.push(7); // The stack is [5,7] freqStack.push(5); // The stack is [5,7,5] freqStack.push(7); // The stack is [5,7,5,7] freqStack.push(4); // The stack is [5,7,5,7,4] freqStack.push(5); // The stack is [5,7,5,7,4,5] freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4]. freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4]. freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4]. freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].

push 1,1,2,1,2,3 => stack [[1,2,3], [1,2], [1]] stack's index is the frequency of the element 此题跟LFU有点像。 都是用frequency作为list的index。但是LFU因为需要移动list中间的val, 所以用linkedlist 比较好。这道题只需要pop,所以可以用list

945. Minimum Increment to Make Array Unique You are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1. Return the minimum number of moves to make every value in nums unique. The test cases are generated so that the answer fits in a 32-bit integer. Input: nums = [3,2,1,2,1,7] Output: 6 Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7]. It can be shown with 5 or less moves that it is impossible for the array to have all unique values.

先sort array [1,1,2,2,3,7] loop thru arr, maintain 一个 max_seen value, 如果max_seen >= arr[i], 说明arr[i]到max_seen之间的数都已经被用了。arr[i]只能被update 成max_seen + 1. 如果arr[i] > max_seen, 说明arr[i]的数还没被取用。不需要update

2096. Step-By-Step Directions From a Binary Tree Node to Another You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction: 'L' means to go from a node to its left child node. 'R' means to go from a node to its right child node. 'U' means to go from a node to its parent node. Return the step-by-step directions of the shortest path from node s to node t. 5 / \ 1 2 /. /\ 3. 6. 4 Source: 3, dest: 6 Output: 'UURL'

先找出lowest common ancestor 然后用stack 写出source和dest的path return 'U' * len(s_path) + d_path

791. Custom Sort String You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously. Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string. Return any permutation of s that satisfies this property. Input: order = "cba", s = "abcd" Output: "cbad" Explanation: "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a". Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.

先把s转化成counter -> char: count 然后loop thru order, 如果order 的char在map 里,就直接根据数量print在res 里。然后把剩下的map里的char 贴到res里

49. Group Anagrams Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

把每个string,先sort一遍,然后把sorted过的string作为map的key

Design Board Game (六子棋) On an infinite board, 2 players (black and white) place black/white stones. Starts with black player (1 move), and then each player place stones alternatively (2 moves each turn). Whoever can make the stones in 6 continuous stones (horizontally/vertically/diagnally) wins can game.

次题因为是infinite board, 所以不能用arr来存board的状态。这里用2d map来存 每下一个棋子,首先更新white/black spots的状态 。然后loop thru四个方向:[(0,1), (0,1), (1,1), (1,-1)], 每个方向,查看当前棋子的前5个到后5个, 看看有没有连续的6个棋子。为什么查前5个到后5个? 最坏情况,如果当前棋子是在一个连续6个棋子的最后一个,从前5个棋子开始查就可以detect这6个连续的棋子。其他情况的话,查看当前棋子的前5个到后5个,肯定可以查出6个连续的棋子。 成功的话说明当前player赢了

716. Max Stack Design a max stack data structure that supports the stack operations and supports finding the stack's maximum element. Implement the MaxStack class: MaxStack() Initializes the stack object. void push(int x) Pushes element x onto the stack. int pop() Removes the element on top of the stack and returns it. int top() Gets the element on the top of the stack without removing it. int peekMax() Retrieves the maximum element in the stack without removing it. int popMax() Retrieves the maximum element in the stack and removes it. If there is more than one maximum element, only remove the top-most one. You must come up with a solution that supports O(1) for each top call and O(logn) for each other call.

此题不能像min stack一样简单的维护 两个stacks。因为这道题有pop max而min stack只有pop 这题用一个stack和一个heap来做lazy deletion 因为push进来的value 可能重复,需要一个global的index来标记每个进来的数。注意index是递减的,因为如果两个数相等,我们需要在heap里把后来的数放在前面 (因为需要remove top-most one) 每次pop 或者 popmax之后需要把pop出来的index加到一个invalid set里,表示这个数已经invalid了。然后进行一次clear。clear 就是把stack 最后一个数和 heap 里最大的数 清除掉,如果它是invalid的话 (soft deletion的精髓) For clear() function, The run time is averagely O(1) because each element is at most deleted once

240. Search a 2D Matrix II Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. Input: matrix = [[1,4,7,11,15], [2,5,8,12,19], [3,6,9,16,22], [10,13,14,17,24], [18,21,23,26,30]], target = 5 Output: true

此题从左下角开始,如果val 大于 target, 往右走。如果val 小于target, 往上走。如果等于,return true 此题因为只能往上走或者往右走。runtime 是o(m+n). 因为所有竖着的加上横着的边 =》 m+n

1775. Equal Sum Arrays With Minimum Number of Operations You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive. In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive. Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1​​​​​ if it is not possible to make the sum of the two arrays equal. Input: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2] Output: 3 Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. - Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2]. - Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2]. - Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].

此题其实没有那么复杂,flexibility 很高。因为只要确保len(nums1) <= len(nums2) * 6 或者 len(nums2) <= len(nums1) * 6, 就会有答案 假如sum1 > sum2 那我们如何尽快的转换,可以使sum1 和sum2相等呢?我们需要从转化幅度最大的开始。我需要先试着把nums1 最大的数转化成1, 或者是这把nums2最小的数转化成6. (取决于哪个情况幅度更大) 所以根据这个思路,先将nums1, nums2 排序,然后用2 pointers

213. House Robber II You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night. Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. Input: nums = [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.

此题几乎跟house robber 1 一样,只是dfs 的parameter需要加一个is first house robber? 然后在考虑最后一个index的时候需要考虑 is first house robber

348. Design Tic-Tac-Toe Assume the following rules are for the tic-tac-toe game on an n x n board between two players: A move is guaranteed to be valid and is placed on an empty block. Once a winning condition is reached, no more moves are allowed. A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game. Implement the TicTacToe class: TicTacToe(int n) Initializes the object the size of the board n. int move(int row, int col, int player) Indicates that the player with id player plays at the cell (row, col) of the board. The move is guaranteed to be a valid move, and the two players alternate in making moves. Return0 if there is no winner after the move,1 if player 1 is the winner after the move, or2 if player 2 is the winner after the move. Input ["TicTacToe", "move", "move", "move", "move", "move", "move", "move"] [[3], [0, 0, 1], [0, 2, 2], [2, 2, 1], [1, 1, 2], [2, 0, 1], [1, 0, 2], [2, 1, 1]] Output [null, 0, 0, 0, 0, 0, 0, 1]

此题创建三个array, row_array, column_array, diagnal_array 每个array[i]代表所在row/column/diagnal 被哪个player占领。0 说明还没有player 占领。被1占领+1, 被2占领-1, 如果1和2 都有棋子在这个row/column/diagnal,说明这个row/column/diagnal已经dead, mark it as none

1642. Furthest Building You Can Reach You are given an integer array heights representing the heights of buildings, some bricks, and some ladders. You start your journey from building 0 and move to the next building by possibly using bricks or ladders. While moving from building i to building i+1 (0-indexed), If the current building's height is greater than or equal to the next building's height, you do not need a ladder or bricks. If the current building's height is less than the next building's height, you can either use one ladder or (h[i+1] - h[i]) bricks. Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally. Input: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1 Output: 4 Explanation: Starting at building 0, you can follow these steps: - Go to building 1 without using ladders nor bricks since 4 >= 2. - Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7. - Go to building 3 without using ladders nor bricks since 7 >= 6. - Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9. It is impossible to go beyond building 4 because you do not have any more bricks or ladders.

此题如果用dfs + memo 会超时,因为constraint太大。更简单的方法是用min heap. 对于当前位置前面的gaps全部用ladders。如果ladder不够了, 把当前位置前面的最小的gap 用bricks 来代替。直到bricks 也不够了,就return 当前的index。

354. Russian Doll Envelopes You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other). Note: You cannot rotate an envelope. Input: envelopes = [[5,4],[6,4],[6,7],[2,3]] Output: 3 Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).

此题如果用dfs+memo会超时 => O(n^2) 更巧妙的方法是用 longest increasing subsequence的方法 先把evelopes 排序。x[0] increasing, x[1] decreasing。为什么要这样排序?x[0] increasing =》 先把evelopes 的顺序确定下来。 longest increasing subsequence 题中,我们不能更换element的位置。这题中我们可以。所以先用x[0] increasing 排序把element的顺序确定。 因为我们需要在x[1]上进行 longest increasing subsequence的逻辑。(3,4), (3,5)在此题中不是一个valid的sequence。 所以把(3,5)排在(3,4)前面, 在进行 longest increasing subsequence的时候,(3,4), (3,5) 这两个elemnt就不是一个valida的case

948. Bag of Tokens You have an initial power of power, an initial score of 0, and a bag of tokens where tokens[i] is the value of the ith token (0-indexed). Your goal is to maximize your total score by potentially playing each token in one of two ways: If your current power is at least tokens[i], you may play the ith token face up, losing tokens[i] power and gaining 1 score. If your current score is at least 1, you may play the ith token face down, gaining tokens[i] power and losing 1 score. Each token may be played at most once and in any order. You do not have to play all the tokens. Return the largest possible score you can achieve after playing any number of tokens. Input: tokens = [100,200,300,400], power = 200 Output: 2 Explanation: Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2.

此题如果用dfs会超时 有一个更加巧妙的方法是用2 pointers。 首先把tokens 从大到小sort一下 原则是:尽量用最小的power换取1分, 用1分换power的时候,用最大的power。 (elif)如果当前最小的token比当前的power大,就用一份换最大的token。(else) 如果换完了最大的token,还是满足不了当前的power,break。如果能换,继续two pointers while loop Solution is straightforward. Always aim for highest point Sort the tokens so we can buy from lowest & sell from highest which means =>If we have enough power, no worries. Just lose token[l(eft)], and increase score by 1.If we have at least 1 score and we are not in the last processed token, gain token[r(ight)] and decrease score by 1.Otherwise, we are finished.

2035. Partition Array Into Two Arrays to Minimize Sum Difference Input: nums = [3,9,7,3] Output: 2 Explanation: One optimal partition is: [3,9] and [7,3]. The absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2.

此题如果直接枚举出所有combinations, 会是2^n (n 最大是30, 2^30会超时 把nums 分成两半: nums1, nums2. 然后分别用combination。这样时间就可以缩短成2^15 (这个runtime可以接受)。 x 是 从nums1 选出的个数. y 是从nums2 选出的个数; y = n - x sum_x 是 从num1选出的数的sum sum_y 是从num2选出的数的sum 尽量找出一个sum_x + sum_y = total_sum - (sum_x + sum_y) 也就是找出一个sum_y 尽量接近于 total_sum / 2 - sum_x 具体操作是: 1. 首先预处理nums2. 用combinations,生成一个map。map的key是所有可能的 y (选出的数量),value 是一个list: 所有个数是y 的sum 2. 对nums1 进行combination。 对一每一种情况,通过x算出对应的y (n-x)。然后在map里找出sum_y的所有candidates。用binary search 找出最接近于 total_sum // 2 - sum_x 的sum_y。 3. res 就是最小的abs(sum_x + sum_y - (total_sum - sum_x - sum_y))

163. Missing Ranges You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are in the inclusive range. A number x is considered missing if x is in the range [lower, upper] and x is not in nums. Return the smallest sorted list of ranges that cover every missing number exactly. That is, no element of nums is in any of the ranges, and each missing number is in one of the ranges. Each range [a,b] in the list should be output as: "a->b" if a != b "a" if a == b Input: nums = [0,1,3,50,75], lower = 0, upper = 99 Output: ["2","4->49","51->74","76->99"] Explanation: The ranges are: [2,2] --> "2" [4,49] --> "4->49" [51,74] --> "51->74" [76,99] --> "76->99"

此题就是loop thru nums 每次看看prev +1 是不是num, 如果不是就加到res里

768. Max Chunks To Make Sorted II You are given an integer array arr. We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return the largest number of chunks we can make to sort the array. Input: arr = [2,1,3,4,4] Output: 4 Explanation: We can split into two chunks, such as [2, 1], [3, 4, 4]. However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.

用stack 例遍每一个数n, 形成一个初始chunk [n,n]. 然后开始pop stack:如果前一个chunk的最大值比当前chunk 的最小值小, 把这两个chunk merge 了。

151. Reverse Words in a String Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. Input: s = "a good example" Output: "example good a" Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

此题用2 pointer 做 先把两边的space trim 掉 然后从后往前,让j先走,知道遇到space 停住,开始往res里输入从j+1 到i 的char。然后j继续走直到 j == 0 注意需要处理的情况是double space,每一轮结束前如果j 下一个char是space的话需要shrink j

315. Count of Smaller Numbers After Self Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i]. Input: nums = [5,2,6,1] Output: [2,1,1,0] Explanation: To the right of 5 there are 2 smaller elements (2 and 1). To the right of 2 there is only 1 smaller element (1). To the right of 6 there is 1 smaller element (1). To the right of 1 there is 0 smaller element.

此题用BIT 做。BIT (Binary Index Tree)另一题:307. Range Sum Query - Mutable e.x [5,2,6,1] 首先reverse 一下[1,6,2,5]此题等同于找出reversed list 的左边比self小的数。 rank: 1,4,2,3 维护一个freq_list 例遍reversed list,更新freq_list (index就是rank-1)。此题等同于找出freq_list 每个index左边的 freq_list的sum。 所以就要用BIT。 因为freq_list 就相当于BIT里的nums, 然后freq_list是不停更新的。因为后面例遍的数在freq_list 还没更新,所以我们可以放心的使用sum freq_list: [1,0,0,0] -> [1,0,0,1] -> [1,1,0,1] -> [1,1,1,1]

1044. Longest Duplicate Substring Given a string s, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap. Return any duplicated substring that has the longest possible length. If s does not have a duplicated substring, the answer is "". Input: s = "banana" Output: "ana"

此题用binary search + fixed window sliding binary search: 找最大满足条件的值 每次看看mid满不满足 =》 s里有长度为mid的duplicated的substring。 检查s里有没有长度为mid 的duplicated substrings: 用fixed window sliding. 先把substring hash 一下, d 可以取任意值。因为hash可能会有collision,所以用dict来储存 'abc' => ord('a') * d^2 + ord('b')*d + ord('c'). slide 的时候, 先减去左边的hash, cur - ord('a') * d^2. 再promote剩余的hash =》ord('b')*d^2 + ord('c')*d. 再加上右边的hash => ord('b')*d^2 + ord('c')*d + ord('e') 如果hash 在dict里 且substring 一样,说明有重复的,return true

968. Binary Tree Cameras You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return the minimum number of cameras needed to monitor all nodes of the tree. Input: root = [0,0,null,0,null,0,null,null,0] Output: 2 Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.

此题用dfs + memo 设置一个 status: 1. parent has camera 2. parent has no camera 3. parent needs camera 然后分情况讨论 1. 如果parent 有 camera, cur node 可以设camera, 可以不设 2. 如果parent 没有camera, 有几种情况: 2.1. 如果cur node 没有children, 那么cur node 必须自己设camera 2.2. 如果cur node 只有left child,那么left child必须设camera 2.3 如果cur node 只有right child, 那么right child必须舍camera 2.4如果cur node两个children 都有,那么其中一个child设camera就行了 3. 如果parent needs camera,说明cur node 必须设camera 每一轮 取可行情况的最小值

2484. Count Palindromic Subsequences Given a string of digits s, return the number of palindromic subsequences of s having length 5. Since the answer may be very large, return it modulo 109 + 7. Note: A string is palindromic if it reads the same forward and backward. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. Input: s = "103301" Output: 2 Explanation: There are 6 possible subsequences of length 5: "10330","10331","10301","10301","13301","03301". Two of them (both equal to "10301") are palindromic.

此题用dfs + memo的做法 memo 是 (index, x, y, length) 假设最终的subsequence是 1,2,3,4,5 x是1的value, y 是2的value 对于每一个index,我可以取或者不取。 x, y 可以取任何数 position 3也可以取任何数 position 4只能match y position 5 只能match x

694. Number of Distinct Islands You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. An island is considered to be the same as another if and only if one island can be translated (and not rotated or reflected) to equal the other. Return the number of distinct islands. Input: grid = [ [1,1,0, 1, 1], [1,0,0,0,0], [0,0,0,0,1], [1,1,0,1,1]] Output: 3

此题用dfs来做。 例遍所有cell,如果cell是1,开始用dfs 找出所在island的shape shape 其实就是island里所有的cells到initial cell的relative position 的集合。visit 过的cell就mark 成-1, 所以不会再被visit 找出shape (是一个list)后,把它转化为tuple存在set里,最后看这个set里有多少个shape

823. Binary Trees With Factors Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7. Input: arr = [2,4,5,10] Output: 7 Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].

此题用memo + dfs 每一轮的input 是num,num 就是parent node,go thru arr: 如果num % arr[i] == 0, 然后num // arr[i] 也在arr 里。说明能够形成subtree。然后继续dfs children nodes。分别用dfs(arr[i]) 和 dfs(num // arr[i]). 注意的是,如果left tree 有m 种树的可能。right tree 有n种树的可能。那么 parent tree就有m*n种可能。e.x 两个6的subtree分别有2种可能。36的subtree有4种可能 36 / \ 6 6 /\ /\ 2 3 2 3 36 / \ 6 6 /\ /\ 3 2 2 3 36 / \ 6 6 /\ /\ 2 3 3 2 36 / \ 6 6 /\ /\ 3 2 3 2

855. Exam Room There is an exam room with n seats in a single row labeled from 0 to n - 1. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0. Design a class that simulates the mentioned exam room. Implement the ExamRoom class: ExamRoom(int n) Initializes the object of the exam room with the number of the seats n. int seat() Returns the label of the seat at which the next student will set. void leave(int p) Indicates that the student sitting at seat p will leave the room. It is guaranteed that there will be a student sitting at seat p. Input ["ExamRoom", "seat", "seat", "seat", "seat", "leave", "seat"] [[10], [], [], [], [], [4], []] Output [null, 0, 9, 4, 2, null, 5] Explanation ExamRoom examRoom = new ExamRoom(10); examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0. examRoom.seat(); // return 9, the student sits at the last seat number 9. examRoom.seat(); // return 4, the student sits at the last seat number 4. examRoom.seat(); // return 2, the student sits at the last seat number 2. examRoom.leave(4); examRoom.seat(); // return 5, the student sits at the last seat number 5.

此题用priority queue. element 是 (-length, start, end), 称作range。 start 和 end 都是可取的 inclusive 的。 length 就是range 的长度,queue里的priority. 注意有特殊情况:start,__,end 和 start,__,__,end 这两种情况的length 都是3因为在queue 里它们的priority 都是一样的 seat: 如果当前最长的range 里有0, result 就是0. 因为0左边没有值了。这个range离end 最远的就是0. 同理,如果有n-1, result 就是n-1. 否则result 就是(start + end) // 2 找到result 之后需要把劈开的两个ranges加到queue里 leave(p): 首先loop thru queue, 找到两个p 左右两边的range, merge成一个range =》new_start, new_end。 特殊情况,如果是1,2,__,__, 5, leave(2). new_start 会是none, 这种情况把new_start set成p。同理如果new_end 是none,把new_end set成p 此题具体写起来比较复杂。需多写几遍

149. Max Points on a Line Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line. Input: points = [[1,1],[2,2],[3,3]] Output: 3

此题由于数目较小, n < 40, 所以可以n^2 例遍每一个pair,用y = kx + b 的公式算出k, b然后放进map. map的key 是 (k, b), value 是point set。 然后找出最大的set就是result。注意处理垂直 直线的情况

390. Elimination Game You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr: Starting from left to right, remove the first number and every other number afterward until you reach the end of the list. Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers. Keep repeating the steps again, alternating left to right and right to left, until a single number remains. Given the integer n, return the last number that remains in arr. Input: n = 9 Output: 6 Explanation: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] arr = [2, 4, 6, 8] arr = [2, 6] arr = [6]

此题的解法很巧妙 每一轮,更新head的值。一直到list的size是1的时候,head的值,就是result 每一轮,如果是从左往右,或者 (从右往左 + size是奇数),head 的值就会发生变化变成head的下一个值 current head + gap。gap,通过观察,就是当前轮(n)的2^n

16. 3Sum Closest Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

此题类似于3 sum for loop + two pointers 的做法 在用while loop 做two pointers 的时候,instead of 找两个element sum to 的target,找closest one

621. Task Scheduler Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks. Return the least number of units of times that the CPU will take to finish all the given tasks. Input: tasks = ["A","A","A","B","B","B"], n = 2 Output: 8 Explanation: A -> B -> idle -> A -> B -> idle -> A -> B There is at least 2 units of time between any two same tasks.

此题跟shuffle letters 那题很像 (shuffle letters 使得相同的letter 不相邻) 用priority queue 来做。首先先count每个task, 然后把(count, key)从大到小放进priority queue 里。每一轮试着从queue里pop出n个元素,如果凑不齐n个,就需要加idle。 每一轮结束后把更新过的(count, key)再加到queue里。count是0就不需要加了 为什么是从大到小排序,因为我们尽可能需要用掉频率最高的元素。这样到最后就能剩跟多不同的元素

380. Insert Delete GetRandom O(1) Implement the RandomizedSet class: RandomizedSet() Initializes the RandomizedSet object. bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise. bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise. int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned. You must implement the functions of the class such that each function works in average O(1) time complexity.

此题需要用一个map + 一个array 每次insert,把新的val append到arr。然后更新map,map[val] = len(arr) - 1 每次delete,把array 的最后一个element 挪到要被delete的val的index,更新map,这样就能保证array里没有空的值

Merge K sorted stream Notice that this is not merge k sorted list. Streams could have infinite length, so here can't use divide and conqur Give two streams, for each the first element is the real value and the followings are the delta value. Given n streams with (time, value), and merge them into one stream

维护一个length 为 n (# of streams)的priority queue (递增)。queue 的element是 (time, value, index)index是stream所在的index。 每一次, 在priority queue满了的时候,把最小的el pop出来加到res里。然后找的el所在的stream,拿到下一个stream element,加到priority queue里 (加之前注意要加上前一个el的value因为是deltaa)

1567. Maximum Length of Subarray With Positive Product Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive. A subarray of an array is a consecutive sequence of zero or more values taken out of that array. Return the maximum length of a subarray with positive product. Input: nums = [0,1,-2,-3,-4] Output: 3 Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6. Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.

此题首先将arr 以0作为delimiter,split成chunk。每个chunk 如果negative的数量是偶数,说明它们的product是positive,返回chunk的length。如果negative的数量是奇数,尝试着exclude最左边或者最右边的negative,再比较哪种情况的length最长

730. Count Different Palindromic Subsequences Given a string s, return the number of different non-empty palindromic subsequences in s. Since the answer may be very large, return it modulo 109 + 7. A subsequence of a string is obtained by deleting zero or more characters from the string. A sequence is palindromic if it is equal to the sequence reversed. Two sequences a1, a2, ... and b1, b2, ... are different if there is some i for which ai != bi. Input: s = "bccb" Output: 6 Explanation: The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'. Note that 'bcb' is counted only once, even though it occurs twice.

注意此题限定character是'abcd' 用dfs+memo 每一轮,例遍'abcd', 找到当前char的最左边和最右边的index i, j If i == j. There is only one 'a' in the segment. So the answer is 1. If i != j. The possible palindromes are 'a', 'aa', and 'a*a' where '*' stands for any palindromes contained in S[i+1:j-1]. The answer would be DFS(i+1,j) + 2 "abba" 例遍'ab': 1. 'a': i: 0, j: 3 2 + dfs(1,2) : 2, 代表 "a", "aa" dfs(1,2): 2, 代表 "aba", "abba" 2. 'b': i=1, j = 2 2 + dfs(2,1): 代表"b", "bb" 所以加起来就是4

Treasure Hunter Given a 2 D array, 1 represents a treasure, 2 represent wall, 0 represent empty path. Find the shortest steps to take to get all treasures

用bfs。 首先先找出所有1,把每个1 对应一个index 用一个string (或者binary)来表示status, seen set 里的element是(x, y, status)。意思是相同的位置,如果status一样(在当前位置,已经获得的key是一样的)就没有必要再visit了

Maximum sum of nodes in Binary tree such that no two are adjacent https://www.geeksforgeeks.org/maximum-sum-nodes-binary-tree-no-two-adjacent/ Given a binary tree with a value associated with each node, we need to choose a subset of these nodes such that the sum of selected nodes is maximum under a constraint that no two chosen nodes in the subset should be directly connected, that is, if we have taken a node in our sum then we can't take any of its children in consideration and vice versa. 1 / \ 2. 3 /. /\ 1. 4. 5. => result 2 + 4 + 5

用dfs + memo 每一轮,有两种情况 1. 当前value + grandson's max value 2. skip current node's value and take children's max value 把node作为memo的key

1244. Design A Leaderboard Design a Leaderboard class, which has 3 functions: addScore(playerId, score): Update the leaderboard by adding score to the given player's score. If there is no player with such id in the leaderboard, add him to the leaderboard with the given score. top(K): Return the score sum of the top K players. reset(playerId): Reset the score of the player with the given id to 0 (in other words erase it from the leaderboard). It is guaranteed that the player was added to the leaderboard before calling this function. Initially, the leaderboard is empty.

用priority queue + hashmap。 更新priority queue里的reference。更新完之后要heapify一遍 (o(n)) 或者用priority queue + lazy deletion。 这种情况averagely k*log(n)。因为每个element最多被remove一次

32. Longest Valid Parentheses Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring . Input: s = "(()" Output: 2 Explanation: The longest valid parentheses substring is "()". Input: s = ")()())" Output: 4 Explanation: The longest valid parentheses substring is "()()".

用stack stack的第一个element 是 last "bad" index. last bad index 就是上一个bad ")",或者-1. 遇到 "(", 就把index加到stack里。遇到")", 就pop 一个"(",计算一下长度。如果pop 出来的是last bad index (stack之后是empty),说明前面没有"("和当前的")"组合。当前的")"就是bad index, 加到stack 里

Top K element of a stream Implement a top k object obj = TopKStructure(2) obj.processEventCounts([('A', 30)]) obj.processEventCounts([('B', 5)]) obj.processEventCounts([('A', 23)]) obj.processEventCounts([('B', 6), ('C', 24), ('D', 12)]) print(obj.getTopK()) output: [('C', 24), ('A', 23)]. Note that for A, 23 override 30

维护一个长度为k的递增的queue,queue里面的element是array。因为需要用到reference,所以不能用tuple。然后用一个map来store key: array。如果遇到一样的key,用map找到对应的array, 更新array。因为priority queue被更新了所以需要heapify again。 heapify 一般需要o(n)

249. Group Shifted Strings We can shift a string by shifting each of its letters to its successive letter. For example, "abc" can be shifted to be "bcd". We can keep shifting the string to form a sequence. For example, we can keep shifting "abc" to form the sequence: "abc" -> "bcd" -> ... -> "xyz". Given an array of strings strings, group all strings[i] that belong to the same shifting sequence. You may return the answer in any order. Input: strings = ["abc","bcd","acef","xyz","az","ba","a","z"] Output: [["acef"],["a","z"],["abc","bcd","xyz"],["az","ba"]]

计算每个char之间的差,放进一个string里作为hashmap的key

311. Sparse Matrix Multiplication Given two sparse matrices mat1 of size m x k and mat2 of size k x n, return the result of mat1 x mat2. You may assume that multiplication is always possible. Input: mat1 = [[1,0,0], [-1,0,3]], mat2 = [[7,0,0], [0,0,0], [0,0,1]] Output: [[7,0,0],[-7,0,3]]

这是一个sparse数据结构的题目。如果按照正常的算法,很不划算因为有许多值都是0。runtime 是 m * n 更优化的做法是先用map 把非0的数存下来,再算出result。 map1 (mat1) 的key 是 row index, value 是 (col index, val) map2 (mat2) 的key 是 col index, value 是 (row index, val) 相当于是例遍 map1 的 key: 例遍map2 的key: product(map1[key1], map2[key2]) product就是把两个list 乘起来。用2 pointer的方法。list 的element是tuple(row/col index, val) 需要两个element有相同的index才能乘起来。 follow up: 如果其中一个matrix比另一个matrix大很多,怎么优化? 在product(list1, list2)的时候,例遍小的那个list,大的那个list用binary search

835. Image Overlap You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values. We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images. Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased. Return the largest possible overlap. E.x Img1 = [1, 1, 0] [0, 1, 0] [0, 1, 0] img2 = [0, 0, 0] [0, 1, 1] [0, 0, 1] ans = 3 : 3 is the max overlap

这道题用bfs 会超时 因为这道题size比较小, 所以可以用n^2 把每个img1 里的1 和每一个img2 里的1 pair up. 算出 (x1 - x2, y1- y2)。 这个代表s1 => s2 的位移。 counter里,每一个unique的位移作为key。找出频率最高的位移

254. Factor Combinations Numbers can be regarded as the product of their factors. For example, 8 = 2 x 2 x 2 = 2 x 4. Given an integer n, return all possible combinations of its factors. You may return the answer in any order. Note that the factors should be in the range [2, n - 1]. Input: n = 12 Output: [[2,6],[3,4],[2,2,3]]

这道题类似于find subset. 但是由于每个数可以重复,给下一轮的paraameter用的是i, 不是 i+1 每一轮,parameter 里会携带一个path, path 就是一个list,里面是能被之前的amount 整除的数。amount 是 剩下的n

1405. Longest Happy String A string s is called happy if it satisfies the following conditions: s only contains the letters 'a', 'b', and 'c'. s does not contain any of "aaa", "bbb", or "ccc" as a substring. s contains at most a occurrences of the letter 'a'. s contains at most b occurrences of the letter 'b'. s contains at most c occurrences of the letter 'c'. Given three integers a, b, and c, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string "". A substring is a contiguous sequence of characters within a string. Input: a = 1, b = 1, c = 7 Output: "ccaccbcc" Explanation: "ccbccacc" would also be a correct answer.

这道题跟shuffle letters 那题类似。用heap 来做。 idea 是尽量先append major elements (count最多的element). 每次append 2 个。如果pop出来的char 跟上一个append的char是一样的,再pop一个char出来append。注意因为第二个append出来的char 是minor element, 我们需要省着用(只append一次),因为它可能可以下次再split major element

307. Range Sum Query - Mutable Given an integer array nums, handle multiple queries of the following types: Update the value of an element in nums. 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. void update(int index, int val) Updates the value of nums[index] to be val. 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]). Input ["NumArray", "sumRange", "update", "sumRange"] [[[1, 3, 5]], [0, 2], [1, 2], [0, 2]] Output [null, 9, null, 8] Explanation NumArray numArray = new NumArray([1, 3, 5]); numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9 numArray.update(1, 2); // nums = [1, 2, 5] numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8

这道题需要用到 Fenwick Tree 或者是叫 Binary Index Tree 这道题如果没有update的话,可以直接用presum 做。但是nums 可以被update,naive 的方法就是 用n^2的方法做。更好的方式是用Binary Index Tree nums = [1,2,3,4,5,6,7,8] - - - - - ------ 36 (8) / / / --- 10(4) 11(6) 7(7) / / / 3(2) 3(3) 5 (5) / 1(1) 每个index 都有对应的parent 1 -> 2 -> 4 -> 8 2 -> 4 -> 8 3 -> 4 -> 8 4 -> 8 5 -> 6 ->8 7 -> 8 如何确定parent? index + least significant number 比如 6, '110', 最小1的数 就是 '10' 所以 6 + '10' (2) 就是8 所以我们更新一个数的时候,只需要把每个parent加上delta query 的时候只需要找到自己加上左边sibling 的sum 然后减去自己的num。如果找左边的sibling? index - least significant number 比如6, ('10') 左边的sibling 就是6 - 2 ('10') = 4 那么6 左边的sum 就是 10 + 11 - 6 = 15

334. Increasing Triplet Subsequence Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false. Input: nums = [2,1,5,0,4,6] Output: true Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.

这题最简单的方法就是 对每个数,找出左边最小的,然后找出右边最大的。看看有没有。但这个space capacity 是 0(n) space o(1) 的方法是类似于找最长的increasing subsequence那道题。 但此题只需要len为3所以不需要用list,只需要3 个placeholder。 e.x [1,6,0,4,5] placeholder : [1] => [1,6] => [0, 6 ] (注意这里不是说0,6 是一个sequencee而是说 最长的sequence的len依然为2.) => [0,4] => [0,4,5]

2246. Longest Path With Different Adjacent Characters You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1. You are also given a string s of length n, where s[i] is the character assigned to node i. Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them. Input: parent = [-1,0,0,1,1,2], s = "abacbe" Output: 3 Explanation: The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned. It can be proven that there is no longer path that satisfies the conditions. 0 (a) /. \ 2(a). 1(b) /. /. \ 5(e). 3(c). 4(b)

这题用bfs, 每一轮返回最长的child branch。每一轮计算一次path, 试图更新result (最长的path) 需要注意两点: 1. 每一个children都需要dfs, 因为result可能在children里。但如果child和parent的string相同,则不比较次轮的path,也不考虑返回这个child branch 2. 每一个node可能有多个children, 在计算path时, 只能计算top 2。 所以需要用max1 和max2, 而不是简单的把所有children的result加起来

480. Sliding Window Median The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. For examples, if arr = [2,3,4], the median is 3. For examples, if arr = [1,2,3,4], the median is (2 + 3) / 2 = 2.5. You are given an integer array nums and an integer k. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the median array for each window in the original array. Answers within 10-5 of the actual value will be accepted. Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 Output: [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000] Explanation: Window position Median --------------- ----- [1 3 -1] -3 5 3 6 7 1 1 [3 -1 -3] 5 3 6 7 -1 1 3 [-1 -3 5] 3 6 7 -1 1 3 -1 [-3 5 3] 6 7 3 1 3 -1 -3 [5 3 6] 7 5 1 3 -1 -3 5 [3 6 7] 6

这题用两个queues。high 和low,low是递减,high是递增。 high里每个数都比low大。这样就容易计算median。low 和high, 在加入新的数字之后需要balance。 因为是slide window,high 和low里有些数就会invalid (index小于等于left的)。对于这些数用lazy deletion。在计算median的时候,先把两个queue 前面的invalid的数全pop掉。 balance的时候注意不是比较两个queue的len, 而是比较两个queue里valid (total - invalid)的数的len。make sure valid count of low最多只能比high多一个。high 的invalid的数 小于等于low。 需要track low_invalid count 和high_invalid count. 然后需要一个index_position来记录每个index是在low里还是high里

189. Rotate Array Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]

首先 reverse 整个 list。这样的话index k 左边和右边的elements 都在正确的区域里。接下来就是把order弄正确。 以k为边界,分别reverse 左边和 右边的elements

845. Longest Mountain in Array You may recall that an array arr is a mountain array if and only if: arr.length >= 3 There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:arr[0] < arr[1] < ... < arr[i - 1] < arr[i]arr[i] > arr[i + 1] > ... > arr[arr.length - 1] Given an integer array arr, return the length of the longest subarray, which is a mountain. Return 0 if there is no mountain subarray. Input: arr = [2,1,4,7,3,2,5] Output: 5 Explanation: The largest mountain is [1,4,7,3,2] which has length 5.

首先loop thru 所有peaks: 找出i, arr[i-1] < arr[i] and arr[i] > arr[i+1] 然后对于每个peak, 分别向左右两边延伸。 直到左右两边不再下降。记录长度。 由于每个element最多被访问一次,所以是O(n)

1444. Number of Ways of Cutting a Pizza Given a rectangular pizza represented as a rows x cols matrix containing the following characters: 'A' (an apple) and '.' (empty cell) and given the integer k. You have to cut the pizza into k pieces using k-1 cuts. For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person. Return the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7. A * * A A A * * * There are 3 ways to cut this pizza => 2 vertical cut, 1 horizontal cut

首先为了能够快速的求出每个rectangle 的apple 的数量,先求出2d array presum (leetcode 304) 具体做法是首先先求出所有cell到左上角的rec的sum放到presum这个2d array 里。 然后求具体的rec的sum: 比如 [6, 3] [2, 0] 这个rec 就是 [3, 0, 1] [3] [5, 6, 3] - [5] - [3, 0, 1] + [3] [1, 2, 0] [1] 然后是用dfs + memo 每一轮的paramter是 (i,j, k)i, j 是剩下的pizza的top left cell。k 是剩下cut的次数 base case: 如果剩下cut 的次数是0,说明这是个成功的cut way, 因为每一轮我们都会查看剩下的pizza是否有apple,如果k 是0, 说明最后一个rec也有apple, return 1 每一轮, 横着切,从[i, m-1], 查看被切的rec和剩下的rec是不是都含有apple。是的话,继续往下切 竖着切 同理

304. Range Sum Query 2D - Immutable Given a 2D matrix matrix, handle multiple queries of the following type: Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). Implement the NumMatrix class: NumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix. int sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). You must design an algorithm where sumRegion works on O(1) time complexity. [[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]] numMatrix.sumRegion(2, 1, 4, 3); // return 8 (2, 1) is upper left corner. (4,3) is lower right corner

首先先求出所有cell到左上角的rec的sum放到presum这个2d array 里 求 [[3, 0] [5, 6]] 这个rec, 就是[6] + [3,5] + [3,0] - [3] 然后求具体的rec的sum: 比如 [6, 3] [2, 0] 这个rec 就是 [3, 0, 1] [3] [5, 6, 3] - [5] - [3, 0, 1] + [3] [1, 2, 0] [1]

2179. Count Good Triplets in an Array You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1]. A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2v as the index of the value v in nums2, then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z. Return the total number of good triplets. Input: nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3] Output: 4 Explanation: The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2).

(not complete)此题需要运用315. Count of Smaller Numbers After Self 首先,nums1 和 num2里的数值大小其实没有用因为我们只考虑顺序。所以我们先按照num1的顺序更新一下num2 e.x nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3] 更新过后的nums2 = [0,2,1,4,3] (就是num2里每个数排在nums1的第几位) 然后此题其实就转化成例遍nums2里每个数,找出它们左边比它小的个数,放到 prev_smaller list里,然后再里遍每个数找出右边比它大的个数, 放到 next_bigger list里。然后把每个prev_smaller[i] * next_bigger[j]加起来 Count of Smaller Numbers After Self 需要用到 BIT

70. Climbing Stairs You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

DP recursive method: dfs(cur - 1) + dfs(cur - 2) Base case: if cur == 0: return 1 if cur < 0: return 0

23. Merge k Sorted Lists You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it. Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted list: 1->1->2->3->4->4->5->6

Divide and concur

191. Number of 1 Bits Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). Input: n = 00000000000000000000000000001011 Output: 3 Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

n-1 will flip all bits after (include) the last significant bit n & (n-1) will remove the last significant bit (1)

43. Multiply Strings Input: num1 = "123", num2 = "456" Output: "56088" 1 <= num1.length, num2.length <= 200

一个digit一个digit的来 先乘,后加

846. Hand of Straights Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards. Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise. Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3 Output: true Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]

先sort 然后从最小的开始,找下一个连续的数然后remove

48. Rotate Image You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. 1,2,3 4,5,6 7,8,9 7,4,1 8,5,2 9,6,3

先上下swap, 然后在沿左上-右下的对角线swap why? 因为新位置一定是在顺时针的下一条边上。 例子:最下面那条边,target cell离最左边的距离是x 先把最下面的边和最上面的边互换。然后用圆规。圆心是左上角,半径是x => 与左边那条边的交点就是天target cell 移动90度之后的cell

670. Maximum Swap You are given an integer num. You can swap two digits at most once to get the maximum valued number. Return the maximum valued number you can get. Input: num = 2736 Output: 7236 Explanation: Swap the number 2 and the number 7. Input: num = 9973 Output: 9973 Explanation: No swap.

先找出每个点右边的最大值,记录最大值和index 然后loop through list, 如果list[i] == 这个点右边最大值 =》 good。这个数在正确的位置上 如果不是,把list[i] 跟这个点右边最大值换一下

76. Minimum Window Substring Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string. Input: s = "ADOBECODEBANC", t = "ABC" Output: "BANC" Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.

尽可能一个最小满足条件的区间

904. Fruit Into Baskets You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold. Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. Once you reach a tree with fruit that cannot fit in your baskets, you must stop. Given the integer array fruits, return the maximum number of fruits you can pick Input: fruits = [0,1,2,2] Output: 3 Explanation: We can pick from trees [1,2,2]. If we had started at the first tree, we would only pick from trees [0,1].

尽可能向右探索,一旦不满足条件,收缩左边

424. Longest Repeating Character Replacement You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. Return the length of the longest substring containing the same letter you can get after performing the above operations. Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa.

尽量向右探索,一旦不满足条件开始收缩

1060. Missing Element in Sorted Array Given an integer array nums which is sorted in ascending order and all of its elements are unique and given also an integer k, return the kth missing number starting from the leftmost number of the array. Input: nums = [4,7,9,10], k = 3 Output: 8 Explanation: The missing numbers are [5,6,8,...], hence the third missing number is 8.

1. Easiesy way is using two pointers. one pointers on range(min, max), one pointer is on nums. 2. Faster approach is using binary search Find the max val that satisfy the condition 4,(5), (6),7,8,(9),10,11, k = 3 Find the max val satisfy condition: previous missing value smaller than k It's 8 in the above example nums[mid] - nums[0] - mid < k Not <= here because the res will be 10 not 8 At the end, Once we find the max number that has previous missing value smaller than k. k (missing vlaue number) + index (index is non-missing value number) is the total distance from nums[0]

399. Evaluate Division You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable. You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?. Return the answers to all queries. If a single answer cannot be determined, return -1.0. Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction. Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]] Output: [6.00000,0.50000,-1.00000,1.00000,-1.00000] Explanation: Given: a / b = 2.0, b / c = 3.0 queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? return: [6.0, 0.5, -1.0, 1.0, -1.0 ]

BFS We can treat each equation as an edge, variables as nodes and value as weight, and build a weighted graph. Then for each queries (x, y), we try to find a path from x to y. 这题就是简单的a / b * b / c = a/c 没有a/b * c/b = ac/bb a/b = 2, b/c = 3 a -> b -> c: a-> : 6 2. 3

994. Rotting Oranges You are given an m x n grid where each cell can have one of three values: 0 representing an empty cell, 1 representing a fresh orange, or 2 representing a rotten orange. Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten. Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1. Input: grid = [[2,1,1],[1,1,0],[0,1,1]] Output: 4

BFS starting from each gate, queue will only have empty room Each time, compare the new path and the existing path for the empty room, update if it's shorter

286. Walls and Gates You are given an m x n grid rooms initialized with these three possible values. -1 A wall or an obstacle. 0 A gate. INF Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF. Input: rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]] Output: [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]

BFS starting from each gate, queue will only have empty room Each time, compare the new path and the existing path for the empty room, update if it's shorter

93. Restore IP Addresses A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245", "192.168.1.312" and "[email protected]" are invalid IP addresses. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order. Input: s = "25525511135" Output: ["255.255.11.135","255.255.111.35"]

Backtracking base case: if idx > 4: return if idx == 4 and not s: res.append(path[:-1]) return

1102. Path With Maximum Minimum Value Given an m x n integer matrix grid, return the maximum score of a path starting at (0, 0) and ending at (m - 1, n - 1) moving in the 4 cardinal directions. The score of a path is the minimum value in that path. For example, the score of the path 8 → 4 → 5 → 9 is 4. Input: grid = [[5,4,5], [1,2,6], [7,4,6]] Output: 4 Explanation: The path with the maximum score is highlighted in yellow. 5 -> 4 -> 5 -> 6 -> 6

Binary search + BFS left = min of all cells right = min(grid[0][0], grid[m-1][n-1]) 因为这两个cell是path必经的。所以我们考虑的值必须要小于等于这两个数 找满足条件的最大值 满足的条件: path 每一个cell都必须小于等于mid runtime: m*n*log(k) => k is the min(grid[0][0], grid[m-1][n-1])

863. All Nodes Distance K in Binary Tree Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node. You can return the answer in any order. Graph in pic Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2 Output: [7,4,1] Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1. Blue in answer, yellow is target

Build the graph first, and then use BFS to get the node with distance k When building the graph, graph[node].add(parent) graph[node].add(node.left) graph[node].add(node.right)

62. Unique Paths There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. The test cases are generated so that the answer will be less than or equal to 2 * 109

Classic (counting way) DF

854. K-Similar Strings Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2. Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar. Input: s1 = "abc", s2 = "bca" Output: 2 Explanation: The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc" --> "bac" --> "bca".

Clearly we need to use BFS for this question, but for each string, we just need to find the useful "next string" otherwise it will timeout Useful swap: 1. make sure the new position of s[i] -> j is not the same as s[j] -> no point to swap 2. make sure the new position of s[i] -> j is the same as s2[j]

981. Time Based Key-Value Store Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp. Implement the TimeMap class: TimeMap() Initializes the object of the data structure. void set(String key, String value, int timestamp) Stores the key key with the value value at the given time timestamp. String get(String key, int timestamp) Returns a value such that set was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the value associated with the largest timestamp_prev. If there are no values, it returns "". Input ["TimeMap", "set", "get", "get", "set", "get", "get"] [[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]] Output [null, null, "bar", "bar", null, "bar2", "bar2"] Explanation TimeMap timeMap = new TimeMap(); timeMap.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1. timeMap.get("foo", 1); // return "bar" timeMap.get("foo", 3); // return "bar", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar". timeMap.set("foo", "bar2", 4); // store the key "foo" and value "bar2" along with timestamp = 4. timeMap.get("foo", 4); // return "bar2" timeMap.get("foo", 5); // return "bar2"

Create a map {key: [(time, value)]} Find the biggest number that satisfies the condition.. mid <= target

767. Reorganize String Given a string s, rearrange the characters of s so that any two adjacent characters are not the same. Return any possible rearrangement of s or return "" if not possible. Input: s = "aab" Output: "aba" Input: s = "aaab" Output: ""

Create a queue that sort string's charaters with high frequence to low Pop the 2 most frequent chars evertime, and append to res. Add the chars back with decreased count At the end, if there char left in queue with count > 1. That means there's char with too much frequency, and we can't find any other char inserted in between, so no result. Let say first round we take char1, char2 second round we take char3, char4 We know that char 1 != char2 and char3 != 4 but how about char2 and char3? case 1: if char1 and char2 has the same frequency, char 3 and char 4 will still be char1 and char 2. case2: If char1 has more freq than char2, the next round char1 still has more freq than char2, so char3 won't be char2

332. Reconstruct Itinerary You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] Output: ["JFK","ATL","JFK","SFO","ATL","SFO"] Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order.

DFS Once an edge is used, pop it out

79. 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. Input: board = [["A","B","C","E"], ["S","F","C","S"], ["A","D","E","E"]], word = "ABCCED" Output: true

DFS Runtime: 3^L. L is the length of the word, each step we can have 3 options (don't count the direction where we came from) Space: L. L recursion call. maximun call stack

301. Remove Invalid Parentheses Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid. Return all the possible results. You may return the answer in any order. Input: s = "()())()" Output: ["(())()","()()()"]

DFS each round, decide options based on the "(" count and ")" count Potentially add MEMO

473. Matchsticks to Square You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time. Return true if you can make this square and false otherwise. Input: matchsticks = [1,1,2,2,2] Output: true Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.

DFS + MEMO 先求 edge: sum(matches) / 4 def dfs(l1, l2, l3, l4, i) 每一轮,matches[i] 可以选择放在l1, l2, l3, l4中一个 每一轮,如果l1 == l2== l3 == l4 == edge: return true

403. Frog Jump A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit. If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction. Input: stones = [0,1,3,5,6,8,12,17] Output: true Explanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.

DP

746. Min Cost Climbing Stairs You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index 0, or the step with index 1. Return the minimum cost to reach the top of the floor. Input: cost = [1,100,1,1,1,100,1,1,100,1] Output: 6

DP recursive method: cost[index] + min(dfs(index+1), dfs(index+2)) base case: index > len: return 0

115. Distinct Subsequences Given two strings s and t, return the number of distinct subsequences of s which equals t. A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., "ACE" is a subsequence of "ABCDE" while "AEC" is not). The test cases are generated so that the answer fits on a 32-bit signed integer. Input: s = "rabbbit", t = "rabbit" Output: 3 Explanation: As shown below, there are 3 ways you can generate "rabbit" from S. rabbbit rabbbit rabbbit

DP (counting way) if s[i] != t[j]: try next char in s if s[i] == t[j]: try next char in s, or take current char in s

322. Coin Change You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin. Input: coins = [1,2,5], amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1

DP 类似背包问题。可重复拿coin

309. Best Time to Buy and Sell Stock with Cooldown You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). Input: prices = [1,2,3,0,2] Output: 3 Explanation: transactions = [buy, sell, cooldown, buy, sell]

DP: (index, status) status: {0: no stock on hand}, {1: one stock on hand}, {2: just sold a stock} Tip: Do not pass amount to each layer.

202. Happy Number Write an algorithm to determine if a number n is happy. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits. Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy. Return true if n is a happy number, and false if not. Input: n = 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1

Easiest way is to use a set to make sure there is no visited number. If yes, return false The O(1) space solution is to use a slow and fast variable to detect if there is any cycle

73. Set Matrix Zeroes Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's. You must do it in place. 1,2, 3, 4 5,0, 7, 8 0,10,11,12 12,14,15,0 0,0,3,0 0,0,0,0 0,0,0,0 0,0,0,0

Easy solution: set1 store all column that need to be turn to 0 set2 store all rows that need to be turn to 0 Go through all cells, see if i or j is in set1/set2 O(1) space solution: Store if the row/column is 0 on the first cell. so the top and left sides will be stored if the row/column is 0. Special case is top left cell. It store both column and row's info. we want it to only store the info for the column, not for row, so we use r_0 to store the info for the first row

287. Find the Duplicate Number Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number. You must solve the problem without modifying the array nums and uses only constant extra space. Input: nums = [3,1,3,4,2] Output: 3

Example: 1,2,2,3,4,5 In this question, we don't need to sort the list because we already know the numbers are from 1 ~ len(nums) - 1 Do binary search on 1 ~ len(nums) - 1, and count the number <= mid. if the counter > mid => the duplicate is one the left side (include the final answer) e.x mid = 3, counter = 4, the duplicate is on the left side

41. First Missing Positive Given an unsorted integer array nums, return the smallest missing positive integer. You must implement an algorithm that runs in O(n) time and uses constant extra space. Input: nums = [3,4,-1,1] Output: 2 Explanation: 1 is in the array but 2 is missing.

Example: [3,4, 5,-1,1] First, mark all useless numbers as a irrelevant number (n+1) [3,4, 5,-1,1] => [3,4,5,6,1] Mark all other legit number as negative e.x when i == 0, mark nums[3-1] as negative, 5 => -5 if already marked as negative, skip [-3, 4, -5. 6, -1] Find the first non-negative number. The index is the first missing number

1020. Number of Enclaves You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell. A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid. Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves. Input: grid = [0,0,0, 0], [1, 0,1 ,0], [0,1, 1, 0], [0,0,0,0] Output: 3 Explanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.

From the edge cell that's 1, Use DFS to reach as far as possible along 1's, and update them to 0. The rest 1's are not reachable

45. Jump Game II Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index. Input: nums = [2,3,1,1,4] Output: 2 Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.

Greedy approach The idea is to maintain two pointers left and right, where left initialy set to be 0 and right set to be nums[0]. So points between 0 and nums[0] are the ones you can reach by using just 1 jump. Next, we want to find points I can reach using 2 jumps, so our new left will be set equal to right, and our new right will be set equal to the farest point we can reach by two jumps. which is:right = max(i + nums[i] for i in range(left, right + 1)

973. K Closest Points to Origin Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2). You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in). Input: points = [[3,3],[5,-1],[-2,4]], k = 2 Output: [[3,3],[-2,4]] Explanation: The answer [[-2,4],[3,3]] would also be accepted.

Implement a min heap: a priority queue. if the hits the size limit, compare the new point with the smallest element (the last element in the queue. In python, a priority queue[0] is guarentee to be the smallest one.), If the new point is greater than last element is the queue, pop the last element out and add the new point

42. Trapping Rain Water Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.

Keep track of max_left and max_right. if max_left < max_right => left += 1, res += max_left - height[left]...

300. Longest Increasing Subsequence Given an integer array nums, return the length of the longest strictly increasing subsequence. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. Input: nums = [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.

Loop through nums, if n is greater than all el in arr, append it If not, use binary search to replace the first number in arr that is greater than n Since it's replacement, length of arr won't change. And it won't hurt to replace with a smaller element on the same position

10. Regular Expression Matching Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: '.' Matches any single character.​​​​ '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). Input: s = "aa", p = "a*" Output: true Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". Input: s = "ab", p = ".*" Output: true Explanation: ".*" means "zero or more (*) of any character (.)".

MEMO + DFS base case: if i == len(s): return j == len(p) 1. if j < len(p)-1 and p[j+1] == '*' : return (match(i, j) and dfs(i+1, j)) or dfs(i, j+2) take more of previous | take 0 of previous 2. if match(i, j) => dfs(i+1, j+1) 3. Else: return False def match: s[i] == p[j] or p[j] == '.'

647. Palindromic Substrings Given a string s, return the number of palindromic substrings in it. A string is a palindrome when it reads the same backward as forward. A substring is a contiguous sequence of characters within the string. Input: s = "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c".

Memorize!! how to get all palindrome in one string Use two pointers. DP create a n*n 2-D arr to store if [start, end] is palidrome for end in (0,n): for start in (n-1, -1, -1) if s[start] != s[end] => don't care [start, end] is palidrome if [start+1, end-1] is palidrome that is arr[start][end] is true

53. Maximum Subarray Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A subarray is a contiguous part of an array. Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.

O(n) 维护一个cursum: cursum = max(n, cursum+n) 左边连续的最大的sum。如果n > cursum+n => 左边就没用了,start fresh with n

1483. Kth Ancestor of a Tree Node You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of ith node. The root of the tree is node 0. Find the kth ancestor of a given node. The kth ancestor of a tree node is the kth node in the path from that node to the root node. Implement the TreeAncestor class: TreeAncestor(int n, int[] parent) Initializes the object with the number of nodes in the tree and the parent array. int getKthAncestor(int node, int k) return the kth ancestor of the given node node. If there is no such ancestor, return -1. Input ["TreeAncestor", "getKthAncestor", "getKthAncestor", "getKthAncestor"] [[7, [-1, 0, 0, 1, 1, 2, 2]], [3, 1], [5, 2], [6, 3]] Output [null, 1, 0, -1] Explanation TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]); treeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3 treeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5 treeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor

Preorder + binary search Init: Use preorder traverse to find: Map: node => its level Map: levels => nodes belong to this level Map: graph => node's children Map: preorderIds: give each node a preorder ids, marked according to preorder getKthAncestor: 1. Use maps to find ancestor levels, and get ancestor candidates 2. Use binary search to find ancestor from candidates 0 1 2 3 4 5 6 E.x. node is 3. k is 1. so candidates are [1,2]. Based on the preorder Ids, ancestor preorder id must be smaller than the node. so 找满足条件的最大值

1352. Product of the Last K Numbers Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream. Implement the ProductOfNumbers class: ProductOfNumbers() Initializes the object with an empty stream. void add(int num) Appends the integer num to the stream. int getProduct(int k) Returns the product of the last k numbers in the current list. You can assume that always the current list has at least k numbers. The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing. Input ["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"] [[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]] Output [null,null,null,null,null,null,20,40,0,null,32] Explanation ProductOfNumbers productOfNumbers = new ProductOfNumbers(); productOfNumbers.add(3); // [3] productOfNumbers.add(0); // [3,0] productOfNumbers.add(2); // [3,0,2] productOfNumbers.add(5); // [3,0,2,5] productOfNumbers.add(4); // [3,0,2,5,4]

Presum store lastZeroIndex

491. Increasing Subsequences Given an integer array nums, return all the different possible increasing subsequences of the given array with at least two elements. You may return the answer in any order. The given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence. Input: nums = [4,6,7,7] Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]

Similar to getting subset In each position, we can't choose the same number twice. In each position (layer), initial a set, so make sure the candidates (for (index: len(nums))) are unique. Also the chosen one is greater than the previous chosen one. Other technique to deduplicate: 1. Sort a arr, and use index > 0 and nums[index] != nums[index-1] 2. Use counter. Loop through counter's keys These two are more space efficient, but do not work for this case because the order matter in this case

905. Sort Array By Parity Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers. Return any array that satisfies this condition. Input: nums = [3,1,2,4] Output: [2,4,3,1] Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

Similar to quick sort. Let odd_index be the next index of the last odd index, and even_index be the next index of the last even index. if nums[odd_index] is even. Swap nums[even_index] and nums[odd_index]. even_index ++, odd_index++. if nums[odd_index] is odd, odd_index++ This will make sure any index < even_index are even index, and index between old_index and even_index are odd

75. Sort Colors Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. You must solve this problem without using the library's sort function. Input: nums = [2,0,2,1,1,0] Output: [0,0,1,1,2,2]

Similar to the sort method we use for quick sort Use 3 pointers. i (red), j (white), k (Blue) i (red) is next cell of the last 0 j (white) is the next cell of the last 1 k (blue) is the prev cell of the first 2 if colors[j] == 0 => swap i and j; i++, j++ If colors[j] == 1 => j ++ if colors[j] == 2 => swap j and k; k--

853. Car Fleet There are n cars going to the same destination along a one-lane road. The destination is target miles away. You are given two integer array position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper at the same speed. The faster car will slow down to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return the number of car fleets that will arrive at the destination. Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3] Output: 3 Explanation: The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3.

Stack

268. Missing Number Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. Input: nums = [3,0,1] Output: 2 Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.

Store all number as bit If two lists are the same, After XOR, It will go back to 0 If not, the rest is the missing number

31. Next Permutation A permutation of an array of integers is an arrangement of its members into a sequence or linear order. For example, for arr = [1,2,3], the following are considered permutations of arr: [1,2,3], [1,3,2], [3,1,2], [2,3,1]. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). For example, the next permutation of arr = [1,2,3] is [1,3,2]. Similarly, the next permutation of arr = [2,3,1] is [3,1,2]. While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement. Given an array of integers nums, find the next permutation of nums. Input: nums = [1,2,3] Output: [1,3,2]

The algorithm We will use the sequence (0, 1, 2, 5, 3, 3, 0) as a running example. The key observation in this algorithm is that when we want to compute the next permutation, we must "increase" the sequence as little as possible. Just like when we count up using numbers, we try to modify the rightmost elements and leave the left side unchanged. For example, there is no need to change the first element from 0 to 1, because by changing the prefix from (0, 1) to (0, 2) we get an even closer next permutation. In fact, there is no need to change the second element either, which brings us to the next point

215. Kth Largest Element in an Array Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element. You must solve it in O(n) time complexity. Input: nums = [3,2,1,5,6,4], k = 2 Output: 5

The technique is quick select Find a random pivot point. Split the nums into 3 lists: greater than pivot, equal to pivot, and smaller than pivot Locate the list that contain the kth largest element, and recurse on that list This method will take log(n) time because averagely in each recursive round, we will reduce the list size by 2 n + n/2 + n/4 + ... + 1 = 2n - 1

167. Two Sum II 题目稍微改动一下 Sorted array, return all possible 2 nums that have sum equal to target. the array could have duplicated number Input: [1,2,3,3,4,5] Output: [[0,4], [1,3]]

Two pointer This solution has a key idea the result [[a, b], [c, d]] can only be in the order of a,c,d,b cannot be a,c,b,d or a,b,c,d because a+b = c+d

11. Container With Most Water You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Two pointer Why we movee the shorter one? because the current amount is the most the shorter one can get. The insider, the less amount it will get. Why leave the longer one? because its height hasn't been used yet.

695. Max Area of Island You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. The area of an island is the number of cells with a value 1 in the island. Return the maximum area of an island in grid. If there is no island, return 0.

Union Find

295. Find Median from Data Stream The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values. For example, for arr = [2,3,4], the median is 3. For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5. Implement the MedianFinder class: MedianFinder() initializes the MedianFinder object. void addNum(int num) adds the integer num from the data stream to the data structure. double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted. Input ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"] [[], [1], [2], [], [3], []] Output [null, null, null, 1.5, null, 2.0] Explanation MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr[1, 2, 3] medianFinder.findMedian(); // return 2.0

Use 2 priority queues queue1 store the first half, from big to small queue2 store the second half, from small to big implement a balance function to make sure len(queue1) == len(queue2) or len(queue1) == len(queue2) + 1

523. Continuous Subarray Sum Given an integer array nums and an integer k, return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k, or false otherwise. An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k. Input: nums = [23,2,4,6,7], k = 6 Output: true Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.

Use presum If presum[j] - presum[i] % k == 0 presum[j] % k = presum[i] % k Use a map record the first time we encounter presum[i] % k, if there is presum[j] % k in the map, return True Note that i < j- 1 because we need at least 2 elements in the subarray

489. Robot Room Cleaner You are controlling a robot that is located somewhere in a room. The room is modeled as an m x n binary grid where 0 represents a wall and 1 represents an empty slot. The robot starts at an unknown location in the room that is guaranteed to be empty, and you do not have access to the grid, but you can move the robot using the given API Robot. You are tasked to use the robot to clean the entire room (i.e., clean every empty cell in the room). The robot with the four given APIs can move forward, turn left, or turn right. Each turn is 90 degrees. When the robot tries to move into a wall cell, its bumper sensor detects the obstacle, and it stays on the current cell. Design an algorithm to clean the entire room using the following APIs: interface Robot { // returns true if next cell is open and robot moves into the cell. // returns false if next cell is obstacle and robot stays on the current cell. boolean move(); // Robot will stay on the same cell after calling turnLeft/turnRight. // Each turn will be 90 degrees. void turnLeft(); void turnRight(); // Clean the current cell. void clean(); }

Use DFS. 本题看上去是一个常规的DFS,但是难点在于机器人的运动是第一视角,DFS的回溯过程必须靠"手工"实现 x, y is tracking the position of robot (like the cursor) dx, dy is tracking the direction of robot any update with x, y, dx, dy need to come with action from robot In each layer, turn left 4 times. Each time, dfs into that direction if the next cell has not been visited At the end of each layer (4 directions has tried). the robot will face toward at the initial direction of where he enter the layer. After current layer is done, it will go back to previous layer. The cursor can move easily but the robot need to do it on commend. so we let robot turn back and move to the previous layer (previous cell) and turn back to the initial direction

87. Scramble String We can scramble a string s to get a string t using the following algorithm: If the length of the string is 1, stop. If the length of the string is > 1, do the following:Split the string into two non-empty substrings at a random index, i.e., if the string is s, divide it to x and y where s = x + y.Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step, s may become s = x + y or s = y + x.Apply step 1 recursively on each of the two substrings x and y. Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false. Input: s1 = "great", s2 = "rgeat" Output: true r | g | eat

Use DP Runtime: n^4 (n^2 * n^2) 每一轮,从loop through 每个index check 1. split: s1[:i], s2[:i] 和 s1[i:], s2[i:] 2. split + swap: s1[:i], s2[len(s1) - i:]和s1[i:], s2[:len(s1) - i]

329. Longest Increasing Path in a Matrix Given an m x n integers matrix, return the length of the longest increasing path in matrix. From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed). Input: matrix = [[9,9,4],[6,6,8],[2,1,1]] Output: 4 Explanation: The longest increasing path is [1, 2, 6, 9].

Use DP memo is (x, y) Starting from each cell, run dfs. Base case is when the cell has no increasing neibor. O(mn)

91. Decode Ways A message containing letters from A-Z can be encoded into numbers using the following mapping: 'A' -> "1" 'B' -> "2" ... 'Z' -> "26" To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: "AAJF" with the grouping (1 1 10 6) "KJF" with the grouping (11 10 6) Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". Given a string s containing only digits, return the number of ways to decode it. Input: s = "226" Output: 3 Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

Use DP (backtracking) Classic "counting ways" DP if s[index] is 0, return 0 because "0", or "0?" are invalid each layer has 2 options dfs(index+1) and dfs(index+2) if s[index:index + 2] <= 26

1584. Min Cost to Connect All Points You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi]. The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val. Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points. Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]] Output: 20

Use MST Add each points pair to graph Use MST algorithm, starting with random point, add its neibor to a priority queue if the neibor has not been used yet.

291. Word Pattern II Given a pattern and a string s, return true if s matches the pattern. A string s matches a pattern if there is some bijective mapping of single characters to strings such that if each character in pattern is replaced by the string it maps to, then the resulting string is s. A bijective mapping means that no two characters map to the same string, and no character maps to two different strings. Input: pattern = "abab", s = "redblueredblue" Output: true Explanation: One possible mapping is as follows: 'a' -> "red" 'b' -> "blue"

Use backtracking, not DP def dfs(index_p, index_s, _map, used) _map is a map between a char in pattern with a word used is a set that records the word that has been assigned to a char in pattern

136. Single Number Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space. Input: nums = [4,1,2,1,2] Output: 4

Use bit manipulation XOR: if two bits are equal => return 0

567. Permutation in String Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. In other words, return true if one of s1's permutations is the substring of s2. Input: s1 = "ab", s2 = "eidbaooo" Output: true Explanation: s2 contains one permutation of s1 ("ba").

Use fix size window on s2 and check if the numbers of each letter in the window are the same as the numbers in s1

493. Reverse Pairs Given an integer array nums, return the number of reverse pairs in the array. A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j]. Input: nums = [1,3,2,3,1] Output: 2 Explanation: The reverse pairs are: (1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1 (3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1

Use merge sort. 每一层merge之前,用two pointer 来count i > 2*j 的个数。 因为左边的arr 的index必然全部小于右边的arr的index。所以保证i < j。然后两个arr都是sort过的,所以用two pointer非常容易count

130. Surrounded Regions Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. board = [["X","X","X","X"], ["X","O","O","X"], ["X","X","O","X"], ["X","O","X","X"]] Output: [["X","X","X","X"], ["X","X","X","X"], ["X","X","X","X"], ["X","O","X","X"]]

Use rank to balance the union find tree Use dummy node to connect all cell related to 'O' on the edge Other option is DFS: O(N), each cell will be traversed once

826. Most Profit Assigning Work You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where: difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]). Every worker can be assigned at most one job, but one job can be completed multiple times. For example, if three workers attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, their profit is $0. Return the maximum profit we can achieve after assigning the workers to the jobs. Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7] Output: 100 Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately.

Use sort + two pointers sort worker and difficulty for each worker, explore the work that previous workers cannot do, and compare the most profit with the previous most profit cur_best is the work with most profit for the less-ability (previous) workers new worker just need to explore the work that previous workers cannot do

394. Decode String Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4]. The test cases are generated so that the length of the output will never exceed 105 Input: s = "3[a2[c]]" Output: "accaccacc"

Use stack

735. Asteroid Collision We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. Input: asteroids = [5,10,-5] Output: [5,10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide

Use stack

84. Largest Rectangle in Histogram Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram Example in pics*

Use stack to maintain a increasing bars' index 1. brute force:例遍每一个element,对于每一个element,往两边延伸,直到遇到比element小的height,然后这段区间就是对于element最大的面积。 2.用stack:用stack维护一个递增的height。对于新的element i,如果i的height比stack[-1]的height小,对于stack[-1], i 就是右边边界。左边边界就是stack里的倒数第2个数。

844. Backspace String Compare Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character. Note that after backspacing an empty text, the text will continue empty. Input: s = "ab##", t = "c#d#" Output: true Explanation: Both s and t become "".

Use two pointers, starting at each's string last index for each string, Use counter to record the number of '#' encountered, and if s[index] not '#' and counter > 0, index -= 1. If s[index] is not '#' and counter == 0 => means it's time to compare two string, s[index] != t[index], return False

5. Longest Palindromic Substring Given a string s, return the longest palindromic substring in s. Input: s = "babad" Output: "bab" Explanation: "aba" is also a valid answer.

Use two pointers. DP create a n*n 2-D arr to store if [start, end] is palidrome for end in (0,n): for start in (n-1, -1, -1) if s[start] != s[end] => don't care [start, end] is palidrome if [start+1, end-1] is palidrome that is arr[start][end] is true. 这道题也可以用Expand Around Center 方式,constant space。

453. Minimum Moves to Equal Array Elements Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment n - 1 elements of the array by 1 Input: nums = [1,2,3] Output: 3 Explanation: Only three moves are needed (remember each move increments two elements): [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]

Visualize the nums array as a bar graph where the value at each index is a bar of height nums[i]. Sort the array such that the bar at index 0 is minimum height and the bar at index N-1 is highest. Now in the first iteration, make a sequence of moves such that the height at index 0 is equal to height at index N-1. Clearly this takes nums[N-1]-nums[0] moves. After these moves, index N-2 will be the highest and index 0 will still be the minimum and nums[0] will be same as nums[N-1]. In the next iteration, lets do nums[N-2]-nums[0] moves. After this iteration, nums[0], nums[N-2], and nums[N-1] will be the same.

1570. Dot Product of Two Sparse Vectors Given two sparse vectors, compute their dot product. Implement class SparseVector: SparseVector(nums) Initializes the object with the vector nums dotProduct(vec) Compute the dot product between the instance of SparseVector and vec A sparse vector is a vector that has mostly zero values, you should store the sparse vector efficiently and compute the dot product between two SparseVector. Follow up: What if only one of the vectors is sparse? Input: nums1 = [1,0,0,2,3], nums2 = [0,3,0,4,0] Output: 8 Explanation: v1 = SparseVector(nums1) , v2 = SparseVector(nums2) v1.dotProduct(v2) = 1*0 + 0*3 + 0*0 + 2*4 + 3*0 = 8

Why using a hashset? because the array is sparse, we don't need to store entire array. Just the index: value that are not 0

4. Median of Two Sorted Arrays Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2.

a = [2,8,9,10] b = [1,3,4,11, 12] res = [1,2,3,4,8,9,10,11,12] size = 4 In total we need to take 4 numbers from both set left = 0, right = len(a) Note left and right here are not index, but the amount we take from a amount_a = (left + right) / 2, the number we get from a so size - amount_a is the the number we get from b _ _ _ l1 (amount_a - 1), r1 (amount_a), _ _ _ _ _ _ _ l2 (amount_b - 1), r2(amount_b), _ _ _ _ 我们想让 l1 和 l2 属于 res 的左半边 (或中间) r1 和 r2 属于res的右半边 所以 如果 l1 <= r2, l2 <= r1, 满足条件 如果 l1 > r2, 从a拿的太多,right = mid - 1 如果l2 > l1, 从a拿的太少,left = mid + 1 注意 l1 或 l2 = 0, r1 或 r1 = len 的情况

355. Design Twitter Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the 10 most recent tweets in the user's news feed. Implement the Twitter class: Twitter() Initializes your twitter object. void postTweet(int userId, int tweetId) Composes a new tweet with ID tweetId by the user userId. Each call to this function will be made with a unique tweetId. List<Integer> getNewsFeed(int userId) Retrieves the 10 most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be ordered from most recent to least recent. void follow(int followerId, int followeeId) The user with ID followerId started following the user with ID followeeId. void unfollow(int followerId, int followeeId) The user with ID followerId started unfollowing the user with ID followeeId.

getTimeline: Find top k elements in a list

There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2] Output: 3 Explanation: Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index.

if sum(gas) > sum(cost), it means there must be a solution & guarentee to be unique (based on question) for 0 to n, if we can find the first index (x) that goes to the end without negative balance Why can't we start at the later index like x+1 if x+1 can also go to the end? Because gas[x] - cost[x] is positive. Always good to have a positive gas from the previous index

15. 3Sum Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets. Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]]

transform it to 2sum The hardest part of this question is deduplicate we sort the list first [position1, position2, position3] 避免position1 有重复: if i > 0 and nums[i-1] == nums[i]: continue 避免position3 有重复: while j+1 < len(nums) and nums[j+1] == nums[j]: j+=1 position2 不会有重复因为是个set 为什么position3 不能像position1 一样 用 if nums[i-1] == nums[i]: continue 因为2sum那个loop是position2 和position3 共用的

296. Best Meeting Point Given an m x n binary grid grid where each 1 marks the home of one friend, return the minimal total travel distance. The total travel distance is the sum of the distances between the houses of the friends and the meeting point. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.

找所有x 的中位数 找所有y的中位数 更好的方法是用quick select k = len(arr) // 2 - 因为是找中位数 找pivot, 把所有小于pivot的放左边,大于pivot的放右边。然后看 左边的个数是不是等于k-1, 如果是,说明已经是中位数 如果左边的个数大于k-1, 说明中位数在左边的list里,更新low,high,然后继续call quickselect。 如果左边的个数小于k-1, 说明中位数在右边的list里。更新low, high, 还有k, 然后继续call quickselect。

475. Heaters Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses. Notice that all the heaters follow your radius standard, and the warm radius will the same. Input: houses = [1,2,3,4], heaters = [1,4] Output: 1 Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.

最佳的binary search方案是:遍历所有houses[i],记录其位置pos,在有序的heaters序列里找到第一个大于(等于)pos的迭代器元素it,判断*it和*(it-1)与pos的距离,较小值就是该house[i]的最小供暖半径。 寻找it的方法用lower_bound函数。 auto it = lower_bound(heaters.begin(),heaters.end(),pos); 特别注意当it==heaters.begin()或it==heaters.end()时的特例。说明houses[i]在所有heaters的一边,所以只需要计算单边的半径距离。

1268. Search Suggestions System You are given an array of strings products and a string searchWord. Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products. Return a list of lists of the suggested products after each character of searchWord is typed.

次题有2种做法。一种是用binary search. runtime Time: O((n + L) * m * logn), space: O(L * m) - - including return list ans, but excluding space cost of sorting, where m = average length of products, n = products.length, L = searchWord.length(). 另一种方法就是用trie,每一个node寸一个suggestion list

169. Majority Element Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. Input: nums = [2,2,1,1,1,2,2] Output: 2

此题因为肯定会有一个结果 (某个出现次数次数大于n//2),所以可以用一个counter来记录某个数出现的次数,遇到不同的数就减一,相同数加一。counter变成0后下一个数就是candidate

532. K-diff Pairs in an Array Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: 0 <= i, j < nums.length i != j nums[i] - nums[j] == k Input: nums = [3,1,4,1,5], k = 2 Output: 2 Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of unique pairs.

此题难点是去重 先把list 转化成counter 分情况讨论, 如果k 是0, 只需要计算有多少map 的key 的count是大于1 的 如果k不是0,就loop thru map的key, 然后类似于2 sum的做法

668. Kth Smallest Number in Multiplication Table Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed). Given three integers m, n, and k, return the kth smallest element in the m x n multiplication table. Input: m = 3, n = 3, k = 5 Output: 3 Explanation: The 5th smallest number is 3.

此题非常巧妙地用到了二分(值)查找的思想。 初始状态left=1,right=n*m,每次确定mid之后,计算乘法表里小于等于mid的数目。这只要按照行i=1:m进行遍历就行,count+=min(mid/i,n)。(注意有一个上限n) 如果得到的count<k,那么显然这个mid太小,不满足条件,需要上调左边界,即left=mid+1;反之,count>=k的话,则说明这个mid可能太大但也可能正好就是答案(例如有很多重复的mid),无法确定,因此可以将其纳入右边界(闭区间),即right=mid,(因为答案不可能比mid更大了)。 这种二分逼近得到的结果 x 是什么呢?得到的是乘法表里小于等于x的元素个数不少于k的、且最小的那个数字。这其实就是待求的第k个元素。 但注意有一个问题需要考虑,最终左右指针相遇得到这个数x一定会是出现在乘法表里的吗?表面上看不出来,但答案是肯定的。这是因为满足"乘法表里小于等于x的元素个数不少于k的",这样的x可能会有很多,但最小的那个一定是出现在乘法表里的。 PS: 本题本质上和 378. Kth Smallest Element in a Sorted Matrix一模一样。

36. Valid Sudoku Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without repetition. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition. Note: A Sudoku board (partially filled) could be valid but is not necessarily solvable. Only the filled cells need to be validated according to the mentioned rules.

用3个set 另一种方法只需要1个set: if (!seen.add(number + " in row " + i) || !seen.add(number + " in column " + j) || !seen.add(number + " in block " + i/3 + "-" + j/3))

283. Move Zeroes Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0]

用一个counter记录zero数量。把每个非0的数往右移当前counter的数量

378. Kth Smallest Element in a Sorted Matrix Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. You must find a solution with a memory complexity better than O(n2). Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 Output: 13 Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13

解法1 矩阵的规律是:如果matrix[i][j]不是最小的,则matrix[i+1][j]和matrix[i][j+1]就都不用考虑。或者matrix[i][j]是最小的,则matrix[i+1][j]和matrix[i][j+1]就能进如考虑范围。 所以类似BFS的算法,设计一个小顶堆的Priority_queue,每次出列最小值之后,将最小值邻接的matrix[i+1][j]和matrix[i][j+1]加入这个队列会自动排序。当出列k个数之后就是答案。 解法2 (N*log(Max-Min)) Space (O(1)) 以上的解法在新的测试集下会非常慢.更优的方法是binary search. 显然,答案的上限是matrix[0][0],下限是matrix[N-1][N-1].对于这个区间的任意一个x,我们可以计算出这个矩阵里小于等于x的元素有多少,定义为smallerOrEqual(x).如果smallerOrEqual(x)<k,说明这个k太小了不是想要的答案,应该往上调整,所以left=x+1.反之smallerOrEqual(x)>=k,说明k可能是答案,但可以再缩小一点试一试,因此right=x. (当然,更直接一点,其实如果直接得到smallerOrEqual(x)==k的话就已经说明k就是答案了) 那么如果写这个smallerOrEqual(x)呢?这个思路其实和 240. Search a 2D Matrix II 非常相似.对于这种行列都排序的矩阵,我们可以从左下角(其实右上角也可以)出发,遇到matrix[i][j]<=x,说明从(i,j)之上的整列都smallerOrEqual(x),于是就可以往右移动一列. 否则的话,我们就往上移动一行. 这样直至我们走出这个矩阵,走过的路径就自动将矩阵划分为了左上和右下两个部分,就是以smallerOrEqual(x)为分界的. 这个性质非常好用,请大家多多练习.(从左下角出发或者从右上角出发). 1 5 9 9 10 13 12 13 15 1. k = 4. mid = 9 , 小于等于9的有4个 >= k , meet condition 2. k = 3 mid = 9, 小雨等于9 的有4个 >= k, meet condition

638. Shopping Offers In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy. You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer. Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want. Input: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2] Output: 14 Explanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively. In special offer 1, you can pay $5 for 3A and 0B In special offer 2, you can pay $10 for 1A and 2B. You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.

设计递归函数dfs(state),其中state表示还有哪些物品没有采购,返回的值表示采购完这些物品的最少代价。 在dfs(state)里,为我们尝试每一种合法的offer,将state更新后递归处理。我们取所有尝试中代价最小的结果,并记录在memo[state]里面。 需要注意的细节: 有些offer是不合算的,可以提前从special里排除掉; 在dfs(state)里,除了尝试offer,还可以直接从prices里面按原价采购每一件物品。

135. Candy There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. Return the minimum number of candies you need to have to distribute the candies to the children. Input: ratings = [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. Input: ratings = [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.

这是一道经典的贪心法。 我们令f[0]=1,然后从左往右扫一遍,保证f[i]与f[i-1]比较时符合要求,即f[i]=max(1, f[i-1]+1 if rating[i]>rating[i-1]). 这个操作更新了f[i]的下限,是f[i]合法的一个必要条件。言下之意就是说,f[i]不保证是一个合法的分配,但f[i]不能更小了。 然后从右往左扫一遍,保证f[i]与f[i+1]比较时符合要求,即f[i]=max(f[i], f[i+1]+1 if rating[i]>rating[i+1]). 这个操作同样进一步更新了f[i]的下限,即f[i]不能更小了。 以上两步操作都是必要条件,找到了f[i]的一个下限。但是这个下限本身是否就是符合要求的方案呢?事实上就是如此。上面两轮two pass保证了每个小朋友与相邻两个人做比较时都是公平的。换句话说,任意两个相邻小朋友之间的比较和分配都是公平的。所以此时f[i]的分布同时也是一个充分解。

373. Find K Pairs with Smallest Sums You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. Define a pair (u, v) which consists of one element from the first array and one element from the second array. Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums. Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3 Output: [[1,2],[1,4],[1,6]] Explanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]

这道题如果用min heap 太浪费了。因为不需要例遍所有情况。因为两个list都已经sort了 用bfs + priority queue来做。从(0, 0)开始, 把neibor放进queue里。(i, j+1), (i+1, j). 注意维护一个seen set。因为可能会遇到已经用过的case e.x 有两个方式可以到达 (1, 1) 1. (1,0) => (1,1) 2. (0,1) => (1,1)

55. Jump Game You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. Input: nums = [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. Input: nums = [3,2,1,0,4] Output: false Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.

这道题正常情况应该都是true,因为即使一步一步走,也能到最后一个。除非遇到0,而且不能跳过。 如果用dp 是n^2,然后memorry会超 o(n)的方法: Concept - Instead of starting from the first element of the Array, think if you have already reached the end, Now check from where have you reached there. In the end your destination should be equal to 0 as we needed to start from first index 如果source到不了destination,那它也肯定到不了destination-1。所以source不需要回头看


Conjuntos de estudio relacionados

FON Chapter 29 - Infection Prevention and the Nursing Process

View Set

Macroeconomics 2301 Frank Granack chapter 1,2,3

View Set

Adaptive Learning Assignment - Social Media Marketing

View Set

Chapter 14: Nursing Management During Labor and Birth

View Set

A Look at the Fast-Food Industry by Eric Schlosser & The Poetry of Physics

View Set

Moduel 3-B (cognative psychology)

View Set

Unit2 Chap3 - How the state government works

View Set