Team Ai
Apppublic

rishabhpr/codingprepdemo

sourceHugging Facemitupdated 2y agoView on Hugging Face
4likes
question_metadata.csv4079 linesDownload Raw Back to root
1company,questionId,questionName,difficulty level,Tags,Content2LinkedIn,364,Nested List Weight Sum II,Med,"Stack, Depth-First Search, Breadth-First Search",3LinkedIn,432,All O`one Data Structure,Hard,"Hash Table, Linked List, Design, Doubly-Linked List","Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts. Implement the AllOne class: AllOne() Initializes the object of the data structure. inc(String key) Increments the count of the string key by 1. If key does not exist in the data structure; insert it with count 1. dec(String key) Decrements the count of the string key by 1. If the count of key is 0 after the decrement; remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement. getMaxKey() Returns one of the keys with the maximal count. If no element exists; return an empty string """". getMinKey() Returns one of the keys with the minimum count. If no element exists; return an empty string """". Note that each function must run in O(1) average time complexity. Example 1: Input [""AllOne""; ""inc""; ""inc""; ""getMaxKey""; ""getMinKey""; ""inc""; ""getMaxKey""; ""getMinKey""] [[]; [""hello""]; [""hello""]; []; []; [""leet""]; []; []] Output [null; null; null; ""hello""; ""hello""; null; ""hello""; ""leet""] Explanation AllOne allOne = new AllOne(); allOne.inc(""hello""); allOne.inc(""hello""); allOne.getMaxKey(); // return ""hello"" allOne.getMinKey(); // return ""hello"" allOne.inc(""leet""); allOne.getMaxKey(); // return ""hello"" allOne.getMinKey(); // return ""leet"" Constraints: 1 <= key.length <= 10 key consists of lowercase English letters. It is guaranteed that for each call to dec; key is existing in the data structure. At most 5 * 104 calls will be made to inc; dec; getMaxKey; and getMinKey."4LinkedIn,34,Find First and Last Position of Element in Sorted Array,Med,"Array, Binary Search",Given an array of integers nums sorted in non-decreasing order; find the starting and ending position of a given target value. If target is not found in the array; return [-1; -1]. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [5;7;7;8;8;10]; target = 8 Output: [3;4] Example 2: Input: nums = [5;7;7;8;8;10]; target = 6 Output: [-1;-1] Example 3: Input: nums = []; target = 0 Output: [-1;-1] Constraints: 0 <= nums.length <= 105 -109 <= nums[i] <= 109 nums is a non-decreasing array. -109 <= target <= 1095LinkedIn,716,Max Stack,Hard,"Linked List, Stack, Design, Doubly-Linked List, Ordered Set",6LinkedIn,254,Factor Combinations,Med,Backtracking,7LinkedIn,277,Find the Celebrity,Med,"Two Pointers, Graph, Interactive",8LinkedIn,360,Sort Transformed Array,Med,"Array, Math, Two Pointers, Sorting",9LinkedIn,1650,Lowest Common Ancestor of a Binary Tree III,Med,"Hash Table, Bit Manipulation, Tree, Depth-First Search",10LinkedIn,17,Letter Combinations of a Phone Number,Med,"Hash Table, String, Backtracking","Given a string containing digits from 2-9 inclusive; return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. Example 1: Input: digits = ""23"" Output: [""ad"";""ae"";""af"";""bd"";""be"";""bf"";""cd"";""ce"";""cf""] Example 2: Input: digits = """" Output: [] Example 3: Input: digits = ""2"" Output: [""a"";""b"";""c""] Constraints: 0 <= digits.length <= 4 digits[i] is a digit in the range ['2'; '9']."11LinkedIn,20,Valid Parentheses,Easy,"String, Stack","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. Example 1: Input: s = ""()"" Output: true Example 2: Input: s = ""()[]{}"" Output: true Example 3: Input: s = ""(]"" Output: false Example 4: Input: s = ""([])"" Output: true Constraints: 1 <= s.length <= 104 s consists of parentheses only '()[]{}'."12LinkedIn,152,Maximum Product Subarray,Med,"Array, Dynamic Programming",Given an integer array nums; find a subarray that has the largest product; and return the product. The test cases are generated so that the answer will fit in a 32-bit integer. Example 1: Input: nums = [2;3;-2;4] Output: 6 Explanation: [2;3] has the largest product 6. Example 2: Input: nums = [-2;0;-1] Output: 0 Explanation: The result cannot be 2; because [-2;-1] is not a subarray. Constraints: 1 <= nums.length <= 2 * 104 -10 <= nums[i] <= 10 The product of any subarray of nums is guaranteed to fit in a 32-bit integer.13LinkedIn,156,Binary Tree Upside Down,Med,"Tree, Depth-First Search, Binary Tree",14LinkedIn,200,Number of Islands,Med,"Array, Depth-First Search, Breadth-First Search, Union Find, Matrix","Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water); return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: grid = [ [""1"";""1"";""1"";""1"";""0""]; [""1"";""1"";""0"";""1"";""0""]; [""1"";""1"";""0"";""0"";""0""]; [""0"";""0"";""0"";""0"";""0""] ] Output: 1 Example 2: Input: grid = [ [""1"";""1"";""0"";""0"";""0""]; [""1"";""1"";""0"";""0"";""0""]; [""0"";""0"";""1"";""0"";""0""]; [""0"";""0"";""0"";""1"";""1""] ] Output: 3 Constraints: m == grid.length n == grid[i].length 1 <= m; n <= 300 grid[i][j] is '0' or '1'."15LinkedIn,205,Isomorphic Strings,Easy,"Hash Table, String","Given two strings s and t; determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character; but a character may map to itself. Example 1: Input: s = ""egg""; t = ""add"" Output: true Explanation: The strings s and t can be made identical by: Mapping 'e' to 'a'. Mapping 'g' to 'd'. Example 2: Input: s = ""foo""; t = ""bar"" Output: false Explanation: The strings s and t can not be made identical as 'o' needs to be mapped to both 'a' and 'r'. Example 3: Input: s = ""paper""; t = ""title"" Output: true Constraints: 1 <= s.length <= 5 * 104 t.length == s.length s and t consist of any valid ascii character."16LinkedIn,210,Course Schedule II,Med,"Depth-First Search, Breadth-First Search, Graph, Topological Sort",There are a total of numCourses courses you have to take; labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai; bi] indicates that you must take course bi first if you want to take course ai. For example; the pair [0; 1]; indicates that to take course 0 you have to first take course 1. Return the ordering of courses you should take to finish all courses. If there are many valid answers; return any of them. If it is impossible to finish all courses; return an empty array. Example 1: Input: numCourses = 2; prerequisites = [[1;0]] Output: [0;1] Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0;1]. Example 2: Input: numCourses = 4; prerequisites = [[1;0];[2;0];[3;1];[3;2]] Output: [0;2;1;3] Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0;1;2;3]. Another correct ordering is [0;2;1;3]. Example 3: Input: numCourses = 1; prerequisites = [] Output: [0] Constraints: 1 <= numCourses <= 2000 0 <= prerequisites.length <= numCourses * (numCourses - 1) prerequisites[i].length == 2 0 <= ai; bi < numCourses ai != bi All the pairs [ai; bi] are distinct.17LinkedIn,215,Kth Largest Element in an Array,Med,"Array, Divide and Conquer, Sorting, Heap (Priority Queue), Quickselect",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. Can you solve it without sorting? Example 1: Input: nums = [3;2;1;5;6;4]; k = 2 Output: 5 Example 2: Input: nums = [3;2;3;1;2;4;5;5;6]; k = 4 Output: 4 Constraints: 1 <= k <= nums.length <= 105 -104 <= nums[i] <= 10418LinkedIn,235,Lowest Common Ancestor of a Binary Search Tree,Med,"Tree, Depth-First Search, Binary Search Tree, Binary Tree",Given a binary search tree (BST); find the lowest common ancestor (LCA) node of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Example 1: Input: root = [6;2;8;0;4;7;9;null;null;3;5]; p = 2; q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6. Example 2: Input: root = [6;2;8;0;4;7;9;null;null;3;5]; p = 2; q = 4 Output: 2 Explanation: The LCA of nodes 2 and 4 is 2; since a node can be a descendant of itself according to the LCA definition. Example 3: Input: root = [2;1]; p = 2; q = 1 Output: 2 Constraints: The number of nodes in the tree is in the range [2; 105]. -109 <= Node.val <= 109 All Node.val are unique. p != q p and q will exist in the BST.19LinkedIn,339,Nested List Weight Sum,Med,"Depth-First Search, Breadth-First Search",20LinkedIn,341,Flatten Nested List Iterator,Med,"Stack, Tree, Depth-First Search, Design, Queue, Iterator",You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. Implement the NestedIterator class: NestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested list nestedList. int next() Returns the next integer in the nested list. boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise. Your code will be tested with the following pseudocode: initialize iterator with nestedList res = [] while iterator.hasNext() append iterator.next() to the end of res return res If res matches the expected flattened list; then your code will be judged as correct. Example 1: Input: nestedList = [[1;1];2;[1;1]] Output: [1;1;2;1;1] Explanation: By calling next repeatedly until hasNext returns false; the order of elements returned by next should be: [1;1;2;1;1]. Example 2: Input: nestedList = [1;[4;[6]]] Output: [1;4;6] Explanation: By calling next repeatedly until hasNext returns false; the order of elements returned by next should be: [1;4;6]. Constraints: 1 <= nestedList.length <= 500 The values of the integers in the nested list is in the range [-106; 106].21LinkedIn,380,Insert Delete GetRandom O(1),Med,"Array, Hash Table, Math, Design, Randomized","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. Example 1: Input [""RandomizedSet""; ""insert""; ""remove""; ""insert""; ""getRandom""; ""remove""; ""insert""; ""getRandom""] [[]; [1]; [2]; [2]; []; [1]; [2]; []] Output [null; true; false; true; 2; true; false; 2] Explanation RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set; returns true. Set now contains [1;2]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set; returns true. Set now contains [2]. randomizedSet.insert(2); // 2 was already in the set; so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set; getRandom() will always return 2. Constraints: -231 <= val <= 231 - 1 At most 2 * 105 calls will be made to insert; remove; and getRandom. There will be at least one element in the data structure when getRandom is called."22LinkedIn,611,Valid Triangle Number,Med,"Array, Two Pointers, Binary Search, Greedy, Sorting",Given an integer array nums; return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. Example 1: 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 Example 2: Input: nums = [4;2;3;4] Output: 4 Constraints: 1 <= nums.length <= 1000 0 <= nums[i] <= 100023LinkedIn,489,Robot Room Cleaner,Hard,"Array, Math, Dynamic Programming, Combinatorics","Bob is standing at cell (0; 0); and he wants to reach destination: (row; column). He can only travel right and down. You are going to help Bob by providing instructions for him to reach destination. The instructions are represented as a string; where each character is either: 'H'; meaning move horizontally (go right); or 'V'; meaning move vertically (go down). Multiple instructions will lead Bob to destination. For example; if destination is (2; 3); both ""HHHVV"" and ""HVHVH"" are valid instructions. However; Bob is very picky. Bob has a lucky number k; and he wants the kth lexicographically smallest instructions that will lead him to destination. k is 1-indexed. Given an integer array destination and an integer k; return the kth lexicographically smallest instructions that will take Bob to destination. Example 1: Input: destination = [2;3]; k = 1 Output: ""HHHVV"" Explanation: All the instructions that reach (2; 3) in lexicographic order are as follows: [""HHHVV""; ""HHVHV""; ""HHVVH""; ""HVHHV""; ""HVHVH""; ""HVVHH""; ""VHHHV""; ""VHHVH""; ""VHVHH""; ""VVHHH""]. Example 2: Input: destination = [2;3]; k = 2 Output: ""HHVHV"" Example 3: Input: destination = [2;3]; k = 3 Output: ""HHVVH"" Constraints: destination.length == 2 1 <= row; column <= 15 1 <= k <= nCr(row + column; row); where nCr(a; b) denotes a choose b​​​​​."24LinkedIn,886,Possible Bipartition,Med,"String, Stack","Given a balanced parentheses string s; return the score of the string. The score of a balanced parentheses string is based on the following rule: ""()"" has score 1. AB has score A + B; where A and B are balanced parentheses strings. (A) has score 2 * A; where A is a balanced parentheses string. Example 1: Input: s = ""()"" Output: 1 Example 2: Input: s = ""(())"" Output: 2 Example 3: Input: s = ""()()"" Output: 2 Constraints: 2 <= s.length <= 50 s consists of only '(' and ')'. s is a balanced parentheses string."25LinkedIn,1004,Max Consecutive Ones III,Med,"Math, Dynamic Programming, Memoization","Given a single positive integer x; we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1; op2; etc. is either addition; subtraction; multiplication; or division (+; -; *; or /). For example; with x = 3; we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression; we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happen before addition and subtraction. It is not allowed to use the unary negation operator (-). For example; ""x - x"" is a valid expression as it only uses subtraction; but ""-x + x"" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used. Example 1: Input: x = 3; target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5; target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100; target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations. Constraints: 2 <= x <= 100 1 <= target <= 2 * 108"26Backend,432,All O`one Data Structure,Hard,"Hash Table, Linked List, Design, Doubly-Linked List","Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts. Implement the AllOne class: AllOne() Initializes the object of the data structure. inc(String key) Increments the count of the string key by 1. If key does not exist in the data structure; insert it with count 1. dec(String key) Decrements the count of the string key by 1. If the count of key is 0 after the decrement; remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement. getMaxKey() Returns one of the keys with the maximal count. If no element exists; return an empty string """". getMinKey() Returns one of the keys with the minimum count. If no element exists; return an empty string """". Note that each function must run in O(1) average time complexity. Example 1: Input [""AllOne""; ""inc""; ""inc""; ""getMaxKey""; ""getMinKey""; ""inc""; ""getMaxKey""; ""getMinKey""] [[]; [""hello""]; [""hello""]; []; []; [""leet""]; []; []] Output [null; null; null; ""hello""; ""hello""; null; ""hello""; ""leet""] Explanation AllOne allOne = new AllOne(); allOne.inc(""hello""); allOne.inc(""hello""); allOne.getMaxKey(); // return ""hello"" allOne.getMinKey(); // return ""hello"" allOne.inc(""leet""); allOne.getMaxKey(); // return ""hello"" allOne.getMinKey(); // return ""leet"" Constraints: 1 <= key.length <= 10 key consists of lowercase English letters. It is guaranteed that for each call to dec; key is existing in the data structure. At most 5 * 104 calls will be made to inc; dec; getMaxKey; and getMinKey."27Backend,364,Nested List Weight Sum II,Med,"Stack, Depth-First Search, Breadth-First Search",28Backend,187,Repeated DNA Sequences,Med,"Hash Table, String, Bit Manipulation, Sliding Window, Rolling Hash, Hash Function","The DNA sequence is composed of a series of nucleotides abbreviated as 'A'; 'C'; 'G'; and 'T'. For example; ""ACGAATTCCG"" is a DNA sequence. When studying DNA; it is useful to identify repeated sequences within the DNA. Given a string s that represents a DNA sequence; return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order. Example 1: Input: s = ""AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"" Output: [""AAAAACCCCC"";""CCCCCAAAAA""] Example 2: Input: s = ""AAAAAAAAAAAAA"" Output: [""AAAAAAAAAA""] Constraints: 1 <= s.length <= 105 s[i] is either 'A'; 'C'; 'G'; or 'T'."29Backend,366,Find Leaves of Binary Tree,Med,"Tree, Depth-First Search, Binary Tree",30Backend,23,Merge k Sorted Lists,Hard,"Linked List, Divide and Conquer, Heap (Priority Queue), Merge Sort",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. Example 1: 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 Example 2: Input: lists = [] Output: [] Example 3: Input: lists = [[]] Output: [] Constraints: k == lists.length 0 <= k <= 104 0 <= lists[i].length <= 500 -104 <= lists[i][j] <= 104 lists[i] is sorted in ascending order. The sum of lists[i].length will not exceed 104.31Backend,47,Permutations II,Med,"Array, Backtracking",Given a collection of numbers; nums; that might contain duplicates; return all possible unique permutations in any order. Example 1: Input: nums = [1;1;2] Output: [[1;1;2]; [1;2;1]; [2;1;1]] Example 2: Input: nums = [1;2;3] Output: [[1;2;3];[1;3;2];[2;1;3];[2;3;1];[3;1;2];[3;2;1]] Constraints: 1 <= nums.length <= 8 -10 <= nums[i] <= 1032Backend,152,Maximum Product Subarray,Med,"Array, Dynamic Programming",Given an integer array nums; find a subarray that has the largest product; and return the product. The test cases are generated so that the answer will fit in a 32-bit integer. Example 1: Input: nums = [2;3;-2;4] Output: 6 Explanation: [2;3] has the largest product 6. Example 2: Input: nums = [-2;0;-1] Output: 0 Explanation: The result cannot be 2; because [-2;-1] is not a subarray. Constraints: 1 <= nums.length <= 2 * 104 -10 <= nums[i] <= 10 The product of any subarray of nums is guaranteed to fit in a 32-bit integer.33Backend,671,Second Minimum Node In a Binary Tree,Easy,"Tree, Depth-First Search, Binary Tree",Given a non-empty special binary tree consisting of nodes with the non-negative value; where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes; then this node's value is the smaller value among its two sub-nodes. More formally; the property root.val = min(root.left.val; root.right.val) always holds. Given such a binary tree; you need to output the second minimum value in the set made of all the nodes' value in the whole tree. If no such second minimum value exists; output -1 instead. Example 1: Input: root = [2;2;5;null;null;5;7] Output: 5 Explanation: The smallest value is 2; the second smallest value is 5. Example 2: Input: root = [2;2;2] Output: -1 Explanation: The smallest value is 2; but there isn't any second smallest value. Constraints: The number of nodes in the tree is in the range [1; 25]. 1 <= Node.val <= 231 - 1 root.val == min(root.left.val; root.right.val) for each internal node of the tree.34Backend,1644,Lowest Common Ancestor of a Binary Tree II,Med,"String, Greedy","Given a string s of lowercase letters; you need to find the maximum number of non-empty substrings of s that meet the following conditions: The substrings do not overlap; that is for any two substrings s[i..j] and s[x..y]; either j < x or i > y is true. A substring that contains a certain character c must also contain all occurrences of c. Find the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings; return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length. Notice that you can return the substrings in any order. Example 1: Input: s = ""adefaddaccc"" Output: [""e"";""f"";""ccc""] Explanation: The following are all the possible substrings that meet the conditions: [ ""adefaddaccc"" ""adefadda""; ""ef""; ""e""; ""f""; ""ccc""; ] If we choose the first string; we cannot choose anything else and we'd get only 1. If we choose ""adefadda""; we are left with ""ccc"" which is the only one that doesn't overlap; thus obtaining 2 substrings. Notice also; that it's not optimal to choose ""ef"" since it can be split into two. Therefore; the optimal way is to choose [""e"";""f"";""ccc""] which gives us 3 substrings. No other solution of the same number of substrings exist. Example 2: Input: s = ""abbaccd"" Output: [""d"";""bb"";""cc""] Explanation: Notice that while the set of substrings [""d"";""abba"";""cc""] also has length 3; it's considered incorrect since it has larger total length. Constraints: 1 <= s.length <= 105 s contains only lowercase English letters."35Backend,20,Valid Parentheses,Easy,"String, Stack","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. Example 1: Input: s = ""()"" Output: true Example 2: Input: s = ""()[]{}"" Output: true Example 3: Input: s = ""(]"" Output: false Example 4: Input: s = ""([])"" Output: true Constraints: 1 <= s.length <= 104 s consists of parentheses only '()[]{}'."36Backend,277,Find the Celebrity,Med,"Two Pointers, Graph, Interactive",37Backend,53,Maximum Subarray,Med,"Array, Divide and Conquer, Dynamic Programming",Given an integer array nums; find the subarray with the largest sum; and return its sum. Example 1: Input: nums = [-2;1;-3;4;-1;2;1;-5;4] Output: 6 Explanation: The subarray [4;-1;2;1] has the largest sum 6. Example 2: Input: nums = [1] Output: 1 Explanation: The subarray [1] has the largest sum 1. Example 3: Input: nums = [5;4;-1;7;8] Output: 23 Explanation: The subarray [5;4;-1;7;8] has the largest sum 23. Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 Follow up: If you have figured out the O(n) solution; try coding another solution using the divide and conquer approach; which is more subtle.38Backend,235,Lowest Common Ancestor of a Binary Search Tree,Med,"Tree, Depth-First Search, Binary Search Tree, Binary Tree",Given a binary search tree (BST); find the lowest common ancestor (LCA) node of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Example 1: Input: root = [6;2;8;0;4;7;9;null;null;3;5]; p = 2; q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6. Example 2: Input: root = [6;2;8;0;4;7;9;null;null;3;5]; p = 2; q = 4 Output: 2 Explanation: The LCA of nodes 2 and 4 is 2; since a node can be a descendant of itself according to the LCA definition. Example 3: Input: root = [2;1]; p = 2; q = 1 Output: 2 Constraints: The number of nodes in the tree is in the range [2; 105]. -109 <= Node.val <= 109 All Node.val are unique. p != q p and q will exist in the BST.39Backend,1004,Max Consecutive Ones III,Med,"Math, Dynamic Programming, Memoization","Given a single positive integer x; we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1; op2; etc. is either addition; subtraction; multiplication; or division (+; -; *; or /). For example; with x = 3; we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression; we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happen before addition and subtraction. It is not allowed to use the unary negation operator (-). For example; ""x - x"" is a valid expression as it only uses subtraction; but ""-x + x"" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used. Example 1: Input: x = 3; target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5; target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100; target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations. Constraints: 2 <= x <= 100 1 <= target <= 2 * 108"40Backend,34,Find First and Last Position of Element in Sorted Array,Med,"Array, Binary Search",Given an array of integers nums sorted in non-decreasing order; find the starting and ending position of a given target value. If target is not found in the array; return [-1; -1]. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [5;7;7;8;8;10]; target = 8 Output: [3;4] Example 2: Input: nums = [5;7;7;8;8;10]; target = 6 Output: [-1;-1] Example 3: Input: nums = []; target = 0 Output: [-1;-1] Constraints: 0 <= nums.length <= 105 -109 <= nums[i] <= 109 nums is a non-decreasing array. -109 <= target <= 10941Meta,1249,Minimum Remove to Make Valid Parentheses,Med,"Array, Hash Table, Binary Search, Design","Implement a SnapshotArray that supports the following interface: SnapshotArray(int length) initializes an array-like data structure with the given length. Initially; each element equals 0. void set(index; val) sets the element at the given index to be equal to val. int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1. int get(index; snap_id) returns the value at the given index; at the time we took the snapshot with the given snap_id Example 1: Input: [""SnapshotArray"";""set"";""snap"";""set"";""get""] [[3];[0;5];[];[0;6];[0;0]] Output: [null;null;0;null;5] Explanation: SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3 snapshotArr.set(0;5); // Set array[0] = 5 snapshotArr.snap(); // Take a snapshot; return snap_id = 0 snapshotArr.set(0;6); snapshotArr.get(0;0); // Get the value of array[0] with snap_id = 0; return 5 Constraints: 1 <= length <= 5 * 104 0 <= index < length 0 <= val <= 109 0 <= snap_id < (the total number of times we call snap()) At most 5 * 104 calls will be made to set; snap; and get."42Meta,408,Valid Word Abbreviation,Easy,"Two Pointers, String",43Meta,680,Valid Palindrome II,Easy,"Two Pointers, String, Greedy","Given a string s; return true if the s can be palindrome after deleting at most one character from it. Example 1: Input: s = ""aba"" Output: true Example 2: Input: s = ""abca"" Output: true Explanation: You could delete the character 'c'. Example 3: Input: s = ""abc"" Output: false Constraints: 1 <= s.length <= 105 s consists of lowercase English letters."44Meta,227,Basic Calculator II,Med,"Math, String, Stack","Given a string s which represents an expression; evaluate this expression and return its value. 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(). Example 1: Input: s = ""3+2*2"" Output: 7 Example 2: Input: s = "" 3/2 "" Output: 1 Example 3: Input: s = "" 3+5 / 2 "" Output: 5 Constraints: 1 <= s.length <= 3 * 105 s consists of integers and operators ('+'; '-'; '*'; '/') separated by some number of spaces. s represents a valid expression. All the integers in the expression are non-negative integers in the range [0; 231 - 1]. The answer is guaranteed to fit in a 32-bit integer."45Meta,314,Binary Tree Vertical Order Traversal,Med,"Hash Table, Tree, Depth-First Search, Breadth-First Search, Sorting, Binary Tree",46Meta,215,Kth Largest Element in an Array,Med,"Array, Divide and Conquer, Sorting, Heap (Priority Queue), Quickselect",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. Can you solve it without sorting? Example 1: Input: nums = [3;2;1;5;6;4]; k = 2 Output: 5 Example 2: Input: nums = [3;2;3;1;2;4;5;5;6]; k = 4 Output: 4 Constraints: 1 <= k <= nums.length <= 105 -104 <= nums[i] <= 10447Meta,1650,Lowest Common Ancestor of a Binary Tree III,Med,"Hash Table, Bit Manipulation, Tree, Depth-First Search",48Meta,339,Nested List Weight Sum,Med,"Depth-First Search, Breadth-First Search",49Meta,528,Random Pick with Weight,Med,"Linked List, Two Pointers",You are given the head of a linked list; and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). Example 1: Input: head = [1;2;3;4;5]; k = 2 Output: [1;4;3;2;5] Example 2: Input: head = [7;9;6;6;7;8;3;0;9;5]; k = 5 Output: [7;9;6;6;8;7;3;0;9;5] Constraints: The number of nodes in the list is n. 1 <= k <= n <= 105 0 <= Node.val <= 10050Meta,236,Lowest Common Ancestor of a Binary Tree,Med,"Tree, Depth-First Search, Binary Tree",Given a binary tree; find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Example 1: Input: root = [3;5;1;6;2;0;8;null;null;7;4]; p = 5; q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3. Example 2: Input: root = [3;5;1;6;2;0;8;null;null;7;4]; p = 5; q = 4 Output: 5 Explanation: The LCA of nodes 5 and 4 is 5; since a node can be a descendant of itself according to the LCA definition. Example 3: Input: root = [1;2]; p = 1; q = 2 Output: 1 Constraints: The number of nodes in the tree is in the range [2; 105]. -109 <= Node.val <= 109 All Node.val are unique. p != q p and q will exist in the tree.51Meta,1091,Shortest Path in Binary Matrix,Med,"Tree, Depth-First Search, Binary Tree",52Meta,71,Simplify Path,Med,"String, Stack","You are given an absolute path for a Unix-style file system; which always begins with a slash '/'. Your task is to transform this absolute path into its simplified canonical path. The rules of a Unix-style file system are as follows: A single period '.' represents the current directory. A double period '..' represents the previous/parent directory. Multiple consecutive slashes such as '//' and '///' are treated as a single slash '/'. Any sequence of periods that does not match the rules above should be treated as a valid directory or file name. For example; '...' and '....' are valid directory or file names. The simplified canonical path should follow these rules: The path must start with a single slash '/'. Directories within the path must be separated by exactly one slash '/'. The path must not end with a slash '/'; unless it is the root directory. The path must not have any single or double periods ('.' and '..') used to denote current or parent directories. Return the simplified canonical path. Example 1: Input: path = ""/home/"" Output: ""/home"" Explanation: The trailing slash should be removed. Example 2: Input: path = ""/home//foo/"" Output: ""/home/foo"" Explanation: Multiple consecutive slashes are replaced by a single one. Example 3: Input: path = ""/home/user/Documents/../Pictures"" Output: ""/home/user/Pictures"" Explanation: A double period "".."" refers to the directory up a level (the parent directory). Example 4: Input: path = ""/../"" Output: ""/"" Explanation: Going one level up from the root directory is not possible. Example 5: Input: path = ""/.../a/../b/c/../d/./"" Output: ""/.../b/d"" Explanation: ""..."" is a valid name for a directory in this problem. Constraints: 1 <= path.length <= 3000 path consists of English letters; digits; period '.'; slash '/' or '_'. path is a valid absolute Unix path."53Meta,162,Find Peak Element,Med,"Array, Binary Search",A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums; find a peak element; and return its index. If the array contains multiple peaks; return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -∞. In other words; an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in O(log n) time. Example 1: Input: nums = [1;2;3;1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2. Example 2: Input: nums = [1;2;1;3;5;6;4] Output: 5 Explanation: Your function can return either index number 1 where the peak element is 2; or index number 5 where the peak element is 6. Constraints: 1 <= nums.length <= 1000 -231 <= nums[i] <= 231 - 1 nums[i] != nums[i + 1] for all valid i.54Meta,88,Merge Sorted Array,Easy,"Array, Two Pointers, Sorting",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. Example 1: 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. Example 2: Input: nums1 = [1]; m = 1; nums2 = []; n = 0 Output: [1] Explanation: The arrays we are merging are [1] and []. The result of the merge is [1]. Example 3: Input: nums1 = [0]; m = 0; nums2 = [1]; n = 1 Output: [1] Explanation: The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0; there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. Constraints: nums1.length == m + n nums2.length == n 0 <= m; n <= 200 1 <= m + n <= 200 -109 <= nums1[i]; nums2[j] <= 109 Follow up: Can you come up with an algorithm that runs in O(m + n) time?55Meta,1570,Dot Product of Two Sparse Vectors,Med,"Array, Stack, Monotonic Stack",You are given an integer array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop. If you buy the ith item; then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i]. Otherwise; you will not receive any discount at all. Return an integer array answer where answer[i] is the final price you will pay for the ith item of the shop; considering the special discount. Example 1: Input: prices = [8;4;6;2;3] Output: [4;2;4;2;3] Explanation: For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4; therefore; the final price you will pay is 8 - 4 = 4. For item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2; therefore; the final price you will pay is 4 - 2 = 2. For item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2; therefore; the final price you will pay is 6 - 2 = 4. For items 3 and 4 you will not receive any discount at all. Example 2: Input: prices = [1;2;3;4;5] Output: [1;2;3;4;5] Explanation: In this case; for all items; you will not receive any discount at all. Example 3: Input: prices = [10;1;1;6] Output: [9;0;1;6] Constraints: 1 <= prices.length <= 500 1 <= prices[i] <= 100056Meta,938,Range Sum of BST,Easy,"Array, Math, String, Binary Search, Dynamic Programming","Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example; if digits = ['1';'3';'5']; we may write numbers such as '13'; '551'; and '1351315'. Return the number of positive integers that can be generated that are less than or equal to a given integer n. Example 1: Input: digits = [""1"";""3"";""5"";""7""]; n = 100 Output: 20 Explanation: The 20 numbers that can be written are: 1; 3; 5; 7; 11; 13; 15; 17; 31; 33; 35; 37; 51; 53; 55; 57; 71; 73; 75; 77. Example 2: Input: digits = [""1"";""4"";""9""]; n = 1000000000 Output: 29523 Explanation: We can write 3 one digit numbers; 9 two digit numbers; 27 three digit numbers; 81 four digit numbers; 243 five digit numbers; 729 six digit numbers; 2187 seven digit numbers; 6561 eight digit numbers; and 19683 nine digit numbers. In total; this is 29523 integers that can be written using the digits array. Example 3: Input: digits = [""7""]; n = 8 Output: 1 Constraints: 1 <= digits.length <= 9 digits[i].length == 1 digits[i] is a digit from '1' to '9'. All the values in digits are unique. digits is sorted in non-decreasing order. 1 <= n <= 109"57Meta,50,"Pow(x, n)",Med,"Math, Recursion",Implement pow(x; n); which calculates x raised to the power n (i.e.; xn). Example 1: Input: x = 2.00000; n = 10 Output: 1024.00000 Example 2: Input: x = 2.10000; n = 3 Output: 9.26100 Example 3: Input: x = 2.00000; n = -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25 Constraints: -100.0 < x < 100.0 -231 <= n <= 231-1 n is an integer. Either x is not zero or n > 0. -104 <= xn <= 10458Meta,199,Binary Tree Right Side View,Med,"Tree, Depth-First Search, Breadth-First Search, Binary Tree",Given the root of a binary tree; imagine yourself standing on the right side of it; return the values of the nodes you can see ordered from top to bottom. Example 1: Input: root = [1;2;3;null;5;null;4] Output: [1;3;4] Example 2: Input: root = [1;null;3] Output: [1;3] Example 3: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0; 100]. -100 <= Node.val <= 10059Meta,56,Merge Intervals,Med,"Array, Sorting",Given an array of intervals where intervals[i] = [starti; endi]; merge all overlapping intervals; and return an array of the non-overlapping intervals that cover all the intervals in the input. Example 1: Input: intervals = [[1;3];[2;6];[8;10];[15;18]] Output: [[1;6];[8;10];[15;18]] Explanation: Since intervals [1;3] and [2;6] overlap; merge them into [1;6]. Example 2: Input: intervals = [[1;4];[4;5]] Output: [[1;5]] Explanation: Intervals [1;4] and [4;5] are considered overlapping. Constraints: 1 <= intervals.length <= 104 intervals[i].length == 2 0 <= starti <= endi <= 10460Meta,560,Subarray Sum Equals K,Med,"Array, Hash Table, Prefix Sum",Given an array of integers nums and an integer k; return the total number of subarrays whose sum equals to k. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: nums = [1;1;1]; k = 2 Output: 2 Example 2: Input: nums = [1;2;3]; k = 3 Output: 2 Constraints: 1 <= nums.length <= 2 * 104 -1000 <= nums[i] <= 1000 -107 <= k <= 10761Meta,1,Two Sum,Easy,"Array, Hash Table",Given an array of integers nums and an integer target; return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution; and you may not use the same element twice. You can return the answer in any order. Example 1: Input: nums = [2;7;11;15]; target = 9 Output: [0;1] Explanation: Because nums[0] + nums[1] == 9; we return [0; 1]. Example 2: Input: nums = [3;2;4]; target = 6 Output: [1;2] Example 3: Input: nums = [3;3]; target = 6 Output: [0;1] Constraints: 2 <= nums.length <= 104 -109 <= nums[i] <= 109 -109 <= target <= 109 Only one valid answer exists. Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?62Meta,543,Diameter of Binary Tree,Easy,"Tree, Depth-First Search, Binary Tree",Given the root of a binary tree; return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them. Example 1: Input: root = [1;2;3;4;5] Output: 3 Explanation: 3 is the length of the path [4;2;1;3] or [5;2;1;3]. Example 2: Input: root = [1;2] Output: 1 Constraints: The number of nodes in the tree is in the range [1; 104]. -100 <= Node.val <= 10063Meta,138,Copy List with Random Pointer,Med,"Hash Table, Linked List",A linked list of length n is given such that each node contains an additional random pointer; which could point to any node in the list; or null. Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes; where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list. For example; if there are two nodes X and Y in the original list; where X.random --> Y; then for the corresponding two nodes x and y in the copied list; x.random --> y. Return the head of the copied linked list. The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val; random_index] where: val: an integer representing Node.val random_index: the index of the node (range from 0 to n-1) that the random pointer points to; or null if it does not point to any node. Your code will only be given the head of the original linked list. Example 1: Input: head = [[7;null];[13;0];[11;4];[10;2];[1;0]] Output: [[7;null];[13;0];[11;4];[10;2];[1;0]] Example 2: Input: head = [[1;1];[2;1]] Output: [[1;1];[2;1]] Example 3: Input: head = [[3;null];[3;0];[3;null]] Output: [[3;null];[3;0];[3;null]] Constraints: 0 <= n <= 1000 -104 <= Node.val <= 104 Node.random is null or is pointing to some node in the linked list.64Meta,31,Next Permutation,Med,"Array, Two Pointers",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 all the permutations of arr: [1;2;3]; [1;3;2]; [2; 1; 3]; [2; 3; 1]; [3;1;2]; [3;2;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. The replacement must be in place and use only constant extra memory. Example 1: Input: nums = [1;2;3] Output: [1;3;2] Example 2: Input: nums = [3;2;1] Output: [1;2;3] Example 3: Input: nums = [1;1;5] Output: [1;5;1] Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 10065Meta,125,Valid Palindrome,Easy,"Two Pointers, String","A phrase is a palindrome if; after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters; it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s; return true if it is a palindrome; or false otherwise. Example 1: Input: s = ""A man; a plan; a canal: Panama"" Output: true Explanation: ""amanaplanacanalpanama"" is a palindrome. Example 2: Input: s = ""race a car"" Output: false Explanation: ""raceacar"" is not a palindrome. Example 3: Input: s = "" "" Output: true Explanation: s is an empty string """" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward; it is a palindrome. Constraints: 1 <= s.length <= 2 * 105 s consists only of printable ASCII characters."66Meta,973,K Closest Points to Origin,Med,"String, Stack, Greedy, Queue","You are given two strings stamp and target. Initially; there is a string s of length target.length with all s[i] == '?'. In one turn; you can place stamp over s and replace every letter in the s with the corresponding letter from stamp. For example; if stamp = ""abc"" and target = ""abcba""; then s is ""?????"" initially. In one turn you can: place stamp at index 0 of s to obtain ""abc??""; place stamp at index 1 of s to obtain ""?abc?""; or place stamp at index 2 of s to obtain ""??abc"". Note that stamp must be fully contained in the boundaries of s in order to stamp (i.e.; you cannot place stamp at index 3 of s). We want to convert s to target using at most 10 * target.length turns. Return an array of the index of the left-most letter being stamped at each turn. If we cannot obtain target from s within 10 * target.length turns; return an empty array. Example 1: Input: stamp = ""abc""; target = ""ababc"" Output: [0;2] Explanation: Initially s = ""?????"". - Place stamp at index 0 to get ""abc??"". - Place stamp at index 2 to get ""ababc"". [1;0;2] would also be accepted as an answer; as well as some other answers. Example 2: Input: stamp = ""abca""; target = ""aabcaca"" Output: [3;0;1] Explanation: Initially s = ""???????"". - Place stamp at index 3 to get ""???abca"". - Place stamp at index 0 to get ""abcabca"". - Place stamp at index 1 to get ""aabcaca"". Constraints: 1 <= stamp.length <= target.length <= 1000 stamp and target consist of lowercase English letters."67Meta,1762,Buildings With an Ocean View,Med,"Array, Greedy, Heap (Priority Queue)",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. Example 1: 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. Example 2: Input: heights = [4;12;2;7;3;18;20;3;19]; bricks = 10; ladders = 2 Output: 7 Example 3: Input: heights = [14;3;19;3]; bricks = 17; ladders = 0 Output: 3 Constraints: 1 <= heights.length <= 105 1 <= heights[i] <= 106 0 <= bricks <= 109 0 <= ladders <= heights.length68Meta,146,LRU Cache,Med,"Hash Table, Linked List, Design, Doubly-Linked List","Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class: LRUCache(int capacity) Initialize the LRU cache with positive size capacity. int get(int key) Return the value of the key if the key exists; otherwise return -1. void put(int key; int value) Update the value of the key if the key exists. Otherwise; add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation; evict the least recently used key. The functions get and put must each run in O(1) average time complexity. Example 1: Input [""LRUCache""; ""put""; ""put""; ""get""; ""put""; ""get""; ""put""; ""get""; ""get""; ""get""] [[2]; [1; 1]; [2; 2]; [1]; [3; 3]; [2]; [4; 4]; [1]; [3]; [4]] Output [null; null; null; 1; null; -1; null; -1; 3; 4] Explanation LRUCache lRUCache = new LRUCache(2); lRUCache.put(1; 1); // cache is {1=1} lRUCache.put(2; 2); // cache is {1=1; 2=2} lRUCache.get(1); // return 1 lRUCache.put(3; 3); // LRU key was 2; evicts key 2; cache is {1=1; 3=3} lRUCache.get(2); // returns -1 (not found) lRUCache.put(4; 4); // LRU key was 1; evicts key 1; cache is {4=4; 3=3} lRUCache.get(1); // return -1 (not found) lRUCache.get(3); // return 3 lRUCache.get(4); // return 4 Constraints: 1 <= capacity <= 3000 0 <= key <= 104 0 <= value <= 105 At most 2 * 105 calls will be made to get and put."69Meta,283,Move Zeroes,Easy,"Array, Two Pointers",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. Example 1: Input: nums = [0;1;0;3;12] Output: [1;3;12;0;0] Example 2: Input: nums = [0] Output: [0] Constraints: 1 <= nums.length <= 104 -231 <= nums[i] <= 231 - 1 Follow up: Could you minimize the total number of operations done?70Meta,791,Custom Sort String,Med,"Tree, Binary Search Tree, Recursion, Binary Tree",71Meta,921,Minimum Add to Make Parentheses Valid,Med,"Array, Matrix, Simulation",You start at the cell (rStart; cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid; and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary; we continue our walk outside the grid (but may return to the grid boundary later.). Eventually; we reach all rows * cols spaces of the grid. Return an array of coordinates representing the positions of the grid in the order you visited them. Example 1: Input: rows = 1; cols = 4; rStart = 0; cStart = 0 Output: [[0;0];[0;1];[0;2];[0;3]] Example 2: Input: rows = 5; cols = 6; rStart = 1; cStart = 4 Output: [[1;4];[1;5];[2;5];[2;4];[2;3];[1;3];[0;3];[0;4];[0;5];[3;5];[3;4];[3;3];[3;2];[2;2];[1;2];[0;2];[4;5];[4;4];[4;3];[4;2];[4;1];[3;1];[2;1];[1;1];[0;1];[4;0];[3;0];[2;0];[1;0];[0;0]] Constraints: 1 <= rows; cols <= 100 0 <= rStart < rows 0 <= cStart < cols72Meta,986,Interval List Intersections,Med,"Array, String, Enumeration","Given an array arr of 4 digits; find the latest 24-hour time that can be made using each digit exactly once. 24-hour times are formatted as ""HH:MM""; where HH is between 00 and 23; and MM is between 00 and 59. The earliest 24-hour time is 00:00; and the latest is 23:59. Return the latest 24-hour time in ""HH:MM"" format. If no valid time can be made; return an empty string. Example 1: Input: arr = [1;2;3;4] Output: ""23:41"" Explanation: The valid 24-hour times are ""12:34""; ""12:43""; ""13:24""; ""13:42""; ""14:23""; ""14:32""; ""21:34""; ""21:43""; ""23:14""; and ""23:41"". Of these times; ""23:41"" is the latest. Example 2: Input: arr = [5;5;5;5] Output: """" Explanation: There are no valid 24-hour times as ""55:55"" is not valid. Constraints: arr.length == 4 0 <= arr[i] <= 9"73Meta,347,Top K Frequent Elements,Med,"Array, Hash Table, Divide and Conquer, Sorting, Heap (Priority Queue), Bucket Sort, Counting, Quickselect",Given an integer array nums and an integer k; return the k most frequent elements. You may return the answer in any order. Example 1: Input: nums = [1;1;1;2;2;3]; k = 2 Output: [1;2] Example 2: Input: nums = [1]; k = 1 Output: [1] Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 k is in the range [1; the number of unique elements in the array]. It is guaranteed that the answer is unique. Follow up: Your algorithm's time complexity must be better than O(n log n); where n is the array's size.74Meta,426,Convert Binary Search Tree to Sorted Doubly Linked List,Med,,75Meta,670,Maximum Swap,Med,"Math, Greedy",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. Example 1: Input: num = 2736 Output: 7236 Explanation: Swap the number 2 and the number 7. Example 2: Input: num = 9973 Output: 9973 Explanation: No swap. Constraints: 0 <= num <= 10876Meta,1004,Max Consecutive Ones III,Med,"Math, Dynamic Programming, Memoization","Given a single positive integer x; we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1; op2; etc. is either addition; subtraction; multiplication; or division (+; -; *; or /). For example; with x = 3; we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression; we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happen before addition and subtraction. It is not allowed to use the unary negation operator (-). For example; ""x - x"" is a valid expression as it only uses subtraction; but ""-x + x"" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used. Example 1: Input: x = 3; target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5; target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100; target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations. Constraints: 2 <= x <= 100 1 <= target <= 2 * 108"77Meta,129,Sum Root to Leaf Numbers,Med,"Tree, Depth-First Search, Binary Tree",You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number. For example; the root-to-leaf path 1 -> 2 -> 3 represents the number 123. Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer. A leaf node is a node with no children. Example 1: Input: root = [1;2;3] Output: 25 Explanation: The root-to-leaf path 1->2 represents the number 12. The root-to-leaf path 1->3 represents the number 13. Therefore; sum = 12 + 13 = 25. Example 2: Input: root = [4;9;0;5;1] Output: 1026 Explanation: The root-to-leaf path 4->9->5 represents the number 495. The root-to-leaf path 4->9->1 represents the number 491. The root-to-leaf path 4->0 represents the number 40. Therefore; sum = 495 + 491 + 40 = 1026. Constraints: The number of nodes in the tree is in the range [1; 1000]. 0 <= Node.val <= 9 The depth of the tree will not exceed 10.78Meta,346,Moving Average from Data Stream,Easy,"Array, Design, Queue, Data Stream",79Meta,987,Vertical Order Traversal of a Binary Tree,Hard,"Array, Queue, Sorting, Simulation",You are given an integer array deck. There is a deck of cards where every card has a unique integer. The integer on the ith card is deck[i]. You can order the deck in any order you want. Initially; all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: Take the top card of the deck; reveal it; and take it out of the deck. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. If there are still unrevealed cards; go back to step 1. Otherwise; stop. Return an ordering of the deck that would reveal the cards in increasing order. Note that the first entry in the answer is considered to be the top of the deck. Example 1: Input: deck = [17;13;11;2;3;5;7] Output: [2;13;3;11;5;17;7] Explanation: We get the deck in the order [17;13;11;2;3;5;7] (this order does not matter); and reorder it. After reordering; the deck starts as [2;13;3;11;5;17;7]; where 2 is the top of the deck. We reveal 2; and move 13 to the bottom. The deck is now [3;11;5;17;7;13]. We reveal 3; and move 11 to the bottom. The deck is now [5;17;7;13;11]. We reveal 5; and move 17 to the bottom. The deck is now [7;13;11;17]. We reveal 7; and move 13 to the bottom. The deck is now [11;17;13]. We reveal 11; and move 17 to the bottom. The deck is now [13;17]. We reveal 13; and move 17 to the bottom. The deck is now [17]. We reveal 17. Since all the cards revealed are in increasing order; the answer is correct. Example 2: Input: deck = [1;1000] Output: [1;1000] Constraints: 1 <= deck.length <= 1000 1 <= deck[i] <= 106 All the values of deck are unique.80Meta,15,3Sum,Med,"Array, Two Pointers, Sorting",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. Example 1: Input: nums = [-1;0;1;2;-1;-4] Output: [[-1;-1;2];[-1;0;1]] Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1;0;1] and [-1;-1;2]. Notice that the order of the output and the order of the triplets does not matter. Example 2: Input: nums = [0;1;1] Output: [] Explanation: The only possible triplet does not sum up to 0. Example 3: Input: nums = [0;0;0] Output: [[0;0;0]] Explanation: The only possible triplet sums up to 0. Constraints: 3 <= nums.length <= 3000 -105 <= nums[i] <= 10581Meta,23,Merge k Sorted Lists,Hard,"Linked List, Divide and Conquer, Heap (Priority Queue), Merge Sort",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. Example 1: 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 Example 2: Input: lists = [] Output: [] Example 3: Input: lists = [[]] Output: [] Constraints: k == lists.length 0 <= k <= 104 0 <= lists[i].length <= 500 -104 <= lists[i][j] <= 104 lists[i] is sorted in ascending order. The sum of lists[i].length will not exceed 104.82Meta,1539,Kth Missing Positive Number,Easy,"Array, Sorting, Heap (Priority Queue)",Given a 2D integer array nums; return all elements of nums in diagonal order as shown in the below images. Example 1: Input: nums = [[1;2;3];[4;5;6];[7;8;9]] Output: [1;4;2;7;5;3;8;6;9] Example 2: Input: nums = [[1;2;3;4;5];[6;7];[8];[9;10;11];[12;13;14;15;16]] Output: [1;6;2;8;7;3;9;4;12;10;5;13;11;14;15;16] Constraints: 1 <= nums.length <= 105 1 <= nums[i].length <= 105 1 <= sum(nums[i].length) <= 105 1 <= nums[i][j] <= 10583Meta,133,Clone Graph,Med,"Hash Table, Depth-First Search, Breadth-First Search, Graph",Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. class Node { public int val; public List<Node> neighbors; } Test case format: For simplicity; each node's value is the same as the node's index (1-indexed). For example; the first node with val == 1; the second node with val == 2; and so on. The graph is represented in the test case using an adjacency list. An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph. Example 1: Input: adjList = [[2;4];[1;3];[2;4];[1;3]] Output: [[2;4];[1;3];[2;4];[1;3]] Explanation: There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). Example 2: Input: adjList = [[]] Output: [[]] Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. Example 3: Input: adjList = [] Output: [] Explanation: This an empty graph; it does not have any nodes. Constraints: The number of nodes in the graph is in the range [0; 100]. 1 <= Node.val <= 100 Node.val is unique for each node. There are no repeated edges and no self-loops in the graph. The Graph is connected and all nodes can be visited starting from the given node.84Meta,200,Number of Islands,Med,"Array, Depth-First Search, Breadth-First Search, Union Find, Matrix","Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water); return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: grid = [ [""1"";""1"";""1"";""1"";""0""]; [""1"";""1"";""0"";""1"";""0""]; [""1"";""1"";""0"";""0"";""0""]; [""0"";""0"";""0"";""0"";""0""] ] Output: 1 Example 2: Input: grid = [ [""1"";""1"";""0"";""0"";""0""]; [""1"";""1"";""0"";""0"";""0""]; [""0"";""0"";""1"";""0"";""0""]; [""0"";""0"";""0"";""1"";""1""] ] Output: 3 Constraints: m == grid.length n == grid[i].length 1 <= m; n <= 300 grid[i][j] is '0' or '1'."85Meta,636,Exclusive Time of Functions,Med,"Array, Stack","On a single-threaded CPU; we execute a program containing n functions. Each function has a unique ID between 0 and n-1. Function calls are stored in a call stack: when a function call starts; its ID is pushed onto the stack; and when a function call ends; its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed. Each time a function starts or ends; we write a log with the ID; whether it started or ended; and the timestamp. You are given a list logs; where logs[i] represents the ith log message formatted as a string ""{function_id}:{""start"" | ""end""}:{timestamp}"". For example; ""0:start:3"" means a function call with function ID 0 started at the beginning of timestamp 3; and ""1:end:2"" means a function call with function ID 1 ended at the end of timestamp 2. Note that a function can be called multiple times; possibly recursively. A function's exclusive time is the sum of execution times for all function calls in the program. For example; if a function is called twice; one call executing for 2 time units and another call executing for 1 time unit; the exclusive time is 2 + 1 = 3. Return the exclusive time of each function in an array; where the value at the ith index represents the exclusive time for the function with ID i. Example 1: Input: n = 2; logs = [""0:start:0"";""1:start:2"";""1:end:5"";""0:end:6""] Output: [3;4] Explanation: Function 0 starts at the beginning of time 0; then it executes 2 for units of time and reaches the end of time 1. Function 1 starts at the beginning of time 2; executes for 4 units of time; and ends at the end of time 5. Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time. So function 0 spends 2 + 1 = 3 units of total time executing; and function 1 spends 4 units of total time executing. Example 2: Input: n = 1; logs = [""0:start:0"";""0:start:2"";""0:end:5"";""0:start:6"";""0:end:6"";""0:end:7""] Output: [8] Explanation: Function 0 starts at the beginning of time 0; executes for 2 units of time; and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls itself again. Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time. Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time. So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing. Example 3: Input: n = 2; logs = [""0:start:0"";""0:start:2"";""0:end:5"";""1:start:6"";""1:end:6"";""0:end:7""] Output: [7;1] Explanation: Function 0 starts at the beginning of time 0; executes for 2 units of time; and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls function 1. Function 1 starts at the beginning of time 6; executes 1 unit of time; and ends at the end of time 6. Function 0 resumes execution at the beginning of time 6 and executes for 2 units of time. So function 0 spends 2 + 4 + 1 = 7 units of total time executing; and function 1 spends 1 unit of total time executing. Constraints: 1 <= n <= 100 1 <= logs.length <= 500 0 <= function_id < n 0 <= timestamp <= 109 No two start events will happen at the same timestamp. No two end events will happen at the same timestamp. Each function has an ""end"" log for each ""start"" log."86Meta,163,Missing Ranges,Easy,Array,87Meta,498,Diagonal Traverse,Med,"Array, Matrix, Simulation",Given an m x n matrix mat; return an array of all the elements of the array in a diagonal order. Example 1: Input: mat = [[1;2;3];[4;5;6];[7;8;9]] Output: [1;2;4;7;5;3;6;8;9] Example 2: Input: mat = [[1;2];[3;4]] Output: [1;2;3;4] Constraints: m == mat.length n == mat[i].length 1 <= m; n <= 104 1 <= m * n <= 104 -105 <= mat[i][j] <= 10588Meta,766,Toeplitz Matrix,Easy,"Linked List, Depth-First Search, Doubly-Linked List",You are given a doubly linked list; which contains nodes that have a next pointer; a previous pointer; and an additional child pointer. This child pointer may or may not point to a separate doubly linked list; also containing these special nodes. These child lists may have one or more children of their own; and so on; to produce a multilevel data structure as shown in the example below. Given the head of the first level of the list; flatten the list so that all the nodes appear in a single-level; doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list. Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null. Example 1: Input: head = [1;2;3;4;5;6;null;null;null;7;8;9;10;null;null;11;12] Output: [1;2;3;7;8;11;12;9;10;4;5;6] Explanation: The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: Example 2: Input: head = [1;2;null;3] Output: [1;3;2] Explanation: The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: Example 3: Input: head = [] Output: [] Explanation: There could be empty list in the input. Constraints: The number of Nodes will not exceed 1000. 1 <= Node.val <= 105 How the multilevel linked list is represented in test cases: We use the multilevel linked list from Example 1 above: 1---2---3---4---5---6--NULL | 7---8---9---10--NULL | 11--12--NULL The serialization of each level is as follows: [1;2;3;4;5;6;null] [7;8;9;10;null] [11;12;null] To serialize all levels together; we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes: [1; 2; 3; 4; 5; 6; null] | [null; null; 7; 8; 9; 10; null] | [ null; 11; 12; null] Merging the serialization of each level and removing trailing nulls we obtain: [1;2;3;4;5;6;null;null;null;7;8;9;10;null;null;11;12]89Meta,34,Find First and Last Position of Element in Sorted Array,Med,"Array, Binary Search",Given an array of integers nums sorted in non-decreasing order; find the starting and ending position of a given target value. If target is not found in the array; return [-1; -1]. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [5;7;7;8;8;10]; target = 8 Output: [3;4] Example 2: Input: nums = [5;7;7;8;8;10]; target = 6 Output: [-1;-1] Example 3: Input: nums = []; target = 0 Output: [-1;-1] Constraints: 0 <= nums.length <= 105 -109 <= nums[i] <= 109 nums is a non-decreasing array. -109 <= target <= 10990Meta,121,Best Time to Buy and Sell Stock,Easy,"Array, Dynamic Programming",You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit; return 0. Example 1: Input: prices = [7;1;5;3;6;4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6); profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. Example 2: Input: prices = [7;6;4;3;1] Output: 0 Explanation: In this case; no transactions are done and the max profit = 0. Constraints: 1 <= prices.length <= 105 0 <= prices[i] <= 10491Meta,708,Insert into a Sorted Circular Linked List,Med,,92Meta,65,Valid Number,Hard,String,"Given a string s; return whether s is a valid number. For example; all the following are valid numbers: ""2""; ""0089""; ""-0.1""; ""+3.14""; ""4.""; ""-.9""; ""2e10""; ""-90E3""; ""3e+7""; ""+6e-1""; ""53.5e93""; ""-123.456e789""; while the following are not valid numbers: ""abc""; ""1a""; ""1e""; ""e3""; ""99e2.5""; ""--6""; ""-+3""; ""95a54e53"". Formally; a valid number is defined using one of the following definitions: An integer number followed by an optional exponent. A decimal number followed by an optional exponent. An integer number is defined with an optional sign '-' or '+' followed by digits. A decimal number is defined with an optional sign '-' or '+' followed by one of the following definitions: Digits followed by a dot '.'. Digits followed by a dot '.' followed by digits. A dot '.' followed by digits. An exponent is defined with an exponent notation 'e' or 'E' followed by an integer number. The digits are defined as one or more digits. Example 1: Input: s = ""0"" Output: true Example 2: Input: s = ""e"" Output: false Example 3: Input: s = ""."" Output: false Constraints: 1 <= s.length <= 20 s consists of only English letters (both uppercase and lowercase); digits (0-9); plus '+'; minus '-'; or dot '.'."93Meta,249,Group Shifted Strings,Med,"Array, Hash Table, String",94Meta,17,Letter Combinations of a Phone Number,Med,"Hash Table, String, Backtracking","Given a string containing digits from 2-9 inclusive; return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. Example 1: Input: digits = ""23"" Output: [""ad"";""ae"";""af"";""bd"";""be"";""bf"";""cd"";""ce"";""cf""] Example 2: Input: digits = """" Output: [] Example 3: Input: digits = ""2"" Output: [""a"";""b"";""c""] Constraints: 0 <= digits.length <= 4 digits[i] is a digit in the range ['2'; '9']."95Meta,76,Minimum Window Substring,Hard,"Hash Table, String, Sliding Window","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. Example 1: Input: s = ""ADOBECODEBANC""; t = ""ABC"" Output: ""BANC"" Explanation: The minimum window substring ""BANC"" includes 'A'; 'B'; and 'C' from string t. Example 2: Input: s = ""a""; t = ""a"" Output: ""a"" Explanation: The entire string s is the minimum window. Example 3: Input: s = ""a""; t = ""aa"" Output: """" Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has one 'a'; return empty string. Constraints: m == s.length n == t.length 1 <= m; n <= 105 s and t consist of uppercase and lowercase English letters. Follow up: Could you find an algorithm that runs in O(m + n) time?"96Meta,173,Binary Search Tree Iterator,Med,"Stack, Tree, Design, Binary Search Tree, Binary Tree, Iterator","Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST): BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST. boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer; otherwise returns false. int next() Moves the pointer to the right; then returns the number at the pointer. Notice that by initializing the pointer to a non-existent smallest number; the first call to next() will return the smallest element in the BST. You may assume that next() calls will always be valid. That is; there will be at least a next number in the in-order traversal when next() is called. Example 1: Input [""BSTIterator""; ""next""; ""next""; ""hasNext""; ""next""; ""hasNext""; ""next""; ""hasNext""; ""next""; ""hasNext""] [[[7; 3; 15; null; null; 9; 20]]; []; []; []; []; []; []; []; []; []] Output [null; 3; 7; true; 9; true; 15; true; 20; false] Explanation BSTIterator bSTIterator = new BSTIterator([7; 3; 15; null; null; 9; 20]); bSTIterator.next(); // return 3 bSTIterator.next(); // return 7 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 9 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 15 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 20 bSTIterator.hasNext(); // return False Constraints: The number of nodes in the tree is in the range [1; 105]. 0 <= Node.val <= 106 At most 105 calls will be made to hasNext; and next. Follow up: Could you implement next() and hasNext() to run in average O(1) time and use O(h) memory; where h is the height of the tree?"97Meta,398,Random Pick Index,Med,"Hash Table, Math, Reservoir Sampling, Randomized","Given an integer array nums with possible duplicates; randomly output the index of a given target number. You can assume that the given target number must exist in the array. Implement the Solution class: Solution(int[] nums) Initializes the object with the array nums. int pick(int target) Picks a random index i from nums where nums[i] == target. If there are multiple valid i's; then each index should have an equal probability of returning. Example 1: Input [""Solution""; ""pick""; ""pick""; ""pick""] [[[1; 2; 3; 3; 3]]; [3]; [1]; [3]] Output [null; 4; 0; 2] Explanation Solution solution = new Solution([1; 2; 3; 3; 3]); solution.pick(3); // It should return either index 2; 3; or 4 randomly. Each index should have equal probability of returning. solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1. solution.pick(3); // It should return either index 2; 3; or 4 randomly. Each index should have equal probability of returning. Constraints: 1 <= nums.length <= 2 * 104 -231 <= nums[i] <= 231 - 1 target is an integer from nums. At most 104 calls will be made to pick."98Meta,1047,Remove All Adjacent Duplicates In String,Easy,"Array, Greedy, Sorting",Given an integer array nums and an integer k; modify the array in the following way: choose an index i and replace nums[i] with -nums[i]. You should apply this process exactly k times. You may choose the same index i multiple times. Return the largest possible sum of the array after modifying it in this way. Example 1: Input: nums = [4;2;3]; k = 1 Output: 5 Explanation: Choose index 1 and nums becomes [4;-2;3]. Example 2: Input: nums = [3;-1;0;2]; k = 3 Output: 6 Explanation: Choose indices (1; 2; 2) and nums becomes [3;1;0;2]. Example 3: Input: nums = [2;-3;-1;5;-4]; k = 2 Output: 13 Explanation: Choose indices (1; 4) and nums becomes [2;3;-1;5;4]. Constraints: 1 <= nums.length <= 104 -100 <= nums[i] <= 100 1 <= k <= 10499Meta,2,Add Two Numbers,Med,"Linked List, Math, Recursion",You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order; and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero; except the number 0 itself. Example 1: Input: l1 = [2;4;3]; l2 = [5;6;4] Output: [7;0;8] Explanation: 342 + 465 = 807. Example 2: Input: l1 = [0]; l2 = [0] Output: [0] Example 3: Input: l1 = [9;9;9;9;9;9;9]; l2 = [9;9;9;9] Output: [8;9;9;9;0;0;0;1] Constraints: The number of nodes in each linked list is in the range [1; 100]. 0 <= Node.val <= 9 It is guaranteed that the list represents a number that does not have leading zeros.100Meta,14,Longest Common Prefix,Easy,"String, Trie","Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix; return an empty string """". Example 1: Input: strs = [""flower"";""flow"";""flight""] Output: ""fl"" Example 2: Input: strs = [""dog"";""racecar"";""car""] Output: """" Explanation: There is no common prefix among the input strings. Constraints: 1 <= strs.length <= 200 0 <= strs[i].length <= 200 strs[i] consists of only lowercase English letters."101Meta,415,Add Strings,Easy,"Math, String, Simulation","Given two non-negative integers; num1 and num2 represented as string; return the sum of num1 and num2 as a string. You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly. Example 1: Input: num1 = ""11""; num2 = ""123"" Output: ""134"" Example 2: Input: num1 = ""456""; num2 = ""77"" Output: ""533"" Example 3: Input: num1 = ""0""; num2 = ""0"" Output: ""0"" Constraints: 1 <= num1.length; num2.length <= 104 num1 and num2 consist of only digits. num1 and num2 don't have any leading zeros except for the zero itself."102Meta,523,Continuous Subarray Sum,Med,"Array, Hash Table, Math, Prefix Sum",Given an integer array nums and an integer k; return true if nums has a good subarray or false otherwise. A good subarray is a subarray where: its length is at least two; and the sum of the elements of the subarray is a multiple of k. Note that: A subarray is a contiguous part of the array. 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. Example 1: 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. Example 2: Input: nums = [23;2;6;4;7]; k = 6 Output: true Explanation: [23; 2; 6; 4; 7] is an continuous subarray of size 5 whose elements sum up to 42. 42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer. Example 3: Input: nums = [23;2;6;4;7]; k = 13 Output: false Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 109 0 <= sum(nums[i]) <= 231 - 1 1 <= k <= 231 - 1103Meta,1768,Merge Strings Alternately,Easy,"Array, Math, Stack, Tree, Design, Binary Tree",104Meta,253,Meeting Rooms II,Med,"Array, Two Pointers, Greedy, Sorting, Heap (Priority Queue), Prefix Sum",105Meta,282,Expression Add Operators,Hard,"Math, String, Backtracking","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. Example 1: Input: num = ""123""; target = 6 Output: [""1*2*3"";""1+2+3""] Explanation: Both ""1*2*3"" and ""1+2+3"" evaluate to 6. Example 2: Input: num = ""232""; target = 8 Output: [""2*3+2"";""2+3*2""] Explanation: Both ""2*3+2"" and ""2+3*2"" evaluate to 8. Example 3: Input: num = ""3456237490""; target = 9191 Output: [] Explanation: There are no expressions that can be created from ""3456237490"" to evaluate to 9191. Constraints: 1 <= num.length <= 10 num consists of only digits. -231 <= target <= 231 - 1"106Meta,827,Making A Large Island,Hard,"Array, Two Pointers, String","Sometimes people repeat letters to represent extra feeling. For example: ""hello"" -> ""heeellooo"" ""hi"" -> ""hiiii"" In these strings like ""heeellooo""; we have groups of adjacent letters that are all the same: ""h""; ""eee""; ""ll""; ""ooo"". You are given a string s and an array of query strings words. A query word is stretchy if it can be made to be equal to s by any number of applications of the following extension operation: choose a group consisting of characters c; and add some number of characters c to the group so that the size of the group is three or more. For example; starting with ""hello""; we could do an extension on the group ""o"" to get ""hellooo""; but we cannot get ""helloo"" since the group ""oo"" has a size less than three. Also; we could do another extension like ""ll"" -> ""lllll"" to get ""helllllooo"". If s = ""helllllooo""; then the query word ""hello"" would be stretchy because of these two extension operations: query = ""hello"" -> ""hellooo"" -> ""helllllooo"" = s. Return the number of query strings that are stretchy. Example 1: Input: s = ""heeellooo""; words = [""hello""; ""hi""; ""helo""] Output: 1 Explanation: We can extend ""e"" and ""o"" in the word ""hello"" to get ""heeellooo"". We can't extend ""helo"" to get ""heeellooo"" because the group ""ll"" is not size 3 or more. Example 2: Input: s = ""zzzzzyyyyy""; words = [""zzyy"";""zy"";""zyy""] Output: 3 Constraints: 1 <= s.length; words.length <= 100 1 <= words[i].length <= 100 s and words[i] consist of lowercase letters."107Meta,863,All Nodes Distance K in Binary Tree,Med,"Dynamic Programming, Tree, Depth-First Search, Graph",There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [ai; bi] indicates that there is an edge between nodes ai and bi in the tree. Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes. Example 1: Input: n = 6; edges = [[0;1];[0;2];[2;3];[2;4];[2;5]] Output: [8;12;6;10;10;10] Explanation: The tree is shown above. We can see that dist(0;1) + dist(0;2) + dist(0;3) + dist(0;4) + dist(0;5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence; answer[0] = 8; and so on. Example 2: Input: n = 1; edges = [] Output: [0] Example 3: Input: n = 2; edges = [[1;0]] Output: [1;1] Constraints: 1 <= n <= 3 * 104 edges.length == n - 1 edges[i].length == 2 0 <= ai; bi < n ai != bi The given input represents a valid tree.108Meta,8,String to Integer (atoi),Med,String,"Implement the myAtoi(string s) function; which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: Whitespace: Ignore any leading whitespace ("" ""). Signedness: Determine the sign by checking if the next character is '-' or '+'; assuming positivity if neither present. Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read; then the result is 0. Rounding: If the integer is out of the 32-bit signed integer range [-231; 231 - 1]; then round the integer to remain in the range. Specifically; integers less than -231 should be rounded to -231; and integers greater than 231 - 1 should be rounded to 231 - 1. Return the integer as the final result. Example 1: Input: s = ""42"" Output: 42 Explanation: The underlined characters are what is read in and the caret is the current reader position. Step 1: ""42"" (no characters read because there is no leading whitespace) ^ Step 2: ""42"" (no characters read because there is neither a '-' nor '+') ^ Step 3: ""42"" (""42"" is read in) ^ Example 2: Input: s = "" -042"" Output: -42 Explanation: Step 1: "" -042"" (leading whitespace is read and ignored) ^ Step 2: "" -042"" ('-' is read; so the result should be negative) ^ Step 3: "" -042"" (""042"" is read in; leading zeros ignored in the result) ^ Example 3: Input: s = ""1337c0d3"" Output: 1337 Explanation: Step 1: ""1337c0d3"" (no characters read because there is no leading whitespace) ^ Step 2: ""1337c0d3"" (no characters read because there is neither a '-' nor '+') ^ Step 3: ""1337c0d3"" (""1337"" is read in; reading stops because the next character is a non-digit) ^ Example 4: Input: s = ""0-1"" Output: 0 Explanation: Step 1: ""0-1"" (no characters read because there is no leading whitespace) ^ Step 2: ""0-1"" (no characters read because there is neither a '-' nor '+') ^ Step 3: ""0-1"" (""0"" is read in; reading stops because the next character is a non-digit) ^ Example 5: Input: s = ""words and 987"" Output: 0 Explanation: Reading stops at the first non-digit character 'w'. Constraints: 0 <= s.length <= 200 s consists of English letters (lower-case and upper-case); digits (0-9); ' '; '+'; '-'; and '.'."109Meta,20,Valid Parentheses,Easy,"String, Stack","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. Example 1: Input: s = ""()"" Output: true Example 2: Input: s = ""()[]{}"" Output: true Example 3: Input: s = ""(]"" Output: false Example 4: Input: s = ""([])"" Output: true Constraints: 1 <= s.length <= 104 s consists of parentheses only '()[]{}'."110Meta,2667,Create Hello World Function,Easy,"Array, Hash Table, Math, Stack, Sliding Window",111Meta,4,Median of Two Sorted Arrays,Hard,"Array, Binary Search, Divide and Conquer",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)). Example 1: Input: nums1 = [1;3]; nums2 = [2] Output: 2.00000 Explanation: merged array = [1;2;3] and median is 2. Example 2: Input: nums1 = [1;2]; nums2 = [3;4] Output: 2.50000 Explanation: merged array = [1;2;3;4] and median is (2 + 3) / 2 = 2.5. Constraints: nums1.length == m nums2.length == n 0 <= m <= 1000 0 <= n <= 1000 1 <= m + n <= 2000 -106 <= nums1[i]; nums2[i] <= 106112Meta,270,Closest Binary Search Tree Value,Easy,"Binary Search, Tree, Depth-First Search, Binary Search Tree, Binary Tree",113Meta,691,Stickers to Spell Word,Hard,"Array, String, Dynamic Programming, Backtracking, Bit Manipulation, Bitmask","We are given n different types of stickers. Each sticker has a lowercase English word on it. You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want; and you have infinite quantities of each sticker. Return the minimum number of stickers that you need to spell out target. If the task is impossible; return -1. Note: In all test cases; all words were chosen randomly from the 1000 most common US English words; and target was chosen as a concatenation of two random words. Example 1: Input: stickers = [""with"";""example"";""science""]; target = ""thehat"" Output: 3 Explanation: We can use 2 ""with"" stickers; and 1 ""example"" sticker. After cutting and rearrange the letters of those stickers; we can form the target ""thehat"". Also; this is the minimum number of stickers necessary to form the target string. Example 2: Input: stickers = [""notice"";""possible""]; target = ""basicbasic"" Output: -1 Explanation: We cannot form the target ""basicbasic"" from cutting letters from the given stickers. Constraints: n == stickers.length 1 <= n <= 50 1 <= stickers[i].length <= 10 1 <= target.length <= 15 stickers[i] and target consist of lowercase English letters."114Meta,721,Accounts Merge,Med,"Array, Hash Table, String, Depth-First Search, Breadth-First Search, Union Find, Sorting","Given a list of accounts where each element accounts[i] is a list of strings; where the first element accounts[i][0] is a name; and the rest of the elements are emails representing emails of the account. Now; we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name; they may belong to different people as people could have the same name. A person can have any number of accounts initially; but all of their accounts definitely have the same name. After merging the accounts; return the accounts in the following format: the first element of each account is the name; and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order. Example 1: Input: accounts = [[""John"";""johnsmith@mail.com"";""john_newyork@mail.com""];[""John"";""johnsmith@mail.com"";""john00@mail.com""];[""Mary"";""mary@mail.com""];[""John"";""johnnybravo@mail.com""]] Output: [[""John"";""john00@mail.com"";""john_newyork@mail.com"";""johnsmith@mail.com""];[""Mary"";""mary@mail.com""];[""John"";""johnnybravo@mail.com""]] Explanation: The first and second John's are the same person as they have the common email ""johnsmith@mail.com"". The third John and Mary are different people as none of their email addresses are used by other accounts. We could return these lists in any order; for example the answer [['Mary'; 'mary@mail.com']; ['John'; 'johnnybravo@mail.com']; ['John'; 'john00@mail.com'; 'john_newyork@mail.com'; 'johnsmith@mail.com']] would still be accepted. Example 2: Input: accounts = [[""Gabe"";""Gabe0@m.co"";""Gabe3@m.co"";""Gabe1@m.co""];[""Kevin"";""Kevin3@m.co"";""Kevin5@m.co"";""Kevin0@m.co""];[""Ethan"";""Ethan5@m.co"";""Ethan4@m.co"";""Ethan0@m.co""];[""Hanzo"";""Hanzo3@m.co"";""Hanzo1@m.co"";""Hanzo0@m.co""];[""Fern"";""Fern5@m.co"";""Fern1@m.co"";""Fern0@m.co""]] Output: [[""Ethan"";""Ethan0@m.co"";""Ethan4@m.co"";""Ethan5@m.co""];[""Gabe"";""Gabe0@m.co"";""Gabe1@m.co"";""Gabe3@m.co""];[""Hanzo"";""Hanzo0@m.co"";""Hanzo1@m.co"";""Hanzo3@m.co""];[""Kevin"";""Kevin0@m.co"";""Kevin3@m.co"";""Kevin5@m.co""];[""Fern"";""Fern0@m.co"";""Fern1@m.co"";""Fern5@m.co""]] Constraints: 1 <= accounts.length <= 1000 2 <= accounts[i].length <= 10 1 <= accounts[i][j].length <= 30 accounts[i][0] consists of English letters. accounts[i][j] (for j > 0) is a valid email."115Meta,207,Course Schedule,Med,"Depth-First Search, Breadth-First Search, Graph, Topological Sort",There are a total of numCourses courses you have to take; labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai; bi] indicates that you must take course bi first if you want to take course ai. For example; the pair [0; 1]; indicates that to take course 0 you have to first take course 1. Return true if you can finish all courses. Otherwise; return false. Example 1: Input: numCourses = 2; prerequisites = [[1;0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. Example 2: Input: numCourses = 2; prerequisites = [[1;0];[0;1]] Output: false Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0; and to take course 0 you should also have finished course 1. So it is impossible. Constraints: 1 <= numCourses <= 2000 0 <= prerequisites.length <= 5000 prerequisites[i].length == 2 0 <= ai; bi < numCourses All the pairs prerequisites[i] are unique.116Meta,219,Contains Duplicate II,Easy,"Array, Hash Table, Sliding Window",Given an integer array nums and an integer k; return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k. Example 1: Input: nums = [1;2;3;1]; k = 3 Output: true Example 2: Input: nums = [1;0;1;1]; k = 1 Output: true Example 3: Input: nums = [1;2;3;1;2;3]; k = 2 Output: false Constraints: 1 <= nums.length <= 105 -109 <= nums[i] <= 109 0 <= k <= 105117Meta,380,Insert Delete GetRandom O(1),Med,"Array, Hash Table, Math, Design, Randomized","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. Example 1: Input [""RandomizedSet""; ""insert""; ""remove""; ""insert""; ""getRandom""; ""remove""; ""insert""; ""getRandom""] [[]; [1]; [2]; [2]; []; [1]; [2]; []] Output [null; true; false; true; 2; true; false; 2] Explanation RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set; returns true. Set now contains [1;2]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set; returns true. Set now contains [2]. randomizedSet.insert(2); // 2 was already in the set; so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set; getRandom() will always return 2. Constraints: -231 <= val <= 231 - 1 At most 2 * 105 calls will be made to insert; remove; and getRandom. There will be at least one element in the data structure when getRandom is called."118Meta,9,Palindrome Number,Easy,Math,Given an integer x; return true if x is a palindrome; and false otherwise. Example 1: Input: x = 121 Output: true Explanation: 121 reads as 121 from left to right and from right to left. Example 2: Input: x = -121 Output: false Explanation: From left to right; it reads -121. From right to left; it becomes 121-. Therefore it is not a palindrome. Example 3: Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Constraints: -231 <= x <= 231 - 1 Follow up: Could you solve it without converting the integer to a string?119Meta,16,3Sum Closest,Med,"Array, Two Pointers, Sorting",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. Example 1: 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). Example 2: Input: nums = [0;0;0]; target = 1 Output: 0 Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0). Constraints: 3 <= nums.length <= 500 -1000 <= nums[i] <= 1000 -104 <= target <= 104120Meta,19,Remove Nth Node From End of List,Med,"Linked List, Two Pointers",Given the head of a linked list; remove the nth node from the end of the list and return its head. Example 1: Input: head = [1;2;3;4;5]; n = 2 Output: [1;2;3;5] Example 2: Input: head = [1]; n = 1 Output: [] Example 3: Input: head = [1;2]; n = 1 Output: [1] Constraints: The number of nodes in the list is sz. 1 <= sz <= 30 0 <= Node.val <= 100 1 <= n <= sz Follow up: Could you do this in one pass?121Meta,127,Word Ladder,Hard,"Hash Table, String, Breadth-First Search","A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Every adjacent pair of words differs by a single letter. Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. sk == endWord Given two words; beginWord and endWord; and a dictionary wordList; return the number of words in the shortest transformation sequence from beginWord to endWord; or 0 if no such sequence exists. Example 1: Input: beginWord = ""hit""; endWord = ""cog""; wordList = [""hot"";""dot"";""dog"";""lot"";""log"";""cog""] Output: 5 Explanation: One shortest transformation sequence is ""hit"" -> ""hot"" -> ""dot"" -> ""dog"" -> cog""; which is 5 words long. Example 2: Input: beginWord = ""hit""; endWord = ""cog""; wordList = [""hot"";""dot"";""dog"";""lot"";""log""] Output: 0 Explanation: The endWord ""cog"" is not in wordList; therefore there is no valid transformation sequence. Constraints: 1 <= beginWord.length <= 10 endWord.length == beginWord.length 1 <= wordList.length <= 5000 wordList[i].length == beginWord.length beginWord; endWord; and wordList[i] consist of lowercase English letters. beginWord != endWord All the words in wordList are unique."122Meta,139,Word Break,Med,"Array, Hash Table, String, Dynamic Programming, Trie, Memoization","Given a string s and a dictionary of strings wordDict; return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation. Example 1: Input: s = ""leetcode""; wordDict = [""leet"";""code""] Output: true Explanation: Return true because ""leetcode"" can be segmented as ""leet code"". Example 2: Input: s = ""applepenapple""; wordDict = [""apple"";""pen""] Output: true Explanation: Return true because ""applepenapple"" can be segmented as ""apple pen apple"". Note that you are allowed to reuse a dictionary word. Example 3: Input: s = ""catsandog""; wordDict = [""cats"";""dog"";""sand"";""and"";""cat""] Output: false Constraints: 1 <= s.length <= 300 1 <= wordDict.length <= 1000 1 <= wordDict[i].length <= 20 s and wordDict[i] consist of only lowercase English letters. All the strings of wordDict are unique."123Meta,197,Rising Temperature,Easy,Database,Table: Weather +---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | recordDate | date | | temperature | int | +---------------+---------+ id is the column with unique values for this table. There are no different rows with the same recordDate. This table contains information about the temperature on a certain day. Write a solution to find all dates' id with higher temperatures compared to its previous dates (yesterday). Return the result table in any order. The result format is in the following example. Example 1: Input: Weather table: +----+------------+-------------+ | id | recordDate | temperature | +----+------------+-------------+ | 1 | 2015-01-01 | 10 | | 2 | 2015-01-02 | 25 | | 3 | 2015-01-03 | 20 | | 4 | 2015-01-04 | 30 | +----+------------+-------------+ Output: +----+ | id | +----+ | 2 | | 4 | +----+ Explanation: In 2015-01-02; the temperature was higher than the previous day (10 -> 25). In 2015-01-04; the temperature was higher than the previous day (20 -> 30).124Meta,198,House Robber,Med,"Array, Dynamic Programming",You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed; the only constraint stopping you from robbing each of them is that adjacent houses have security systems 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. Example 1: 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. Example 2: Input: nums = [2;7;9;3;1] Output: 12 Explanation: Rob house 1 (money = 2); rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 400125Meta,269,Alien Dictionary,Hard,"Array, String, Depth-First Search, Breadth-First Search, Graph, Topological Sort",126Meta,329,Longest Increasing Path in a Matrix,Hard,"Array, Dynamic Programming, Depth-First Search, Breadth-First Search, Graph, Topological Sort, Memoization, 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). Example 1: Input: matrix = [[9;9;4];[6;6;8];[2;1;1]] Output: 4 Explanation: The longest increasing path is [1; 2; 6; 9]. Example 2: Input: matrix = [[3;4;5];[3;2;6];[2;2;1]] Output: 4 Explanation: The longest increasing path is [3; 4; 5; 6]. Moving diagonally is not allowed. Example 3: Input: matrix = [[1]] Output: 1 Constraints: m == matrix.length n == matrix[i].length 1 <= m; n <= 200 0 <= matrix[i][j] <= 231 - 1127Meta,536,Construct Binary Tree from String,Med,"String, Stack, Tree, Depth-First Search, Binary Tree",128Meta,539,Minimum Time Difference,Med,"Array, Math, String, Sorting","Given a list of 24-hour clock time points in ""HH:MM"" format; return the minimum minutes difference between any two time-points in the list. Example 1: Input: timePoints = [""23:59"";""00:00""] Output: 1 Example 2: Input: timePoints = [""00:00"";""23:59"";""00:00""] Output: 0 Constraints: 2 <= timePoints.length <= 2 * 104 timePoints[i] is in the format ""HH:MM""."129Meta,658,Find K Closest Elements,Med,"Array, Two Pointers, Binary Search, Sliding Window, Sorting, Heap (Priority Queue)",Given a sorted integer array arr; two integers k and x; return the k closest integers to x in the array. The result should also be sorted in ascending order. An integer a is closer to x than an integer b if: |a - x| < |b - x|; or |a - x| == |b - x| and a < b Example 1: Input: arr = [1;2;3;4;5]; k = 4; x = 3 Output: [1;2;3;4] Example 2: Input: arr = [1;1;2;3;4;5]; k = 4; x = -1 Output: [1;1;2;3] Constraints: 1 <= k <= arr.length 1 <= arr.length <= 104 arr is sorted in ascending order. -104 <= arr[i]; x <= 104130Meta,735,Asteroid Collision,Med,"Array, Stack, Simulation",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. Example 1: Input: asteroids = [5;10;-5] Output: [5;10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide. Example 2: Input: asteroids = [8;-8] Output: [] Explanation: The 8 and -8 collide exploding each other. Example 3: Input: asteroids = [10;2;-5] Output: [10] Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. Constraints: 2 <= asteroids.length <= 104 -1000 <= asteroids[i] <= 1000 asteroids[i] != 0131Meta,824,Goat Latin,Easy,"Array, String","You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically; widths[0] is the width of 'a'; widths[1] is the width of 'b'; and so on. You are trying to write s across several lines; where each line is no longer than 100 pixels. Starting at the beginning of s; write as many letters on the first line such that the total width does not exceed 100 pixels. Then; from where you stopped in s; continue writing as many letters as you can on the second line. Continue this process until you have written all of s. Return an array result of length 2 where: result[0] is the total number of lines. result[1] is the width of the last line in pixels. Example 1: Input: widths = [10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10]; s = ""abcdefghijklmnopqrstuvwxyz"" Output: [3;60] Explanation: You can write s as follows: abcdefghij // 100 pixels wide klmnopqrst // 100 pixels wide uvwxyz // 60 pixels wide There are a total of 3 lines; and the last line is 60 pixels wide. Example 2: Input: widths = [4;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10;10]; s = ""bbbcccdddaaa"" Output: [2;4] Explanation: You can write s as follows: bbbcccdddaa // 98 pixels wide a // 4 pixels wide There are a total of 2 lines; and the last line is 4 pixels wide. Constraints: widths.length == 26 2 <= widths[i] <= 10 1 <= s.length <= 1000 s contains only lowercase English letters."132Meta,875,Koko Eating Bananas,Med,"Array, Two Pointers, Dynamic Programming, Enumeration",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. Example 1: 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. Example 2: Input: arr = [2;2;2] Output: 0 Explanation: There is no mountain. Constraints: 1 <= arr.length <= 104 0 <= arr[i] <= 104 Follow up: Can you solve it using only one pass? Can you solve it in O(1) space?133Meta,1216,Valid Palindrome III,Hard,Concurrency,"You have a function printNumber that can be called with an integer parameter and prints it to the console. For example; calling printNumber(7) prints 7 to the console. You are given an instance of the class ZeroEvenOdd that has three functions: zero; even; and odd. The same instance of ZeroEvenOdd will be passed to three different threads: Thread A: calls zero() that should only output 0's. Thread B: calls even() that should only output even numbers. Thread C: calls odd() that should only output odd numbers. Modify the given class to output the series ""010203040506..."" where the length of the series must be 2n. Implement the ZeroEvenOdd class: ZeroEvenOdd(int n) Initializes the object with the number n that represents the numbers that should be printed. void zero(printNumber) Calls printNumber to output one zero. void even(printNumber) Calls printNumber to output one even number. void odd(printNumber) Calls printNumber to output one odd number. Example 1: Input: n = 2 Output: ""0102"" Explanation: There are three threads being fired asynchronously. One of them calls zero(); the other calls even(); and the last one calls odd(). ""0102"" is the correct output. Example 2: Input: n = 5 Output: ""0102030405"" Constraints: 1 <= n <= 1000"134Meta,1424,Diagonal Traverse II,Med,"Array, Breadth-First Search, Graph",You have n boxes labeled from 0 to n - 1. You are given four arrays: status; candies; keys; and containedBoxes where: status[i] is 1 if the ith box is open and 0 if the ith box is closed; candies[i] is the number of candies in the ith box; keys[i] is a list of the labels of the boxes you can open after opening the ith box. containedBoxes[i] is a list of the boxes you found inside the ith box. You are given an integer array initialBoxes that contains the labels of the boxes you initially have. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it. Return the maximum number of candies you can get following the rules above. Example 1: Input: status = [1;0;1;0]; candies = [7;5;4;100]; keys = [[];[];[1];[]]; containedBoxes = [[1;2];[3];[];[]]; initialBoxes = [0] Output: 16 Explanation: You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2. Box 1 is closed and you do not have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2. In box 1; you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed. Total number of candies collected = 7 + 4 + 5 = 16 candy. Example 2: Input: status = [1;0;0;0;0;0]; candies = [1;1;1;1;1;1]; keys = [[1;2;3;4;5];[];[];[];[];[]]; containedBoxes = [[1;2;3;4;5];[];[];[];[];[]]; initialBoxes = [0] Output: 6 Explanation: You have initially box 0. Opening it you can find boxes 1;2;3;4 and 5 and their keys. The total number of candies will be 6. Constraints: n == status.length == candies.length == keys.length == containedBoxes.length 1 <= n <= 1000 status[i] is either 0 or 1. 1 <= candies[i] <= 1000 0 <= keys[i].length <= n 0 <= keys[i][j] < n All values of keys[i] are unique. 0 <= containedBoxes[i].length <= n 0 <= containedBoxes[i][j] < n All values of containedBoxes[i] are unique. Each box is contained in one box at most. 0 <= initialBoxes.length <= n 0 <= initialBoxes[i] < n135Meta,1757,Recyclable and Low Fat Products,Easy,"Array, Dynamic Programming, Breadth-First Search",A certain bug's home is on the x-axis at position x. Help them get there from position 0. The bug jumps according to the following rules: It can jump exactly a positions forward (to the right). It can jump exactly b positions backward (to the left). It cannot jump backward twice in a row. It cannot jump to any forbidden positions. The bug may jump forward beyond its home; but it cannot jump to positions numbered with negative integers. Given an array of integers forbidden; where forbidden[i] means that the bug cannot jump to the position forbidden[i]; and integers a; b; and x; return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x; return -1. Example 1: Input: forbidden = [14;4;18;1;15]; a = 3; b = 15; x = 9 Output: 3 Explanation: 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home. Example 2: Input: forbidden = [8;3;16;6;12;20]; a = 15; b = 13; x = 11 Output: -1 Example 3: Input: forbidden = [1;6;2;14;5;17;4]; a = 16; b = 9; x = 7 Output: 2 Explanation: One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home. Constraints: 1 <= forbidden.length <= 1000 1 <= a; b; forbidden[i] <= 2000 0 <= x <= 2000 All the elements in forbidden are distinct. Position x is not forbidden.136Meta,5,Longest Palindromic Substring,Med,"Two Pointers, String, Dynamic Programming","Given a string s; return the longest palindromic substring in s. Example 1: Input: s = ""babad"" Output: ""bab"" Explanation: ""aba"" is also a valid answer. Example 2: Input: s = ""cbbd"" Output: ""bb"" Constraints: 1 <= s.length <= 1000 s consist of only digits and English letters."137Meta,26,Remove Duplicates from Sorted Array,Easy,"Array, Two Pointers",Given an integer array nums sorted in non-decreasing order; remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums. Consider the number of unique elements of nums to be k; to get accepted; you need to do the following things: Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums. Return k. Custom Judge: The judge will test your solution with the following code: int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass; then your solution will be accepted. Example 1: Input: nums = [1;1;2] Output: 2; nums = [1;2;_] Explanation: Your function should return k = 2; with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). Example 2: Input: nums = [0;0;1;1;1;2;2;3;3;4] Output: 5; nums = [0;1;2;3;4;_;_;_;_;_] Explanation: Your function should return k = 5; with the first five elements of nums being 0; 1; 2; 3; and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). Constraints: 1 <= nums.length <= 3 * 104 -100 <= nums[i] <= 100 nums is sorted in non-decreasing order.138Meta,169,Majority Element,Easy,"Array, Hash Table, Divide and Conquer, Sorting, Counting",Given an array nums of size n; return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. Example 1: Input: nums = [3;2;3] Output: 3 Example 2: Input: nums = [2;2;1;1;1;2;2] Output: 2 Constraints: n == nums.length 1 <= n <= 5 * 104 -109 <= nums[i] <= 109 Follow-up: Could you solve the problem in linear time and in O(1) space?139Meta,238,Product of Array Except Self,Med,"Array, Prefix Sum",Given an integer array nums; return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation. Example 1: Input: nums = [1;2;3;4] Output: [24;12;8;6] Example 2: Input: nums = [-1;1;0;-3;3] Output: [0;0;9;0;0] Constraints: 2 <= nums.length <= 105 -30 <= nums[i] <= 30 The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)140Meta,378,Kth Smallest Element in a Sorted Matrix,Med,"Array, Binary Search, Sorting, Heap (Priority Queue), 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). Example 1: 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 Example 2: Input: matrix = [[-5]]; k = 1 Output: -5 Constraints: n == matrix.length == matrix[i].length 1 <= n <= 300 -109 <= matrix[i][j] <= 109 All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order. 1 <= k <= n2 Follow up: Could you solve the problem with a constant memory (i.e.; O(1) memory complexity)? Could you solve the problem in O(n) time complexity? The solution may be too advanced for an interview but you may find reading this paper fun.141Meta,443,String Compression,Med,"Two Pointers, String","Given an array of characters chars; compress it using the following algorithm: Begin with an empty string s. For each group of consecutive repeating characters in chars: If the group's length is 1; append the character to s. Otherwise; append the character followed by the group's length. The compressed string s should not be returned separately; but instead; be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars. After you are done modifying the input array; return the new length of the array. You must write an algorithm that uses only constant extra space. Example 1: Input: chars = [""a"";""a"";""b"";""b"";""c"";""c"";""c""] Output: Return 6; and the first 6 characters of the input array should be: [""a"";""2"";""b"";""2"";""c"";""3""] Explanation: The groups are ""aa""; ""bb""; and ""ccc"". This compresses to ""a2b2c3"". Example 2: Input: chars = [""a""] Output: Return 1; and the first character of the input array should be: [""a""] Explanation: The only group is ""a""; which remains uncompressed since it's a single character. Example 3: Input: chars = [""a"";""b"";""b"";""b"";""b"";""b"";""b"";""b"";""b"";""b"";""b"";""b"";""b""] Output: Return 4; and the first 4 characters of the input array should be: [""a"";""b"";""1"";""2""]. Explanation: The groups are ""a"" and ""bbbbbbbbbbbb"". This compresses to ""ab12"". Constraints: 1 <= chars.length <= 2000 chars[i] is a lowercase English letter; uppercase English letter; digit; or symbol."142Meta,480,Sliding Window Median,Hard,"Array, Hash Table, Sliding Window, Heap (Priority Queue)",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. Example 1: 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 Example 2: Input: nums = [1;2;3;4;2;3;1;4;2]; k = 3 Output: [2.00000;3.00000;3.00000;3.00000;2.00000;3.00000;2.00000] Constraints: 1 <= k <= nums.length <= 105 -231 <= nums[i] <= 231 - 1143Meta,647,Palindromic Substrings,Med,"Two Pointers, String, Dynamic Programming","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. Example 1: Input: s = ""abc"" Output: 3 Explanation: Three palindromic strings: ""a""; ""b""; ""c"". Example 2: Input: s = ""aaa"" Output: 6 Explanation: Six palindromic strings: ""a""; ""a""; ""a""; ""aa""; ""aa""; ""aaa"". Constraints: 1 <= s.length <= 1000 s consists of lowercase English letters."144Meta,1644,Lowest Common Ancestor of a Binary Tree II,Med,"String, Greedy","Given a string s of lowercase letters; you need to find the maximum number of non-empty substrings of s that meet the following conditions: The substrings do not overlap; that is for any two substrings s[i..j] and s[x..y]; either j < x or i > y is true. A substring that contains a certain character c must also contain all occurrences of c. Find the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings; return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length. Notice that you can return the substrings in any order. Example 1: Input: s = ""adefaddaccc"" Output: [""e"";""f"";""ccc""] Explanation: The following are all the possible substrings that meet the conditions: [ ""adefaddaccc"" ""adefadda""; ""ef""; ""e""; ""f""; ""ccc""; ] If we choose the first string; we cannot choose anything else and we'd get only 1. If we choose ""adefadda""; we are left with ""ccc"" which is the only one that doesn't overlap; thus obtaining 2 substrings. Notice also; that it's not optimal to choose ""ef"" since it can be split into two. Therefore; the optimal way is to choose [""e"";""f"";""ccc""] which gives us 3 substrings. No other solution of the same number of substrings exist. Example 2: Input: s = ""abbaccd"" Output: [""d"";""bb"";""cc""] Explanation: Notice that while the set of substrings [""d"";""abba"";""cc""] also has length 3; it's considered incorrect since it has larger total length. Constraints: 1 <= s.length <= 105 s contains only lowercase English letters."145Meta,1868,Product of Two Run-Length Encoded Arrays,Med,,146Meta,3,Longest Substring Without Repeating Characters,Med,"Hash Table, String, Sliding Window","Given a string s; find the length of the longest substring without repeating characters. Example 1: Input: s = ""abcabcbb"" Output: 3 Explanation: The answer is ""abc""; with the length of 3. Example 2: Input: s = ""bbbbb"" Output: 1 Explanation: The answer is ""b""; with the length of 1. Example 3: Input: s = ""pwwkew"" Output: 3 Explanation: The answer is ""wke""; with the length of 3. Notice that the answer must be a substring; ""pwke"" is a subsequence and not a substring. Constraints: 0 <= s.length <= 5 * 104 s consists of English letters; digits; symbols and spaces."147Meta,10,Regular Expression Matching,Hard,"String, Dynamic Programming, Recursion","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). Example 1: Input: s = ""aa""; p = ""a"" Output: false Explanation: ""a"" does not match the entire string ""aa"". Example 2: 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"". Example 3: Input: s = ""ab""; p = "".*"" Output: true Explanation: "".*"" means ""zero or more (*) of any character (.)"". Constraints: 1 <= s.length <= 20 1 <= p.length <= 20 s contains only lowercase English letters. p contains only lowercase English letters; '.'; and '*'. It is guaranteed for each appearance of the character '*'; there will be a previous valid character to match."148Meta,22,Generate Parentheses,Med,"String, Dynamic Programming, Backtracking","Given n pairs of parentheses; write a function to generate all combinations of well-formed parentheses. Example 1: Input: n = 3 Output: [""((()))"";""(()())"";""(())()"";""()(())"";""()()()""] Example 2: Input: n = 1 Output: [""()""] Constraints: 1 <= n <= 8"149Meta,38,Count and Say,Med,String,"The count-and-say sequence is a sequence of digit strings defined by the recursive formula: countAndSay(1) = ""1"" countAndSay(n) is the run-length encoding of countAndSay(n - 1). Run-length encoding (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example; to compress the string ""3322251"" we replace ""33"" with ""23""; replace ""222"" with ""32""; replace ""5"" with ""15"" and replace ""1"" with ""11"". Thus the compressed string becomes ""23321511"". Given a positive integer n; return the nth element of the count-and-say sequence. Example 1: Input: n = 4 Output: ""1211"" Explanation: countAndSay(1) = ""1"" countAndSay(2) = RLE of ""1"" = ""11"" countAndSay(3) = RLE of ""11"" = ""21"" countAndSay(4) = RLE of ""21"" = ""1211"" Example 2: Input: n = 1 Output: ""1"" Explanation: This is the base case. Constraints: 1 <= n <= 30 Follow up: Could you solve it iteratively?"150Meta,42,Trapping Rain Water,Hard,"Array, Two Pointers, Dynamic Programming, Stack, Monotonic Stack",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. Example 1: 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. Example 2: Input: height = [4;2;0;3;2;5] Output: 9 Constraints: n == height.length 1 <= n <= 2 * 104 0 <= height[i] <= 105151Meta,49,Group Anagrams,Med,"Array, Hash Table, String, Sorting","Given an array of strings strs; group the anagrams together. You can return the answer in any order. Example 1: Input: strs = [""eat"";""tea"";""tan"";""ate"";""nat"";""bat""] Output: [[""bat""];[""nat"";""tan""];[""ate"";""eat"";""tea""]] Explanation: There is no string in strs that can be rearranged to form ""bat"". The strings ""nat"" and ""tan"" are anagrams as they can be rearranged to form each other. The strings ""ate""; ""eat""; and ""tea"" are anagrams as they can be rearranged to form each other. Example 2: Input: strs = [""""] Output: [[""""]] Example 3: Input: strs = [""a""] Output: [[""a""]] Constraints: 1 <= strs.length <= 104 0 <= strs[i].length <= 100 strs[i] consists of lowercase English letters."152Meta,66,Plus One,Easy,"Array, Math",You are given a large integer represented as an integer array digits; where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. Increment the large integer by one and return the resulting array of digits. Example 1: Input: digits = [1;2;3] Output: [1;2;4] Explanation: The array represents the integer 123. Incrementing by one gives 123 + 1 = 124. Thus; the result should be [1;2;4]. Example 2: Input: digits = [4;3;2;1] Output: [4;3;2;2] Explanation: The array represents the integer 4321. Incrementing by one gives 4321 + 1 = 4322. Thus; the result should be [4;3;2;2]. Example 3: Input: digits = [9] Output: [1;0] Explanation: The array represents the integer 9. Incrementing by one gives 9 + 1 = 10. Thus; the result should be [1;0]. Constraints: 1 <= digits.length <= 100 0 <= digits[i] <= 9 digits does not contain any leading 0's.153Meta,78,Subsets,Med,"Array, Backtracking, Bit Manipulation",Given an integer array nums of unique elements; return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. Example 1: Input: nums = [1;2;3] Output: [[];[1];[2];[1;2];[3];[1;3];[2;3];[1;2;3]] Example 2: Input: nums = [0] Output: [[];[0]] Constraints: 1 <= nums.length <= 10 -10 <= nums[i] <= 10 All the numbers of nums are unique.154Meta,113,Path Sum II,Med,"Backtracking, Tree, Depth-First Search, Binary Tree",Given the root of a binary tree and an integer targetSum; return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values; not node references. A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children. Example 1: Input: root = [5;4;8;11;null;13;4;7;2;null;null;5;1]; targetSum = 22 Output: [[5;4;11;2];[5;8;4;5]] Explanation: There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 Example 2: Input: root = [1;2;3]; targetSum = 5 Output: [] Example 3: Input: root = [1;2]; targetSum = 0 Output: [] Constraints: The number of nodes in the tree is in the range [0; 5000]. -1000 <= Node.val <= 1000 -1000 <= targetSum <= 1000155Meta,124,Binary Tree Maximum Path Sum,Hard,"Dynamic Programming, Tree, Depth-First Search, Binary Tree",A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree; return the maximum path sum of any non-empty path. Example 1: Input: root = [1;2;3] Output: 6 Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. Example 2: Input: root = [-10;9;20;null;null;15;7] Output: 42 Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42. Constraints: The number of nodes in the tree is in the range [1; 3 * 104]. -1000 <= Node.val <= 1000156Meta,128,Longest Consecutive Sequence,Med,"Array, Hash Table, Union Find",Given an unsorted array of integers nums; return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time. Example 1: Input: nums = [100;4;200;1;3;2] Output: 4 Explanation: The longest consecutive elements sequence is [1; 2; 3; 4]. Therefore its length is 4. Example 2: Input: nums = [0;3;7;2;5;8;4;6;0;1] Output: 9 Constraints: 0 <= nums.length <= 105 -109 <= nums[i] <= 109157Meta,140,Word Break II,Hard,"Array, Hash Table, String, Dynamic Programming, Backtracking, Trie, Memoization","Given a string s and a dictionary of strings wordDict; add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order. Note that the same word in the dictionary may be reused multiple times in the segmentation. Example 1: Input: s = ""catsanddog""; wordDict = [""cat"";""cats"";""and"";""sand"";""dog""] Output: [""cats and dog"";""cat sand dog""] Example 2: Input: s = ""pineapplepenapple""; wordDict = [""apple"";""pen"";""applepen"";""pine"";""pineapple""] Output: [""pine apple pen apple"";""pineapple pen apple"";""pine applepen apple""] Explanation: Note that you are allowed to reuse a dictionary word. Example 3: Input: s = ""catsandog""; wordDict = [""cats"";""dog"";""sand"";""and"";""cat""] Output: [] Constraints: 1 <= s.length <= 20 1 <= wordDict.length <= 1000 1 <= wordDict[i].length <= 10 s and wordDict[i] consist of only lowercase English letters. All the strings of wordDict are unique. Input is generated in a way that the length of the answer doesn't exceed 105."158Meta,143,Reorder List,Med,"Linked List, Two Pointers, Stack, Recursion",You are given the head of a singly linked-list. The list can be represented as: L0 → L1 → … → Ln - 1 → Ln Reorder the list to be on the following form: L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … You may not modify the values in the list's nodes. Only nodes themselves may be changed. Example 1: Input: head = [1;2;3;4] Output: [1;4;2;3] Example 2: Input: head = [1;2;3;4;5] Output: [1;5;2;4;3] Constraints: The number of nodes in the list is in the range [1; 5 * 104]. 1 <= Node.val <= 1000159Meta,153,Find Minimum in Rotated Sorted Array,Med,"Array, Binary Search",Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example; the array nums = [0;1;2;4;5;6;7] might become: [4;5;6;7;0;1;2] if it was rotated 4 times. [0;1;2;4;5;6;7] if it was rotated 7 times. Notice that rotating an array [a[0]; a[1]; a[2]; ...; a[n-1]] 1 time results in the array [a[n-1]; a[0]; a[1]; a[2]; ...; a[n-2]]. Given the sorted rotated array nums of unique elements; return the minimum element of this array. You must write an algorithm that runs in O(log n) time. Example 1: Input: nums = [3;4;5;1;2] Output: 1 Explanation: The original array was [1;2;3;4;5] rotated 3 times. Example 2: Input: nums = [4;5;6;7;0;1;2] Output: 0 Explanation: The original array was [0;1;2;4;5;6;7] and it was rotated 4 times. Example 3: Input: nums = [11;13;15;17] Output: 11 Explanation: The original array was [11;13;15;17] and it was rotated 4 times. Constraints: n == nums.length 1 <= n <= 5000 -5000 <= nums[i] <= 5000 All the integers of nums are unique. nums is sorted and rotated between 1 and n times.160Meta,179,Largest Number,Med,"Array, String, Greedy, Sorting","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. Example 1: Input: nums = [10;2] Output: ""210"" Example 2: Input: nums = [3;30;34;5;9] Output: ""9534330"" Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 109"161Meta,206,Reverse Linked List,Easy,"Linked List, Recursion",Given the head of a singly linked list; reverse the list; and return the reversed list. Example 1: Input: head = [1;2;3;4;5] Output: [5;4;3;2;1] Example 2: Input: head = [1;2] Output: [2;1] Example 3: Input: head = [] Output: [] Constraints: The number of nodes in the list is the range [0; 5000]. -5000 <= Node.val <= 5000 Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?162Meta,246,Strobogrammatic Number,Easy,"Hash Table, Two Pointers, String",163Meta,348,Design Tic-Tac-Toe,Med,"Array, Hash Table, Design, Matrix, Simulation",164Meta,394,Decode String,Med,"String, Stack, Recursion","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. Example 1: Input: s = ""3[a]2[bc]"" Output: ""aaabcbc"" Example 2: Input: s = ""3[a2[c]]"" Output: ""accaccacc"" Example 3: Input: s = ""2[abc]3[cd]ef"" Output: ""abcabccdcdcdef"" Constraints: 1 <= s.length <= 30 s consists of lowercase English letters; digits; and square brackets '[]'. s is guaranteed to be a valid input. All the integers in s are in the range [1; 300]."165Meta,494,Target Sum,Med,"Array, Dynamic Programming, Backtracking","You are given an integer array nums and an integer target. You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers. For example; if nums = [2; 1]; you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression ""+2-1"". Return the number of different expressions that you can build; which evaluates to target. Example 1: Input: nums = [1;1;1;1;1]; target = 3 Output: 5 Explanation: There are 5 ways to assign symbols to make the sum of nums be target 3. -1 + 1 + 1 + 1 + 1 = 3 +1 - 1 + 1 + 1 + 1 = 3 +1 + 1 - 1 + 1 + 1 = 3 +1 + 1 + 1 - 1 + 1 = 3 +1 + 1 + 1 + 1 - 1 = 3 Example 2: Input: nums = [1]; target = 1 Output: 1 Constraints: 1 <= nums.length <= 20 0 <= nums[i] <= 1000 0 <= sum(nums[i]) <= 1000 -1000 <= target <= 1000"166Meta,825,Friends Of Appropriate Ages,Med,"Array, Greedy, Matrix",There is a city composed of n x n blocks; where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c. A city's skyline is the outer contour formed by all the building when viewing the side of the city from a distance. The skyline from each cardinal direction north; east; south; and west may be different. We are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0-height building can also be increased. However; increasing the height of a building should not affect the city's skyline from any cardinal direction. Return the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction. Example 1: Input: grid = [[3;0;8;4];[2;4;5;7];[9;2;6;3];[0;3;1;0]] Output: 35 Explanation: The building heights are shown in the center of the above image. The skylines when viewed from each cardinal direction are drawn in red. The grid after increasing the height of buildings without affecting skylines is: gridNew = [ [8; 4; 8; 7]; [7; 4; 7; 7]; [9; 4; 8; 7]; [3; 3; 3; 3] ] Example 2: Input: grid = [[0;0;0];[0;0;0];[0;0;0]] Output: 0 Explanation: Increasing the height of any building will result in the skyline changing. Constraints: n == grid.length n == grid[r].length 2 <= n <= 50 0 <= grid[r][c] <= 100167Meta,953,Verifying an Alien Dictionary,Easy,"Two Pointers, String","Given a string s; reverse the string according to the following rules: All the characters that are not English letters remain in the same position. All the English letters (lowercase or uppercase) should be reversed. Return s after reversing it. Example 1: Input: s = ""ab-cd"" Output: ""dc-ba"" Example 2: Input: s = ""a-bC-dEf-ghIj"" Output: ""j-Ih-gfE-dCba"" Example 3: Input: s = ""Test1ng-Leet=code-Q!"" Output: ""Qedo1ct-eeLg=ntse-T!"" Constraints: 1 <= s.length <= 100 s consists of characters with ASCII values in the range [33; 122]. s does not contain '\""' or '\\'."168Meta,977,Squares of a Sorted Array,Easy,"String, Dynamic Programming","Given a string s; return the number of distinct non-empty subsequences of s. Since the answer may be very large; return it modulo 109 + 7. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e.; ""ace"" is a subsequence of ""abcde"" while ""aec"" is not. Example 1: Input: s = ""abc"" Output: 7 Explanation: The 7 distinct subsequences are ""a""; ""b""; ""c""; ""ab""; ""ac""; ""bc""; and ""abc"". Example 2: Input: s = ""aba"" Output: 6 Explanation: The 6 distinct subsequences are ""a""; ""b""; ""ab""; ""aa""; ""ba""; and ""aba"". Example 3: Input: s = ""aaa"" Output: 3 Explanation: The 3 distinct subsequences are ""a""; ""aa"" and ""aaa"". Constraints: 1 <= s.length <= 2000 s consists of lowercase English letters."169Meta,2914,Minimum Number of Changes to Make Binary String Beautiful,Med,"Array, Binary Search, Breadth-First Search, Union Find, Matrix",You are given a 0-indexed 2D matrix grid of size n x n; where (r; c) represents: A cell containing a thief if grid[r][c] = 1 An empty cell if grid[r][c] = 0 You are initially positioned at cell (0; 0). In one move; you can move to any adjacent cell in the grid; including cells containing thieves. The safeness factor of a path on the grid is defined as the minimum manhattan distance from any cell in the path to any thief in the grid. Return the maximum safeness factor of all paths leading to cell (n - 1; n - 1). An adjacent cell of cell (r; c); is one of the cells (r; c + 1); (r; c - 1); (r + 1; c) and (r - 1; c) if it exists. The Manhattan distance between two cells (a; b) and (x; y) is equal to |a - x| + |b - y|; where |val| denotes the absolute value of val. Example 1: Input: grid = [[1;0;0];[0;0;0];[0;0;1]] Output: 0 Explanation: All paths from (0; 0) to (n - 1; n - 1) go through the thieves in cells (0; 0) and (n - 1; n - 1). Example 2: Input: grid = [[0;0;1];[0;0;0];[0;0;0]] Output: 2 Explanation: The path depicted in the picture above has a safeness factor of 2 since: - The closest cell of the path to the thief at cell (0; 2) is cell (0; 0). The distance between them is | 0 - 0 | + | 0 - 2 | = 2. It can be shown that there are no other paths with a higher safeness factor. Example 3: Input: grid = [[0;0;0;1];[0;0;0;0];[0;0;0;0];[1;0;0;0]] Output: 2 Explanation: The path depicted in the picture above has a safeness factor of 2 since: - The closest cell of the path to the thief at cell (0; 3) is cell (1; 2). The distance between them is | 0 - 1 | + | 3 - 2 | = 2. - The closest cell of the path to the thief at cell (3; 0) is cell (3; 2). The distance between them is | 3 - 3 | + | 0 - 2 | = 2. It can be shown that there are no other paths with a higher safeness factor. Constraints: 1 <= grid.length == n <= 400 grid[i].length == n grid[i][j] is either 0 or 1. There is at least one thief in the grid.170Meta,7,Reverse Integer,Med,Math,Given a signed 32-bit integer x; return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231; 231 - 1]; then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). Example 1: Input: x = 123 Output: 321 Example 2: Input: x = -123 Output: -321 Example 3: Input: x = 120 Output: 21 Constraints: -231 <= x <= 231 - 1171Meta,48,Rotate Image,Med,"Array, Math, Matrix",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. Example 1: Input: matrix = [[1;2;3];[4;5;6];[7;8;9]] Output: [[7;4;1];[8;5;2];[9;6;3]] Example 2: Input: matrix = [[5;1;9;11];[2;4;8;10];[13;3;6;7];[15;14;12;16]] Output: [[15;13;2;5];[14;3;4;1];[12;6;8;9];[16;7;10;11]] Constraints: n == matrix.length == matrix[i].length 1 <= n <= 20 -1000 <= matrix[i][j] <= 1000172Meta,53,Maximum Subarray,Med,"Array, Divide and Conquer, Dynamic Programming",Given an integer array nums; find the subarray with the largest sum; and return its sum. Example 1: Input: nums = [-2;1;-3;4;-1;2;1;-5;4] Output: 6 Explanation: The subarray [4;-1;2;1] has the largest sum 6. Example 2: Input: nums = [1] Output: 1 Explanation: The subarray [1] has the largest sum 1. Example 3: Input: nums = [5;4;-1;7;8] Output: 23 Explanation: The subarray [5;4;-1;7;8] has the largest sum 23. Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 Follow up: If you have figured out the O(n) solution; try coding another solution using the divide and conquer approach; which is more subtle.173Meta,57,Insert Interval,Med,Array,You are given an array of non-overlapping intervals intervals where intervals[i] = [starti; endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start; end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion. Note that you don't need to modify intervals in-place. You can make a new array and return it. Example 1: Input: intervals = [[1;3];[6;9]]; newInterval = [2;5] Output: [[1;5];[6;9]] Example 2: Input: intervals = [[1;2];[3;5];[6;7];[8;10];[12;16]]; newInterval = [4;8] Output: [[1;2];[3;10];[12;16]] Explanation: Because the new interval [4;8] overlaps with [3;5];[6;7];[8;10]. Constraints: 0 <= intervals.length <= 104 intervals[i].length == 2 0 <= starti <= endi <= 105 intervals is sorted by starti in ascending order. newInterval.length == 2 0 <= start <= end <= 105174Meta,116,Populating Next Right Pointers in Each Node,Med,"Linked List, Tree, Depth-First Search, Breadth-First Search, Binary Tree",You are given a perfect binary tree where all leaves are on the same level; and every parent has two children. The binary tree has the following definition: struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node; the next pointer should be set to NULL. Initially; all next pointers are set to NULL. Example 1: Input: root = [1;2;3;4;5;6;7] Output: [1;#;2;3;#;4;5;6;7;#] Explanation: Given the above perfect binary tree (Figure A); your function should populate each next pointer to point to its next right node; just like in Figure B. The serialized output is in level order as connected by the next pointers; with '#' signifying the end of each level. Example 2: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0; 212 - 1]. -1000 <= Node.val <= 1000 Follow-up: You may only use constant extra space. The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.175Meta,231,Power of Two,Easy,"Math, Bit Manipulation, Recursion",Given an integer n; return true if it is a power of two. Otherwise; return false. An integer n is a power of two; if there exists an integer x such that n == 2x. Example 1: Input: n = 1 Output: true Explanation: 20 = 1 Example 2: Input: n = 16 Output: true Explanation: 24 = 16 Example 3: Input: n = 3 Output: false Constraints: -231 <= n <= 231 - 1 Follow up: Could you solve it without loops/recursion?176Meta,278,First Bad Version,Easy,"Binary Search, Interactive",You are a product manager and currently leading a team to develop a new product. Unfortunately; the latest version of your product fails the quality check. Since each version is developed based on the previous version; all the versions after a bad version are also bad. Suppose you have n versions [1; 2; ...; n] and you want to find out the first bad one; which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. Example 1: Input: n = 5; bad = 4 Output: 4 Explanation: call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version. Example 2: Input: n = 1; bad = 1 Output: 1 Constraints: 1 <= bad <= n <= 231 - 1177Meta,295,Find Median from Data Stream,Hard,"Two Pointers, Design, Sorting, Heap (Priority Queue), 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. Example 1: 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 Constraints: -105 <= num <= 105 There will be at least one element in the data structure before calling findMedian. At most 5 * 104 calls will be made to addNum and findMedian. Follow up: If all integer numbers from the stream are in the range [0; 100]; how would you optimize your solution? If 99% of all integer numbers from the stream are in the range [0; 100]; how would you optimize your solution?"178Meta,301,Remove Invalid Parentheses,Hard,"String, Backtracking, Breadth-First Search","Given a string s that contains parentheses and letters; remove the minimum number of invalid parentheses to make the input string valid. Return a list of unique strings that are valid with the minimum number of removals. You may return the answer in any order. Example 1: Input: s = ""()())()"" Output: [""(())()"";""()()()""] Example 2: Input: s = ""(a)())()"" Output: [""(a())()"";""(a)()()""] Example 3: Input: s = "")("" Output: [""""] Constraints: 1 <= s.length <= 25 s consists of lowercase English letters and parentheses '(' and ')'. There will be at most 20 parentheses in s."179Meta,392,Is Subsequence,Easy,"Two Pointers, String, Dynamic Programming","Given two strings s and t; return true if s is a subsequence of t; or false otherwise. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e.; ""ace"" is a subsequence of ""abcde"" while ""aec"" is not). Example 1: Input: s = ""abc""; t = ""ahbgdc"" Output: true Example 2: Input: s = ""axc""; t = ""ahbgdc"" Output: false Constraints: 0 <= s.length <= 100 0 <= t.length <= 104 s and t consist only of lowercase English letters. Follow up: Suppose there are lots of incoming s; say s1; s2; ...; sk where k >= 109; and you want to check one by one to see if t has its subsequence. In this scenario; how would you change your code?"180Meta,796,Rotate String,Easy,Math,Given four integers sx; sy; tx; and ty; return true if it is possible to convert the point (sx; sy) to the point (tx; ty) through some operations; or false otherwise. The allowed operation on some point (x; y) is to convert it to either (x; x + y) or (x + y; y). Example 1: Input: sx = 1; sy = 1; tx = 3; ty = 5 Output: true Explanation: One series of moves that transforms the starting point to the target is: (1; 1) -> (1; 2) (1; 2) -> (3; 2) (3; 2) -> (3; 5) Example 2: Input: sx = 1; sy = 1; tx = 2; ty = 2 Output: false Example 3: Input: sx = 1; sy = 1; tx = 1; ty = 1 Output: true Constraints: 1 <= sx; sy; tx; ty <= 109181Meta,958,Check Completeness of a Binary Tree,Med,"Array, Two Pointers, Sorting",Given an array of integers nums; half of the integers in nums are odd; and the other half are even. Sort the array so that whenever nums[i] is odd; i is odd; and whenever nums[i] is even; i is even. Return any answer array that satisfies this condition. Example 1: Input: nums = [4;2;5;7] Output: [4;5;2;7] Explanation: [4;7;2;5]; [2;5;4;7]; [2;7;4;5] would also have been accepted. Example 2: Input: nums = [2;3] Output: [2;3] Constraints: 2 <= nums.length <= 2 * 104 nums.length is even. Half of the integers in nums are even. 0 <= nums[i] <= 1000 Follow Up: Could you solve it in-place?182Meta,1011,Capacity To Ship Packages Within D Days,Med,"Tree, Depth-First Search, Binary Tree",You are given the root of a binary tree with n nodes; where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage; which is the desired pre-order traversal of the binary tree. Any node in the binary tree can be flipped by swapping its left and right subtrees. For example; flipping node 1 will have the following effect: Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage. Return a list of the values of all flipped nodes. You may return the answer in any order. If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage; return the list [-1]. Example 1: Input: root = [1;2]; voyage = [2;1] Output: [-1] Explanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage. Example 2: Input: root = [1;2;3]; voyage = [1;3;2] Output: [1] Explanation: Flipping node 1 swaps nodes 2 and 3; so the pre-order traversal matches voyage. Example 3: Input: root = [1;2;3]; voyage = [1;2;3] Output: [] Explanation: The tree's pre-order traversal already matches voyage; so no nodes need to be flipped. Constraints: The number of nodes in the tree is n. n == voyage.length 1 <= n <= 100 1 <= Node.val; voyage[i] <= n All the values in the tree are unique. All the values in voyage are unique.183Meta,1609,Even Odd Tree,Med,"Tree, Depth-First Search, Breadth-First Search, Binary Tree",184Meta,3043,Find the Length of the Longest Common Prefix,Med,"Array, Breadth-First Search, Matrix",185Meta,21,Merge Two Sorted Lists,Easy,"Linked List, Recursion",You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list. Example 1: Input: list1 = [1;2;4]; list2 = [1;3;4] Output: [1;1;2;3;4;4] Example 2: Input: list1 = []; list2 = [] Output: [] Example 3: Input: list1 = []; list2 = [0] Output: [0] Constraints: The number of nodes in both lists is in the range [0; 50]. -100 <= Node.val <= 100 Both list1 and list2 are sorted in non-decreasing order.186Meta,27,Remove Element,Easy,"Array, Two Pointers",Given an integer array nums and an integer val; remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val. Consider the number of elements in nums which are not equal to val be k; to get accepted; you need to do the following things: Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums. Return k. Custom Judge: The judge will test your solution with the following code: int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums; val); // Calls your implementation assert k == expectedNums.length; sort(nums; 0; k); // Sort the first k elements of nums for (int i = 0; i < actualLength; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass; then your solution will be accepted. Example 1: Input: nums = [3;2;2;3]; val = 3 Output: 2; nums = [2;2;_;_] Explanation: Your function should return k = 2; with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). Example 2: Input: nums = [0;1;2;2;3;0;4;2]; val = 2 Output: 5; nums = [0;1;4;0;3;_;_;_] Explanation: Your function should return k = 5; with the first five elements of nums containing 0; 0; 1; 3; and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). Constraints: 0 <= nums.length <= 100 0 <= nums[i] <= 50 0 <= val <= 100187Meta,33,Search in Rotated Sorted Array,Med,"Array, Binary Search",There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function; nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k]; nums[k+1]; ...; nums[n-1]; nums[0]; nums[1]; ...; nums[k-1]] (0-indexed). For example; [0;1;2;4;5;6;7] might be rotated at pivot index 3 and become [4;5;6;7;0;1;2]. Given the array nums after the possible rotation and an integer target; return the index of target if it is in nums; or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [4;5;6;7;0;1;2]; target = 0 Output: 4 Example 2: Input: nums = [4;5;6;7;0;1;2]; target = 3 Output: -1 Example 3: Input: nums = [1]; target = 0 Output: -1 Constraints: 1 <= nums.length <= 5000 -104 <= nums[i] <= 104 All values of nums are unique. nums is an ascending array that is possibly rotated. -104 <= target <= 104188Meta,43,Multiply Strings,Med,"Math, String, Simulation","Given two non-negative integers num1 and num2 represented as strings; return the product of num1 and num2; also represented as a string. Note: You must not use any built-in BigInteger library or convert the inputs to integer directly. Example 1: Input: num1 = ""2""; num2 = ""3"" Output: ""6"" Example 2: Input: num1 = ""123""; num2 = ""456"" Output: ""56088"" Constraints: 1 <= num1.length; num2.length <= 200 num1 and num2 consist of digits only. Both num1 and num2 do not contain any leading zero; except the number 0 itself."189Meta,44,Wildcard Matching,Hard,"String, Dynamic Programming, Greedy, Recursion","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). Example 1: Input: s = ""aa""; p = ""a"" Output: false Explanation: ""a"" does not match the entire string ""aa"". Example 2: Input: s = ""aa""; p = ""*"" Output: true Explanation: '*' matches any sequence. Example 3: Input: s = ""cb""; p = ""?a"" Output: false Explanation: '?' matches 'c'; but the second letter is 'a'; which does not match 'b'. Constraints: 0 <= s.length; p.length <= 2000 s contains only lowercase English letters. p contains only lowercase English letters; '?' or '*'."190Meta,55,Jump Game,Med,"Array, Dynamic Programming, Greedy",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. Example 1: 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. Example 2: 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. Constraints: 1 <= nums.length <= 104 0 <= nums[i] <= 105191Meta,63,Unique Paths II,Med,"Array, Dynamic Programming, Matrix",You are given an m x n integer array grid. There is a robot 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. An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner. The testcases are generated so that the answer will be less than or equal to 2 * 109. Example 1: Input: obstacleGrid = [[0;0;0];[0;1;0];[0;0;0]] Output: 2 Explanation: There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right Example 2: Input: obstacleGrid = [[0;1];[0;0]] Output: 1 Constraints: m == obstacleGrid.length n == obstacleGrid[i].length 1 <= m; n <= 100 obstacleGrid[i][j] is 0 or 1.192Meta,70,Climbing Stairs,Easy,"Math, Dynamic Programming, Memoization",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? Example 1: Input: n = 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: Input: n = 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step Constraints: 1 <= n <= 45193Meta,75,Sort Colors,Med,"Array, Two Pointers, Sorting",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. Example 1: Input: nums = [2;0;2;1;1;0] Output: [0;0;1;1;2;2] Example 2: Input: nums = [2;0;1] Output: [0;1;2] Constraints: n == nums.length 1 <= n <= 300 nums[i] is either 0; 1; or 2. Follow up: Could you come up with a one-pass algorithm using only constant extra space?194Meta,84,Largest Rectangle in Histogram,Hard,"Array, Stack, Monotonic Stack",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 1: Input: heights = [2;1;5;6;2;3] Output: 10 Explanation: The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area; which has an area = 10 units. Example 2: Input: heights = [2;4] Output: 4 Constraints: 1 <= heights.length <= 105 0 <= heights[i] <= 104195Meta,91,Decode Ways,Med,"String, Dynamic Programming","You have intercepted a secret message encoded as a string of numbers. The message is decoded via the following mapping: ""1"" -> 'A' ""2"" -> 'B' ... ""25"" -> 'Y' ""26"" -> 'Z' However; while decoding the message; you realize that there are many different ways you can decode the message because some codes are contained in other codes (""2"" and ""5"" vs ""25""). For example; ""11106"" can be decoded into: ""AAJF"" with the grouping (1; 1; 10; 6) ""KJF"" with the grouping (11; 10; 6) The grouping (1; 11; 06) is invalid because ""06"" is not a valid code (only ""6"" is valid). Note: there may be strings that are impossible to decode. Given a string s containing only digits; return the number of ways to decode it. If the entire string cannot be decoded in any valid way; return 0. The test cases are generated so that the answer fits in a 32-bit integer. Example 1: Input: s = ""12"" Output: 2 Explanation: ""12"" could be decoded as ""AB"" (1 2) or ""L"" (12). Example 2: Input: s = ""226"" Output: 3 Explanation: ""226"" could be decoded as ""BZ"" (2 26); ""VF"" (22 6); or ""BBF"" (2 2 6). Example 3: Input: s = ""06"" Output: 0 Explanation: ""06"" cannot be mapped to ""F"" because of the leading zero (""6"" is different from ""06""). In this case; the string is not a valid encoding; so return 0. Constraints: 1 <= s.length <= 100 s contains only digits and may contain leading zero(s)."196Meta,103,Binary Tree Zigzag Level Order Traversal,Med,"Tree, Breadth-First Search, Binary Tree",Given the root of a binary tree; return the zigzag level order traversal of its nodes' values. (i.e.; from left to right; then right to left for the next level and alternate between). Example 1: Input: root = [3;9;20;null;null;15;7] Output: [[3];[20;9];[15;7]] Example 2: Input: root = [1] Output: [[1]] Example 3: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0; 2000]. -100 <= Node.val <= 100197Meta,104,Maximum Depth of Binary Tree,Easy,"Tree, Depth-First Search, Breadth-First Search, Binary Tree",Given the root of a binary tree; return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Example 1: Input: root = [3;9;20;null;null;15;7] Output: 3 Example 2: Input: root = [1;null;2] Output: 2 Constraints: The number of nodes in the tree is in the range [0; 104]. -100 <= Node.val <= 100198Meta,109,Convert Sorted List to Binary Search Tree,Med,"Linked List, Divide and Conquer, Tree, Binary Search Tree, Binary Tree",Given the head of a singly linked list where elements are sorted in ascending order; convert it to a height-balanced binary search tree. Example 1: Input: head = [-10;-3;0;5;9] Output: [0;-3;9;-10;null;5] Explanation: One possible answer is [0;-3;9;-10;null;5]; which represents the shown height balanced BST. Example 2: Input: head = [] Output: [] Constraints: The number of nodes in head is in the range [0; 2 * 104]. -105 <= Node.val <= 105199Meta,114,Flatten Binary Tree to Linked List,Med,"Linked List, Stack, Tree, Depth-First Search, Binary Tree","Given the root of a binary tree; flatten the tree into a ""linked list"": The ""linked list"" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. The ""linked list"" should be in the same order as a pre-order traversal of the binary tree. Example 1: Input: root = [1;2;5;3;4;null;6] Output: [1;null;2;null;3;null;4;null;5;null;6] Example 2: Input: root = [] Output: [] Example 3: Input: root = [0] Output: [0] Constraints: The number of nodes in the tree is in the range [0; 2000]. -100 <= Node.val <= 100 Follow up: Can you flatten the tree in-place (with O(1) extra space)?"200Meta,118,Pascal's Triangle,Easy,"Array, Dynamic Programming",Given an integer numRows; return the first numRows of Pascal's triangle. In Pascal's triangle; each number is the sum of the two numbers directly above it as shown: Example 1: Input: numRows = 5 Output: [[1];[1;1];[1;2;1];[1;3;3;1];[1;4;6;4;1]] Example 2: Input: numRows = 1 Output: [[1]] Constraints: 1 <= numRows <= 30201Meta,142,Linked List Cycle II,Med,"Hash Table, Linked List, Two Pointers",Given the head of a linked list; return the node where the cycle begins. If there is no cycle; return null. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally; pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter. Do not modify the linked list. Example 1: Input: head = [3;2;0;-4]; pos = 1 Output: tail connects to node index 1 Explanation: There is a cycle in the linked list; where tail connects to the second node. Example 2: Input: head = [1;2]; pos = 0 Output: tail connects to node index 0 Explanation: There is a cycle in the linked list; where tail connects to the first node. Example 3: Input: head = [1]; pos = -1 Output: no cycle Explanation: There is no cycle in the linked list. Constraints: The number of the nodes in the list is in the range [0; 104]. -105 <= Node.val <= 105 pos is -1 or a valid index in the linked-list. Follow up: Can you solve it using O(1) (i.e. constant) memory?202Meta,145,Binary Tree Postorder Traversal,Easy,"Stack, Tree, Depth-First Search, Binary Tree",Given the root of a binary tree; return the postorder traversal of its nodes' values. Example 1: Input: root = [1;null;2;3] Output: [3;2;1] Explanation: Example 2: Input: root = [1;2;3;4;5;null;8;null;null;6;7;9] Output: [4;6;7;5;2;9;8;3;1] Explanation: Example 3: Input: root = [] Output: [] Example 4: Input: root = [1] Output: [1] Constraints: The number of the nodes in the tree is in the range [0; 100]. -100 <= Node.val <= 100 Follow up: Recursive solution is trivial; could you do it iteratively?203Meta,151,Reverse Words in a String,Med,"Two Pointers, 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. Example 1: Input: s = ""the sky is blue"" Output: ""blue is sky the"" Example 2: Input: s = "" hello world "" Output: ""world hello"" Explanation: Your reversed string should not contain leading or trailing spaces. Example 3: 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. Constraints: 1 <= s.length <= 104 s contains English letters (upper-case and lower-case); digits; and spaces ' '. There is at least one word in s. Follow-up: If the string data type is mutable in your language; can you solve it in-place with O(1) extra space?"204Meta,224,Basic Calculator,Hard,"Math, String, Stack, Recursion","Given a string s representing a valid expression; implement a basic calculator to evaluate it; and return the result of the evaluation. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions; such as eval(). Example 1: Input: s = ""1 + 1"" Output: 2 Example 2: Input: s = "" 2-1 + 2 "" Output: 3 Example 3: Input: s = ""(1+(4+5+2)-3)+(6+8)"" Output: 23 Constraints: 1 <= s.length <= 3 * 105 s consists of digits; '+'; '-'; '('; ')'; and ' '. s represents a valid expression. '+' is not used as a unary operation (i.e.; ""+1"" and ""+(2 + 3)"" is invalid). '-' could be used as a unary operation (i.e.; ""-1"" and ""-(2 + 3)"" is valid). There will be no two consecutive operators in the input. Every number and running calculation will fit in a signed 32-bit integer."205Meta,239,Sliding Window Maximum,Hard,"Array, Queue, Sliding Window, Heap (Priority Queue), Monotonic Queue",You are given an array of integers nums; 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 max sliding window. Example 1: Input: nums = [1;3;-1;-3;5;3;6;7]; k = 3 Output: [3;3;5;5;6;7] Explanation: Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 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 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 Example 2: Input: nums = [1]; k = 1 Output: [1] Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 1 <= k <= nums.length206Meta,273,Integer to English Words,Hard,"Math, String, Recursion","Convert a non-negative integer num to its English words representation. Example 1: Input: num = 123 Output: ""One Hundred Twenty Three"" Example 2: Input: num = 12345 Output: ""Twelve Thousand Three Hundred Forty Five"" Example 3: Input: num = 1234567 Output: ""One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"" Constraints: 0 <= num <= 231 - 1"207Meta,317,Shortest Distance from All Buildings,Hard,"Array, Breadth-First Search, Matrix",208Meta,322,Coin Change,Med,"Array, Dynamic Programming, Breadth-First Search",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. Example 1: Input: coins = [1;2;5]; amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1 Example 2: Input: coins = [2]; amount = 3 Output: -1 Example 3: Input: coins = [1]; amount = 0 Output: 0 Constraints: 1 <= coins.length <= 12 1 <= coins[i] <= 231 - 1 0 <= amount <= 104209Meta,333,Largest BST Subtree,Med,"Dynamic Programming, Tree, Depth-First Search, Binary Search Tree, Binary Tree",210Meta,419,Battleships in a Board,Med,"Array, Depth-First Search, Matrix","Given an m x n matrix board where each cell is a battleship 'X' or empty '.'; return the number of the battleships on board. Battleships can only be placed horizontally or vertically on board. In other words; they can only be made of the shape 1 x k (1 row; k columns) or k x 1 (k rows; 1 column); where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e.; there are no adjacent battleships). Example 1: Input: board = [[""X"";""."";""."";""X""];[""."";""."";""."";""X""];[""."";""."";""."";""X""]] Output: 2 Example 2: Input: board = [["".""]] Output: 0 Constraints: m == board.length n == board[i].length 1 <= m; n <= 200 board[i][j] is either '.' or 'X'. Follow up: Could you do it in one-pass; using only O(1) extra memory and without modifying the values board?"211Meta,432,All O`one Data Structure,Hard,"Hash Table, Linked List, Design, Doubly-Linked List","Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts. Implement the AllOne class: AllOne() Initializes the object of the data structure. inc(String key) Increments the count of the string key by 1. If key does not exist in the data structure; insert it with count 1. dec(String key) Decrements the count of the string key by 1. If the count of key is 0 after the decrement; remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement. getMaxKey() Returns one of the keys with the maximal count. If no element exists; return an empty string """". getMinKey() Returns one of the keys with the minimum count. If no element exists; return an empty string """". Note that each function must run in O(1) average time complexity. Example 1: Input [""AllOne""; ""inc""; ""inc""; ""getMaxKey""; ""getMinKey""; ""inc""; ""getMaxKey""; ""getMinKey""] [[]; [""hello""]; [""hello""]; []; []; [""leet""]; []; []] Output [null; null; null; ""hello""; ""hello""; null; ""hello""; ""leet""] Explanation AllOne allOne = new AllOne(); allOne.inc(""hello""); allOne.inc(""hello""); allOne.getMaxKey(); // return ""hello"" allOne.getMinKey(); // return ""hello"" allOne.inc(""leet""); allOne.getMaxKey(); // return ""hello"" allOne.getMinKey(); // return ""leet"" Constraints: 1 <= key.length <= 10 key consists of lowercase English letters. It is guaranteed that for each call to dec; key is existing in the data structure. At most 5 * 104 calls will be made to inc; dec; getMaxKey; and getMinKey."212Meta,529,Minesweeper,Med,"Array, Depth-First Search, Breadth-First Search, Matrix","Let's play the minesweeper game (Wikipedia; online game)! You are given an m x n char matrix board representing the game board where: 'M' represents an unrevealed mine; 'E' represents an unrevealed empty square; 'B' represents a revealed blank square that has no adjacent mines (i.e.; above; below; left; right; and all 4 diagonals); digit ('1' to '8') represents how many mines are adjacent to this revealed square; and 'X' represents a revealed mine. You are also given an integer array click where click = [clickr; clickc] represents the next click position among all the unrevealed squares ('M' or 'E'). Return the board after revealing this position according to the following rules: If a mine 'M' is revealed; then the game is over. You should change it to 'X'. If an empty square 'E' with no adjacent mines is revealed; then change it to a revealed blank 'B' and all of its adjacent unrevealed squares should be revealed recursively. If an empty square 'E' with at least one adjacent mine is revealed; then change it to a digit ('1' to '8') representing the number of adjacent mines. Return the board when no more squares will be revealed. Example 1: Input: board = [[""E"";""E"";""E"";""E"";""E""];[""E"";""E"";""M"";""E"";""E""];[""E"";""E"";""E"";""E"";""E""];[""E"";""E"";""E"";""E"";""E""]]; click = [3;0] Output: [[""B"";""1"";""E"";""1"";""B""];[""B"";""1"";""M"";""1"";""B""];[""B"";""1"";""1"";""1"";""B""];[""B"";""B"";""B"";""B"";""B""]] Example 2: Input: board = [[""B"";""1"";""E"";""1"";""B""];[""B"";""1"";""M"";""1"";""B""];[""B"";""1"";""1"";""1"";""B""];[""B"";""B"";""B"";""B"";""B""]]; click = [1;2] Output: [[""B"";""1"";""E"";""1"";""B""];[""B"";""1"";""X"";""1"";""B""];[""B"";""1"";""1"";""1"";""B""];[""B"";""B"";""B"";""B"";""B""]] Constraints: m == board.length n == board[i].length 1 <= m; n <= 50 board[i][j] is either 'M'; 'E'; 'B'; or a digit from '1' to '8'. click.length == 2 0 <= clickr < m 0 <= clickc < n board[clickr][clickc] is either 'M' or 'E'."213Meta,545,Boundary of Binary Tree,Med,"Tree, Depth-First Search, Binary Tree",214Meta,616,Add Bold Tag in String,Med,"Array, Hash Table, String, Trie, String Matching",215Meta,739,Daily Temperatures,Med,"Array, Stack, Monotonic Stack",Given an array of integers temperatures represents the daily temperatures; return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible; keep answer[i] == 0 instead. Example 1: Input: temperatures = [73;74;75;71;69;72;76;73] Output: [1;1;4;2;1;1;0;0] Example 2: Input: temperatures = [30;40;50;60] Output: [1;1;1;0] Example 3: Input: temperatures = [30;60;90] Output: [1;1;0] Constraints: 1 <= temperatures.length <= 105 30 <= temperatures[i] <= 100216Meta,767,Reorganize String,Med,"Math, Bit Manipulation",Given two integers left and right; return the count of numbers in the inclusive range [left; right] having a prime number of set bits in their binary representation. Recall that the number of set bits an integer has is the number of 1's present when written in binary. For example; 21 written in binary is 10101; which has 3 set bits. Example 1: Input: left = 6; right = 10 Output: 4 Explanation: 6 -> 110 (2 set bits; 2 is prime) 7 -> 111 (3 set bits; 3 is prime) 8 -> 1000 (1 set bit; 1 is not prime) 9 -> 1001 (2 set bits; 2 is prime) 10 -> 1010 (2 set bits; 2 is prime) 4 numbers have a prime number of set bits. Example 2: Input: left = 10; right = 15 Output: 5 Explanation: 10 -> 1010 (2 set bits; 2 is prime) 11 -> 1011 (3 set bits; 3 is prime) 12 -> 1100 (2 set bits; 2 is prime) 13 -> 1101 (3 set bits; 3 is prime) 14 -> 1110 (3 set bits; 3 is prime) 15 -> 1111 (4 set bits; 4 is not prime) 5 numbers have a prime number of set bits. Constraints: 1 <= left <= right <= 106 0 <= right - left <= 104217Meta,930,Binary Subarrays With Sum,Med,"Dynamic Programming, Tree, Recursion, Memoization, Binary Tree",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. Example 1: 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]] Example 2: Input: n = 3 Output: [[0;0;0]] Constraints: 1 <= n <= 20218Meta,934,Shortest Bridge,Med,"Array, Dynamic Programming, Bit Manipulation",Given an integer array arr; return the number of distinct bitwise ORs of all the non-empty subarrays of arr. The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: arr = [0] Output: 1 Explanation: There is only one possible result: 0. Example 2: Input: arr = [1;1;2] Output: 3 Explanation: The possible subarrays are [1]; [1]; [2]; [1; 1]; [1; 2]; [1; 1; 2]. These yield the results 1; 1; 2; 1; 3; 3. There are 3 unique values; so the answer is 3. Example 3: Input: arr = [1;2;4] Output: 6 Explanation: The possible results are 1; 2; 3; 4; 6; and 7. Constraints: 1 <= arr.length <= 5 * 104 0 <= arr[i] <= 109219Meta,1371,Find the Longest Substring Containing Vowels in Even Counts,Med,"String, Stack","Given a string s of '(' ; ')' and lowercase English characters. Your task is to remove the minimum number of parentheses ( '(' or ')'; in any positions ) so that the resulting parentheses string is valid and return any valid string. Formally; a parentheses string is valid if and only if: It is the empty string; contains only lowercase characters; or It can be written as AB (A concatenated with B); where A and B are valid strings; or It can be written as (A); where A is a valid string. Example 1: Input: s = ""lee(t(c)o)de)"" Output: ""lee(t(c)o)de"" Explanation: ""lee(t(co)de)"" ; ""lee(t(c)ode)"" would also be accepted. Example 2: Input: s = ""a)b(c)d"" Output: ""ab(c)d"" Example 3: Input: s = ""))(("" Output: """" Explanation: An empty string is also valid. Constraints: 1 <= s.length <= 105 s[i] is either '(' ; ')'; or lowercase English letter."220Meta,12,Integer to Roman,Med,"Hash Table, Math, String","Seven different symbols represent Roman numerals with the following values: Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 Roman numerals are formed by appending the conversions of decimal place values from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules: If the value does not start with 4 or 9; select the symbol of the maximal value that can be subtracted from the input; append that symbol to the result; subtract its value; and convert the remainder to a Roman numeral. If the value starts with 4 or 9 use the subtractive form representing one symbol subtracted from the following symbol; for example; 4 is 1 (I) less than 5 (V): IV and 9 is 1 (I) less than 10 (X): IX. Only the following subtractive forms are used: 4 (IV); 9 (IX); 40 (XL); 90 (XC); 400 (CD) and 900 (CM). Only powers of 10 (I; X; C; M) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5 (V); 50 (L); or 500 (D) multiple times. If you need to append a symbol 4 times use the subtractive form. Given an integer; convert it to a Roman numeral. Example 1: Input: num = 3749 Output: ""MMMDCCXLIX"" Explanation: 3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M) 700 = DCC as 500 (D) + 100 (C) + 100 (C) 40 = XL as 10 (X) less of 50 (L) 9 = IX as 1 (I) less of 10 (X) Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places Example 2: Input: num = 58 Output: ""LVIII"" Explanation: 50 = L 8 = VIII Example 3: Input: num = 1994 Output: ""MCMXCIV"" Explanation: 1000 = M 900 = CM 90 = XC 4 = IV Constraints: 1 <= num <= 3999"221Meta,25,Reverse Nodes in k-Group,Hard,"Linked List, Recursion",Given the head of a linked list; reverse the nodes of the list k at a time; and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes; in the end; should remain as it is. You may not alter the values in the list's nodes; only nodes themselves may be changed. Example 1: Input: head = [1;2;3;4;5]; k = 2 Output: [2;1;4;3;5] Example 2: Input: head = [1;2;3;4;5]; k = 3 Output: [3;2;1;4;5] Constraints: The number of nodes in the list is n. 1 <= k <= n <= 5000 0 <= Node.val <= 1000 Follow-up: Can you solve the problem in O(1) extra memory space?222Meta,29,Divide Two Integers,Med,"Math, Bit Manipulation",Given two integers dividend and divisor; divide two integers without using multiplication; division; and mod operator. The integer division should truncate toward zero; which means losing its fractional part. For example; 8.345 would be truncated to 8; and -2.7335 would be truncated to -2. Return the quotient after dividing dividend by divisor. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231; 231 − 1]. For this problem; if the quotient is strictly greater than 231 - 1; then return 231 - 1; and if the quotient is strictly less than -231; then return -231. Example 1: Input: dividend = 10; divisor = 3 Output: 3 Explanation: 10/3 = 3.33333.. which is truncated to 3. Example 2: Input: dividend = 7; divisor = -3 Output: -2 Explanation: 7/-3 = -2.33333.. which is truncated to -2. Constraints: -231 <= dividend; divisor <= 231 - 1 divisor != 0223Meta,37,Sudoku Solver,Hard,"Array, Hash Table, Backtracking, Matrix","Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: Each of the digits 1-9 must occur exactly once in each row. Each of the digits 1-9 must occur exactly once in each column. Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. The '.' character indicates empty cells. Example 1: Input: board = [[""5"";""3"";""."";""."";""7"";""."";""."";""."";"".""];[""6"";""."";""."";""1"";""9"";""5"";""."";""."";"".""];[""."";""9"";""8"";""."";""."";""."";""."";""6"";"".""];[""8"";""."";""."";""."";""6"";""."";""."";""."";""3""];[""4"";""."";""."";""8"";""."";""3"";""."";""."";""1""];[""7"";""."";""."";""."";""2"";""."";""."";""."";""6""];[""."";""6"";""."";""."";""."";""."";""2"";""8"";"".""];[""."";""."";""."";""4"";""1"";""9"";""."";""."";""5""];[""."";""."";""."";""."";""8"";""."";""."";""7"";""9""]] Output: [[""5"";""3"";""4"";""6"";""7"";""8"";""9"";""1"";""2""];[""6"";""7"";""2"";""1"";""9"";""5"";""3"";""4"";""8""];[""1"";""9"";""8"";""3"";""4"";""2"";""5"";""6"";""7""];[""8"";""5"";""9"";""7"";""6"";""1"";""4"";""2"";""3""];[""4"";""2"";""6"";""8"";""5"";""3"";""7"";""9"";""1""];[""7"";""1"";""3"";""9"";""2"";""4"";""8"";""5"";""6""];[""9"";""6"";""1"";""5"";""3"";""7"";""2"";""8"";""4""];[""2"";""8"";""7"";""4"";""1"";""9"";""6"";""3"";""5""];[""3"";""4"";""5"";""2"";""8"";""6"";""1"";""7"";""9""]] Explanation: The input board is shown above and the only valid solution is shown below: Constraints: board.length == 9 board[i].length == 9 board[i][j] is a digit or '.'. It is guaranteed that the input board has only one solution."224Meta,40,Combination Sum II,Med,"Array, Backtracking",Given a collection of candidate numbers (candidates) and a target number (target); find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations. Example 1: Input: candidates = [10;1;2;7;6;1;5]; target = 8 Output: [ [1;1;6]; [1;2;5]; [1;7]; [2;6] ] Example 2: Input: candidates = [2;5;2;1;2]; target = 5 Output: [ [1;2;2]; [5] ] Constraints: 1 <= candidates.length <= 100 1 <= candidates[i] <= 50 1 <= target <= 30225Meta,54,Spiral Matrix,Med,"Array, Matrix, Simulation",Given an m x n matrix; return all elements of the matrix in spiral order. Example 1: Input: matrix = [[1;2;3];[4;5;6];[7;8;9]] Output: [1;2;3;6;9;8;7;4;5] Example 2: Input: matrix = [[1;2;3;4];[5;6;7;8];[9;10;11;12]] Output: [1;2;3;4;8;12;11;10;9;5;6;7] Constraints: m == matrix.length n == matrix[i].length 1 <= m; n <= 10 -100 <= matrix[i][j] <= 100226Meta,62,Unique Paths,Med,"Math, Dynamic Programming, Combinatorics",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. Example 1: Input: m = 3; n = 7 Output: 28 Example 2: Input: m = 3; n = 2 Output: 3 Explanation: From the top-left corner; there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down Constraints: 1 <= m; n <= 100227Meta,72,Edit Distance,Med,"String, Dynamic Programming","Given two strings word1 and word2; return the minimum number of operations required to convert word1 to word2. You have the following three operations permitted on a word: Insert a character Delete a character Replace a character Example 1: Input: word1 = ""horse""; word2 = ""ros"" Output: 3 Explanation: horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') Example 2: Input: word1 = ""intention""; word2 = ""execution"" Output: 5 Explanation: intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') Constraints: 0 <= word1.length; word2.length <= 500 word1 and word2 consist of lowercase English letters."228Meta,80,Remove Duplicates from Sorted Array II,Med,"Array, Two Pointers",Given an integer array nums sorted in non-decreasing order; remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages; you must instead have the result be placed in the first part of the array nums. More formally; if there are k elements after removing the duplicates; then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass; then your solution will be accepted. Example 1: Input: nums = [1;1;1;2;2;3] Output: 5; nums = [1;1;2;2;3;_] Explanation: Your function should return k = 5; with the first five elements of nums being 1; 1; 2; 2 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). Example 2: Input: nums = [0;0;1;1;1;1;2;3;3] Output: 7; nums = [0;0;1;1;2;3;3;_;_] Explanation: Your function should return k = 7; with the first seven elements of nums being 0; 0; 1; 1; 2; 3 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). Constraints: 1 <= nums.length <= 3 * 104 -104 <= nums[i] <= 104 nums is sorted in non-decreasing order.229Meta,81,Search in Rotated Sorted Array II,Med,"Array, Binary Search",There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function; nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k]; nums[k+1]; ...; nums[n-1]; nums[0]; nums[1]; ...; nums[k-1]] (0-indexed). For example; [0;1;2;4;4;4;5;6;6;7] might be rotated at pivot index 5 and become [4;5;6;6;7;0;1;2;4;4]. Given the array nums after the rotation and an integer target; return true if target is in nums; or false if it is not in nums. You must decrease the overall operation steps as much as possible. Example 1: Input: nums = [2;5;6;0;0;1;2]; target = 0 Output: true Example 2: Input: nums = [2;5;6;0;0;1;2]; target = 3 Output: false Constraints: 1 <= nums.length <= 5000 -104 <= nums[i] <= 104 nums is guaranteed to be rotated at some pivot. -104 <= target <= 104 Follow up: This problem is similar to Search in Rotated Sorted Array; but nums may contain duplicates. Would this affect the runtime complexity? How and why?230Meta,94,Binary Tree Inorder Traversal,Easy,"Stack, Tree, Depth-First Search, Binary Tree",Given the root of a binary tree; return the inorder traversal of its nodes' values. Example 1: Input: root = [1;null;2;3] Output: [1;3;2] Explanation: Example 2: Input: root = [1;2;3;4;5;null;8;null;null;6;7;9] Output: [4;2;6;5;7;1;3;9;8] Explanation: Example 3: Input: root = [] Output: [] Example 4: Input: root = [1] Output: [1] Constraints: The number of nodes in the tree is in the range [0; 100]. -100 <= Node.val <= 100 Follow up: Recursive solution is trivial; could you do it iteratively?231Meta,96,Unique Binary Search Trees,Med,"Math, Dynamic Programming, Tree, Binary Search Tree, Binary Tree",Given an integer n; return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n. Example 1: Input: n = 3 Output: 5 Example 2: Input: n = 1 Output: 1 Constraints: 1 <= n <= 19232Meta,102,Binary Tree Level Order Traversal,Med,"Tree, Breadth-First Search, Binary Tree",Given the root of a binary tree; return the level order traversal of its nodes' values. (i.e.; from left to right; level by level). Example 1: Input: root = [3;9;20;null;null;15;7] Output: [[3];[9;20];[15;7]] Example 2: Input: root = [1] Output: [[1]] Example 3: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0; 2000]. -1000 <= Node.val <= 1000233Meta,105,Construct Binary Tree from Preorder and Inorder Traversal,Med,"Array, Hash Table, Divide and Conquer, Tree, Binary Tree",Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree; construct and return the binary tree. Example 1: Input: preorder = [3;9;20;15;7]; inorder = [9;3;15;20;7] Output: [3;9;20;null;null;15;7] Example 2: Input: preorder = [-1]; inorder = [-1] Output: [-1] Constraints: 1 <= preorder.length <= 3000 inorder.length == preorder.length -3000 <= preorder[i]; inorder[i] <= 3000 preorder and inorder consist of unique values. Each value of inorder also appears in preorder. preorder is guaranteed to be the preorder traversal of the tree. inorder is guaranteed to be the inorder traversal of the tree.234Meta,126,Word Ladder II,Hard,"Hash Table, String, Backtracking, Breadth-First Search","A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Every adjacent pair of words differs by a single letter. Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. sk == endWord Given two words; beginWord and endWord; and a dictionary wordList; return all the shortest transformation sequences from beginWord to endWord; or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord; s1; s2; ...; sk]. Example 1: Input: beginWord = ""hit""; endWord = ""cog""; wordList = [""hot"";""dot"";""dog"";""lot"";""log"";""cog""] Output: [[""hit"";""hot"";""dot"";""dog"";""cog""];[""hit"";""hot"";""lot"";""log"";""cog""]] Explanation: There are 2 shortest transformation sequences: ""hit"" -> ""hot"" -> ""dot"" -> ""dog"" -> ""cog"" ""hit"" -> ""hot"" -> ""lot"" -> ""log"" -> ""cog"" Example 2: Input: beginWord = ""hit""; endWord = ""cog""; wordList = [""hot"";""dot"";""dog"";""lot"";""log""] Output: [] Explanation: The endWord ""cog"" is not in wordList; therefore there is no valid transformation sequence. Constraints: 1 <= beginWord.length <= 5 endWord.length == beginWord.length 1 <= wordList.length <= 500 wordList[i].length == beginWord.length beginWord; endWord; and wordList[i] consist of lowercase English letters. beginWord != endWord All the words in wordList are unique. The sum of all shortest transformation sequences does not exceed 105."235Meta,131,Palindrome Partitioning,Med,"String, Dynamic Programming, Backtracking","Given a string s; partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. Example 1: Input: s = ""aab"" Output: [[""a"";""a"";""b""];[""aa"";""b""]] Example 2: Input: s = ""a"" Output: [[""a""]] Constraints: 1 <= s.length <= 16 s contains only lowercase English letters."236Meta,135,Candy,Hard,"Array, Greedy",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. Example 1: Input: ratings = [1;0;2] Output: 5 Explanation: You can allocate to the first; second and third child with 2; 1; 2 candies respectively. Example 2: 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. Constraints: n == ratings.length 1 <= n <= 2 * 104 0 <= ratings[i] <= 2 * 104237Meta,136,Single Number,Easy,"Array, Bit Manipulation",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. Example 1: Input: nums = [2;2;1] Output: 1 Example 2: Input: nums = [4;1;2;1;2] Output: 4 Example 3: Input: nums = [1] Output: 1 Constraints: 1 <= nums.length <= 3 * 104 -3 * 104 <= nums[i] <= 3 * 104 Each element in the array appears twice except for one element which appears only once.238Meta,168,Excel Sheet Column Title,Easy,"Math, String","Given an integer columnNumber; return its corresponding column title as it appears in an Excel sheet. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... Example 1: Input: columnNumber = 1 Output: ""A"" Example 2: Input: columnNumber = 28 Output: ""AB"" Example 3: Input: columnNumber = 701 Output: ""ZY"" Constraints: 1 <= columnNumber <= 231 - 1"239Meta,181,Employees Earning More Than Their Managers,Easy,Database,Table: Employee +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | | salary | int | | managerId | int | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table indicates the ID of an employee; their name; salary; and the ID of their manager. Write a solution to find the employees who earn more than their managers. Return the result table in any order. The result format is in the following example. Example 1: Input: Employee table: +----+-------+--------+-----------+ | id | name | salary | managerId | +----+-------+--------+-----------+ | 1 | Joe | 70000 | 3 | | 2 | Henry | 80000 | 4 | | 3 | Sam | 60000 | Null | | 4 | Max | 90000 | Null | +----+-------+--------+-----------+ Output: +----------+ | Employee | +----------+ | Joe | +----------+ Explanation: Joe is the only employee who earns more than his manager.240Meta,205,Isomorphic Strings,Easy,"Hash Table, String","Given two strings s and t; determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character; but a character may map to itself. Example 1: Input: s = ""egg""; t = ""add"" Output: true Explanation: The strings s and t can be made identical by: Mapping 'e' to 'a'. Mapping 'g' to 'd'. Example 2: Input: s = ""foo""; t = ""bar"" Output: false Explanation: The strings s and t can not be made identical as 'o' needs to be mapped to both 'a' and 'r'. Example 3: Input: s = ""paper""; t = ""title"" Output: true Constraints: 1 <= s.length <= 5 * 104 t.length == s.length s and t consist of any valid ascii character."241Meta,229,Majority Element II,Med,"Array, Hash Table, Sorting, Counting",Given an integer array of size n; find all elements that appear more than ⌊ n/3 ⌋ times. Example 1: Input: nums = [3;2;3] Output: [3] Example 2: Input: nums = [1] Output: [1] Example 3: Input: nums = [1;2] Output: [1;2] Constraints: 1 <= nums.length <= 5 * 104 -109 <= nums[i] <= 109 Follow up: Could you solve the problem in linear time and in O(1) space?242Meta,230,Kth Smallest Element in a BST,Med,"Tree, Depth-First Search, Binary Search Tree, Binary Tree",Given the root of a binary search tree; and an integer k; return the kth smallest value (1-indexed) of all the values of the nodes in the tree. Example 1: Input: root = [3;1;4;null;2]; k = 1 Output: 1 Example 2: Input: root = [5;3;6;2;4;null;null;1]; k = 3 Output: 3 Constraints: The number of nodes in the tree is n. 1 <= k <= n <= 104 0 <= Node.val <= 104 Follow up: If the BST is modified often (i.e.; we can do insert and delete operations) and you need to find the kth smallest frequently; how would you optimize?243Meta,266,Palindrome Permutation,Easy,"Hash Table, String, Bit Manipulation",244Meta,296,Best Meeting Point,Hard,"Array, Math, Sorting, Matrix",245Meta,325,Maximum Size Subarray Sum Equals k,Med,"Array, Hash Table, Prefix Sum",246Meta,350,Intersection of Two Arrays II,Easy,"Array, Hash Table, Two Pointers, Binary Search, Sorting",Given two integer arrays nums1 and nums2; return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order. Example 1: Input: nums1 = [1;2;2;1]; nums2 = [2;2] Output: [2;2] Example 2: Input: nums1 = [4;9;5]; nums2 = [9;4;9;8;4] Output: [4;9] Explanation: [9;4] is also accepted. Constraints: 1 <= nums1.length; nums2.length <= 1000 0 <= nums1[i]; nums2[i] <= 1000 Follow up: What if the given array is already sorted? How would you optimize your algorithm? What if nums1's size is small compared to nums2's size? Which algorithm is better? What if elements of nums2 are stored on disk; and the memory is limited such that you cannot load all elements into the memory at once?247Meta,371,Sum of Two Integers,Med,"Math, Bit Manipulation",Given two integers a and b; return the sum of the two integers without using the operators + and -. Example 1: Input: a = 1; b = 2 Output: 3 Example 2: Input: a = 2; b = 3 Output: 5 Constraints: -1000 <= a; b <= 1000248Meta,381,Insert Delete GetRandom O(1) - Duplicates allowed,Hard,"Array, Hash Table, Math, Design, Randomized","RandomizedCollection is a data structure that contains a collection of numbers; possibly duplicates (i.e.; a multiset). It should support inserting and removing specific elements and also reporting a random element. Implement the RandomizedCollection class: RandomizedCollection() Initializes the empty RandomizedCollection object. bool insert(int val) Inserts an item val into the multiset; even if the item is already present. Returns true if the item is not present; false otherwise. bool remove(int val) Removes an item val from the multiset if present. Returns true if the item is present; false otherwise. Note that if val has multiple occurrences in the multiset; we only remove one of them. int getRandom() Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of the same values the multiset contains. You must implement the functions of the class such that each function works on average O(1) time complexity. Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection. Example 1: Input [""RandomizedCollection""; ""insert""; ""insert""; ""insert""; ""getRandom""; ""remove""; ""getRandom""] [[]; [1]; [1]; [2]; []; [1]; []] Output [null; true; false; true; 2; true; 1] Explanation RandomizedCollection randomizedCollection = new RandomizedCollection(); randomizedCollection.insert(1); // return true since the collection does not contain 1. // Inserts 1 into the collection. randomizedCollection.insert(1); // return false since the collection contains 1. // Inserts another 1 into the collection. Collection now contains [1;1]. randomizedCollection.insert(2); // return true since the collection does not contain 2. // Inserts 2 into the collection. Collection now contains [1;1;2]. randomizedCollection.getRandom(); // getRandom should: // - return 1 with probability 2/3; or // - return 2 with probability 1/3. randomizedCollection.remove(1); // return true since the collection contains 1. // Removes 1 from the collection. Collection now contains [1;2]. randomizedCollection.getRandom(); // getRandom should return 1 or 2; both equally likely. Constraints: -231 <= val <= 231 - 1 At most 2 * 105 calls in total will be made to insert; remove; and getRandom. There will be at least one element in the data structure when getRandom is called."249Meta,383,Ransom Note,Easy,"Hash Table, String, Counting","Given two strings ransomNote and magazine; return true if ransomNote can be constructed by using the letters from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote. Example 1: Input: ransomNote = ""a""; magazine = ""b"" Output: false Example 2: Input: ransomNote = ""aa""; magazine = ""ab"" Output: false Example 3: Input: ransomNote = ""aa""; magazine = ""aab"" Output: true Constraints: 1 <= ransomNote.length; magazine.length <= 105 ransomNote and magazine consist of lowercase English letters."250Meta,386,Lexicographical Numbers,Med,"Depth-First Search, Trie",Given an integer n; return all the numbers in the range [1; n] sorted in lexicographical order. You must write an algorithm that runs in O(n) time and uses O(1) extra space. Example 1: Input: n = 13 Output: [1;10;11;12;13;2;3;4;5;6;7;8;9] Example 2: Input: n = 2 Output: [1;2] Constraints: 1 <= n <= 5 * 104251Meta,450,Delete Node in a BST,Med,"Tree, Binary Search Tree, Binary Tree",Given a root node reference of a BST and a key; delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. Basically; the deletion can be divided into two stages: Search for a node to remove. If the node is found; delete the node. Example 1: Input: root = [5;3;6;2;4;null;7]; key = 3 Output: [5;4;6;2;null;null;7] Explanation: Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5;4;6;2;null;null;7]; shown in the above BST. Please notice that another valid answer is [5;2;6;null;4;null;7] and it's also accepted. Example 2: Input: root = [5;3;6;2;4;null;7]; key = 0 Output: [5;3;6;2;4;null;7] Explanation: The tree does not contain a node with value = 0. Example 3: Input: root = []; key = 0 Output: [] Constraints: The number of nodes in the tree is in the range [0; 104]. -105 <= Node.val <= 105 Each node has a unique value. root is a valid binary search tree. -105 <= key <= 105 Follow up: Could you solve it with time complexity O(height of tree)?252Meta,490,The Maze,Med,"Array, Depth-First Search, Breadth-First Search, Matrix",253Meta,605,Can Place Flowers,Easy,"Array, Greedy",You have a long flowerbed in which some of the plots are planted; and some are not. However; flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0's and 1's; where 0 means empty and 1 means not empty; and an integer n; return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise. Example 1: Input: flowerbed = [1;0;0;0;1]; n = 1 Output: true Example 2: Input: flowerbed = [1;0;0;0;1]; n = 2 Output: false Constraints: 1 <= flowerbed.length <= 2 * 104 flowerbed[i] is 0 or 1. There are no two adjacent flowers in flowerbed. 0 <= n <= flowerbed.length254Meta,643,Maximum Average Subarray I,Easy,"Array, Sliding Window",You are given an integer array nums consisting of n elements; and an integer k. Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted. Example 1: Input: nums = [1;12;-5;-6;50;3]; k = 4 Output: 12.75000 Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 Example 2: Input: nums = [5]; k = 1 Output: 5.00000 Constraints: n == nums.length 1 <= k <= n <= 105 -104 <= nums[i] <= 104255Meta,695,Max Area of Island,Med,"Array, Depth-First Search, Breadth-First Search, Union Find, Matrix",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. Example 1: Input: grid = [[0;0;1;0;0;0;0;1;0;0;0;0;0];[0;0;0;0;0;0;0;1;1;1;0;0;0];[0;1;1;0;1;0;0;0;0;0;0;0;0];[0;1;0;0;1;1;0;0;1;0;1;0;0];[0;1;0;0;1;1;0;0;1;1;1;0;0];[0;0;0;0;0;0;0;0;0;0;1;0;0];[0;0;0;0;0;0;0;1;1;1;0;0;0];[0;0;0;0;0;0;0;1;1;0;0;0;0]] Output: 6 Explanation: The answer is not 11; because the island must be connected 4-directionally. Example 2: Input: grid = [[0;0;0;0;0;0;0;0]] Output: 0 Constraints: m == grid.length n == grid[i].length 1 <= m; n <= 50 grid[i][j] is either 0 or 1.256Meta,704,Binary Search,Easy,,257Meta,852,Peak Index in a Mountain Array,Med,"Array, Two Pointers, Binary Search, Sorting",There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the ith person. A Person x will not send a friend request to a person y (x != y) if any of the following conditions is true: age[y] <= 0.5 * age[x] + 7 age[y] > age[x] age[y] > 100 && age[x] < 100 Otherwise; x will send a friend request to y. Note that if x sends a request to y; y will not necessarily send a request to x. Also; a person will not send a friend request to themself. Return the total number of friend requests made. Example 1: Input: ages = [16;16] Output: 2 Explanation: 2 people friend request each other. Example 2: Input: ages = [16;17;18] Output: 2 Explanation: Friend requests are made 17 -> 16; 18 -> 17. Example 3: Input: ages = [20;30;100;110;120] Output: 3 Explanation: Friend requests are made 110 -> 100; 120 -> 110; 120 -> 100. Constraints: n == ages.length 1 <= n <= 2 * 104 1 <= ages[i] <= 120258Meta,862,Shortest Subarray with Sum at Least K,Hard,"Array, Hash Table, String, Sorting","You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays; indices; sources; and targets; all of length k. To complete the ith replacement operation: Check if the substring sources[i] occurs at index indices[i] in the original string s. If it does not occur; do nothing. Otherwise if it does occur; replace that substring with targets[i]. For example; if s = ""abcd""; indices[i] = 0; sources[i] = ""ab""; and targets[i] = ""eee""; then the result of this replacement will be ""eeecd"". All replacement operations must occur simultaneously; meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap. For example; a testcase with s = ""abc""; indices = [0; 1]; and sources = [""ab"";""bc""] will not be generated because the ""ab"" and ""bc"" replacements overlap. Return the resulting string after performing all replacement operations on s. A substring is a contiguous sequence of characters in a string. Example 1: Input: s = ""abcd""; indices = [0; 2]; sources = [""a""; ""cd""]; targets = [""eee""; ""ffff""] Output: ""eeebffff"" Explanation: ""a"" occurs at index 0 in s; so we replace it with ""eee"". ""cd"" occurs at index 2 in s; so we replace it with ""ffff"". Example 2: Input: s = ""abcd""; indices = [0; 2]; sources = [""ab"";""ec""]; targets = [""eee"";""ffff""] Output: ""eeecd"" Explanation: ""ab"" occurs at index 0 in s; so we replace it with ""eee"". ""ec"" does not occur at index 2 in s; so we do nothing. Constraints: 1 <= s.length <= 1000 k == indices.length == sources.length == targets.length 1 <= k <= 100 0 <= indexes[i] < s.length 1 <= sources[i].length; targets[i].length <= 50 s consists of only lowercase English letters. sources[i] and targets[i] consist of only lowercase English letters."259Meta,983,Minimum Cost For Tickets,Med,"Array, Stack, Simulation",Given two integer arrays pushed and popped each with distinct values; return true if this could have been the result of a sequence of push and pop operations on an initially empty stack; or false otherwise. Example 1: Input: pushed = [1;2;3;4;5]; popped = [4;5;3;2;1] Output: true Explanation: We might do the following sequence: push(1); push(2); push(3); push(4); pop() -> 4; push(5); pop() -> 5; pop() -> 3; pop() -> 2; pop() -> 1 Example 2: Input: pushed = [1;2;3;4;5]; popped = [4;3;5;1;2] Output: false Explanation: 1 cannot be popped before 2. Constraints: 1 <= pushed.length <= 1000 0 <= pushed[i] <= 1000 All the elements of pushed are unique. popped.length == pushed.length popped is a permutation of pushed.260Meta,1197,Minimum Knight Moves,Med,"String, Stack, Recursion","A boolean expression is an expression that evaluates to either true or false. It can be in one of the following shapes: 't' that evaluates to true. 'f' that evaluates to false. '!(subExpr)' that evaluates to the logical NOT of the inner expression subExpr. '&(subExpr1; subExpr2; ...; subExprn)' that evaluates to the logical AND of the inner expressions subExpr1; subExpr2; ...; subExprn where n >= 1. '|(subExpr1; subExpr2; ...; subExprn)' that evaluates to the logical OR of the inner expressions subExpr1; subExpr2; ...; subExprn where n >= 1. Given a string expression that represents a boolean expression; return the evaluation of that expression. It is guaranteed that the given expression is valid and follows the given rules. Example 1: Input: expression = ""&(|(f))"" Output: false Explanation: First; evaluate |(f) --> f. The expression is now ""&(f)"". Then; evaluate &(f) --> f. The expression is now ""f"". Finally; return false. Example 2: Input: expression = ""|(f;f;f;t)"" Output: true Explanation: The evaluation of (false OR false OR false OR true) is true. Example 3: Input: expression = ""!(&(f;t))"" Output: true Explanation: First; evaluate &(f;t) --> (false AND true) --> false --> f. The expression is now ""!(f)"". Then; evaluate !(f) --> NOT false --> true. We return true. Constraints: 1 <= expression.length <= 2 * 104 expression[i] is one following characters: '('; ')'; '&'; '|'; '!'; 't'; 'f'; and ';'."261Meta,1106,Parsing A Boolean Expression,Hard,"Array, Hash Table, Depth-First Search, Breadth-First Search",There is a 1 million by 1 million grid on an XY-plane; and the coordinates of each grid square are (x; y). We start at the source = [sx; sy] square and want to reach the target = [tx; ty] square. There is also an array of blocked squares; where each blocked[i] = [xi; yi] represents a blocked square with coordinates (xi; yi). Each move; we can walk one square north; east; south; or west if the square is not in the array of blocked squares. We are also not allowed to walk outside of the grid. Return true if and only if it is possible to reach the target square from the source square through a sequence of valid moves. Example 1: Input: blocked = [[0;1];[1;0]]; source = [0;0]; target = [0;2] Output: false Explanation: The target square is inaccessible starting from the source square because we cannot move. We cannot move north or east because those squares are blocked. We cannot move south or west because we cannot go outside of the grid. Example 2: Input: blocked = []; source = [0;0]; target = [999999;999999] Output: true Explanation: Because there are no blocked cells; it is possible to reach the target square. Constraints: 0 <= blocked.length <= 200 blocked[i].length == 2 0 <= xi; yi < 106 source.length == target.length == 2 0 <= sx; sy; tx; ty < 106 source != target It is guaranteed that source and target are not blocked.262Meta,1110,Delete Nodes And Return Forest,Med,,263Meta,1331,Rank Transform of an Array,Easy,"Array, Backtracking, Matrix",In a gold mine grid of size m x n; each cell in this mine has an integer representing the amount of gold in that cell; 0 if it is empty. Return the maximum amount of gold you can collect under the conditions: Every time you are located in a cell you will collect all the gold in that cell. From your position; you can walk one step to the left; right; up; or down. You can't visit the same cell more than once. Never visit a cell with 0 gold. You can start and stop collecting gold from any position in the grid that has some gold. Example 1: Input: grid = [[0;6;0];[5;8;7];[0;9;0]] Output: 24 Explanation: [[0;6;0]; [5;8;7]; [0;9;0]] Path to get the maximum gold; 9 -> 8 -> 7. Example 2: Input: grid = [[1;0;7];[2;0;6];[3;4;5];[0;3;0];[9;0;20]] Output: 28 Explanation: [[1;0;7]; [2;0;6]; [3;4;5]; [0;3;0]; [9;0;20]] Path to get the maximum gold; 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. Constraints: m == grid.length n == grid[i].length 1 <= m; n <= 15 0 <= grid[i][j] <= 100 There are at most 25 cells containing gold.264Meta,1209,Remove All Adjacent Duplicates in String II,Med,Concurrency,265Meta,1233,Remove Sub-Folders from the Filesystem,Med,"Array, Divide and Conquer, Interactive",266Meta,1275,Find Winner on a Tic Tac Toe Game,Easy,"Tree, Depth-First Search, Breadth-First Search, Union Find, Graph, Binary Tree",You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i]; return true if and only if all the given nodes form exactly one valid binary tree. If node i has no left child then leftChild[i] will equal -1; similarly for the right child. Note that the nodes have no values and that we only use the node numbers in this problem. Example 1: Input: n = 4; leftChild = [1;-1;3;-1]; rightChild = [2;-1;-1;-1] Output: true Example 2: Input: n = 4; leftChild = [1;-1;3;-1]; rightChild = [2;3;-1;-1] Output: false Example 3: Input: n = 2; leftChild = [1;0]; rightChild = [-1;-1] Output: false Constraints: n == leftChild.length == rightChild.length 1 <= n <= 104 -1 <= leftChild[i]; rightChild[i] <= n - 1267Meta,1344,Angle Between Hands of a Clock,Med,"Array, Hash Table",Given an array nums of positive integers; return the longest possible length of an array prefix of nums; such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements; it's still considered that every appeared number has the same number of ocurrences (0). Example 1: Input: nums = [2;2;1;1;5;3;3;5] Output: 7 Explanation: For the subarray [2;2;1;1;5;3;3] of length 7; if we remove nums[4] = 5; we will get [2;2;1;1;3;3]; so that each number will appear exactly twice. Example 2: Input: nums = [1;1;1;2;2;2;3;3;3;4;4;4;5] Output: 13 Constraints: 2 <= nums.length <= 105 1 <= nums[i] <= 105268Meta,1367,Linked List in Binary Tree,Med,"Array, Dynamic Programming, Sorting",Given n cuboids where the dimensions of the ith cuboid is cuboids[i] = [widthi; lengthi; heighti] (0-indexed). Choose a subset of cuboids and place them on each other. You can place cuboid i on cuboid j if widthi <= widthj and lengthi <= lengthj and heighti <= heightj. You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid. Return the maximum height of the stacked cuboids. Example 1: Input: cuboids = [[50;45;20];[95;37;53];[45;23;12]] Output: 190 Explanation: Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95. Cuboid 0 is placed next with the 45x20 side facing down with height 50. Cuboid 2 is placed next with the 23x12 side facing down with height 45. The total height is 95 + 50 + 45 = 190. Example 2: Input: cuboids = [[38;25;45];[76;35;3]] Output: 76 Explanation: You can't place any of the cuboids on the other. We choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76. Example 3: Input: cuboids = [[7;11;17];[7;17;11];[11;7;17];[11;17;7];[17;7;11];[17;11;7]] Output: 102 Explanation: After rearranging the cuboids; you can see that all cuboids have the same dimension. You can place the 11x7 side down on all cuboids so their heights are 17. The maximum height of stacked cuboids is 6 * 17 = 102. Constraints: n == cuboids.length 1 <= n <= 100 1 <= widthi; lengthi; heighti <= 100269Meta,1497,Check If Array Pairs Are Divisible by k,Med,"Array, Stack, Design","Design a stack that supports increment operations on its elements. Implement the CustomStack class: CustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack. void push(int x) Adds x to the top of the stack if the stack has not reached the maxSize. int pop() Pops and returns the top of the stack or -1 if the stack is empty. void inc(int k; int val) Increments the bottom k elements of the stack by val. If there are less than k elements in the stack; increment all the elements in the stack. Example 1: Input [""CustomStack"";""push"";""push"";""pop"";""push"";""push"";""push"";""increment"";""increment"";""pop"";""pop"";""pop"";""pop""] [[3];[1];[2];[];[2];[3];[4];[5;100];[2;100];[];[];[];[]] Output [null;null;null;2;null;null;null;null;null;103;202;201;-1] Explanation CustomStack stk = new CustomStack(3); // Stack is Empty [] stk.push(1); // stack becomes [1] stk.push(2); // stack becomes [1; 2] stk.pop(); // return 2 --> Return top of the stack 2; stack becomes [1] stk.push(2); // stack becomes [1; 2] stk.push(3); // stack becomes [1; 2; 3] stk.push(4); // stack still [1; 2; 3]; Do not add another elements as size is 4 stk.increment(5; 100); // stack becomes [101; 102; 103] stk.increment(2; 100); // stack becomes [201; 202; 103] stk.pop(); // return 103 --> Return top of the stack 103; stack becomes [201; 202] stk.pop(); // return 202 --> Return top of the stack 202; stack becomes [201] stk.pop(); // return 201 --> Return top of the stack 201; stack becomes [] stk.pop(); // return -1 --> Stack is empty return -1. Constraints: 1 <= maxSize; x; k <= 1000 0 <= val <= 100 At most 1000 calls will be made to each method of increment; push and pop each separately."270Meta,1498,Number of Subsequences That Satisfy the Given Sum Condition,Med,"Tree, Depth-First Search, Breadth-First Search, Binary Tree",Given two binary trees original and cloned and given a reference to a node target in the original tree. The cloned tree is a copy of the original tree. Return a reference to the same node in the cloned tree. Note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree. Example 1: Input: tree = [7;4;3;null;null;6;19]; target = 3 Output: 3 Explanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree. Example 2: Input: tree = [7]; target = 7 Output: 7 Example 3: Input: tree = [8;null;6;null;5;null;4;null;3;null;2;null;1]; target = 4 Output: 4 Constraints: The number of nodes in the tree is in the range [1; 104]. The values of the nodes of the tree are unique. target node is a node from the original tree and is not null. Follow up: Could you solve the problem if repeated values on the tree are allowed?271Meta,1590,Make Sum Divisible by P,Med,,272Meta,1652,Defuse the Bomb,Easy,"String, Greedy","You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target. In one operation; you can pick an index i where 0 <= i < n and flip all bits in the inclusive range [i; n - 1]. Flip means changing '0' to '1' and '1' to '0'. Return the minimum number of operations needed to make s equal to target. Example 1: Input: target = ""10111"" Output: 3 Explanation: Initially; s = ""00000"". Choose index i = 2: ""00000"" -> ""00111"" Choose index i = 0: ""00111"" -> ""11000"" Choose index i = 1: ""11000"" -> ""10111"" We need at least 3 flip operations to form target. Example 2: Input: target = ""101"" Output: 3 Explanation: Initially; s = ""000"". Choose index i = 0: ""000"" -> ""111"" Choose index i = 1: ""111"" -> ""100"" Choose index i = 2: ""100"" -> ""101"" We need at least 3 flip operations to form target. Example 3: Input: target = ""00000"" Output: 0 Explanation: We do not need any operations since the initial s already equals target. Constraints: n == target.length 1 <= n <= 105 target[i] is either '0' or '1'."273Meta,1778,Shortest Path in a Hidden Grid,Med,"Dynamic Programming, Bit Manipulation, Memoization, Bitmask",You are given four integers; m; n; introvertsCount; and extrovertsCount. You have an m x n grid; and there are two types of people: introverts and extroverts. There are introvertsCount introverts and extrovertsCount extroverts. You should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you do not have to have all the people living in the grid. The happiness of each person is calculated as follows: Introverts start with 120 happiness and lose 30 happiness for each neighbor (introvert or extrovert). Extroverts start with 40 happiness and gain 20 happiness for each neighbor (introvert or extrovert). Neighbors live in the directly adjacent cells north; east; south; and west of a person's cell. The grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness. Example 1: Input: m = 2; n = 3; introvertsCount = 1; extrovertsCount = 2 Output: 240 Explanation: Assume the grid is 1-indexed with coordinates (row; column). We can put the introvert in cell (1;1) and put the extroverts in cells (1;3) and (2;3). - Introvert at (1;1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120 - Extrovert at (1;3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60 - Extrovert at (2;3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60 The grid happiness is 120 + 60 + 60 = 240. The above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells. Example 2: Input: m = 3; n = 1; introvertsCount = 2; extrovertsCount = 1 Output: 260 Explanation: Place the two introverts in (1;1) and (3;1) and the extrovert at (2;1). - Introvert at (1;1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90 - Extrovert at (2;1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80 - Introvert at (3;1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90 The grid happiness is 90 + 80 + 90 = 260. Example 3: Input: m = 2; n = 2; introvertsCount = 4; extrovertsCount = 0 Output: 240 Constraints: 1 <= m; n <= 5 0 <= introvertsCount; extrovertsCount <= min(m * n; 6)274Meta,2090,K Radius Subarray Averages,Med,"Dynamic Programming, Graph, Topological Sort, Shortest Path",You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer n and a 2D integer array roads where roads[i] = [ui; vi; timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time. Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large; return it modulo 109 + 7. Example 1: Input: n = 7; roads = [[0;6;7];[0;1;2];[1;2;3];[1;3;3];[6;3;3];[3;5;1];[6;5;1];[2;5;1];[0;4;5];[4;6;2]] Output: 4 Explanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes. The four ways to get there in 7 minutes are: - 0 ➝ 6 - 0 ➝ 4 ➝ 6 - 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6 - 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6 Example 2: Input: n = 2; roads = [[1;0;10]] Output: 1 Explanation: There is only one way to go from intersection 0 to intersection 1; and it takes 10 minutes. Constraints: 1 <= n <= 200 n - 1 <= roads.length <= n * (n - 1) / 2 roads[i].length == 3 0 <= ui; vi <= n - 1 1 <= timei <= 109 ui != vi There is at most one road connecting any two intersections. You can reach any intersection from any other intersection.275Meta,2235,Add Two Integers,Easy,String,"You are given a string title consisting of one or more words separated by a single space; where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that: If the length of the word is 1 or 2 letters; change all letters to lowercase. Otherwise; change the first letter to uppercase and the remaining letters to lowercase. Return the capitalized title. Example 1: Input: title = ""capiTalIze tHe titLe"" Output: ""Capitalize The Title"" Explanation: Since all the words have a length of at least 3; the first letter of each word is uppercase; and the remaining letters are lowercase. Example 2: Input: title = ""First leTTeR of EACH Word"" Output: ""First Letter of Each Word"" Explanation: The word ""of"" has length 2; so it is all lowercase. The remaining words have a length of at least 3; so the first letter of each remaining word is uppercase; and the remaining letters are lowercase. Example 3: Input: title = ""i lOve leetcode"" Output: ""i Love Leetcode"" Explanation: The word ""i"" has length 1; so it is lowercase. The remaining words have a length of at least 3; so the first letter of each remaining word is uppercase; and the remaining letters are lowercase. Constraints: 1 <= title.length <= 100 title consists of words separated by a single space without any leading or trailing spaces. Each word consists of uppercase and lowercase English letters and is non-empty."276Meta,2236,Root Equals Sum of Children,Easy,"Linked List, Two Pointers, Stack",In a linked list of size n; where n is even; the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node; if 0 <= i <= (n / 2) - 1. For example; if n = 4; then node 0 is the twin of node 3; and node 1 is the twin of node 2. These are the only nodes with twins for n = 4. The twin sum is defined as the sum of a node and its twin. Given the head of a linked list with even length; return the maximum twin sum of the linked list. Example 1: Input: head = [5;4;2;1] Output: 6 Explanation: Nodes 0 and 1 are the twins of nodes 3 and 2; respectively. All have twin sum = 6. There are no other nodes with twins in the linked list. Thus; the maximum twin sum of the linked list is 6. Example 2: Input: head = [4;2;2;3] Output: 7 Explanation: The nodes with twins present in this linked list are: - Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7. - Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4. Thus; the maximum twin sum of the linked list is max(7; 4) = 7. Example 3: Input: head = [1;100000] Output: 100001 Explanation: There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001. Constraints: The number of nodes in the list is an even integer in the range [2; 105]. 1 <= Node.val <= 105277Meta,2406,Divide Intervals Into Minimum Number of Groups,Med,"Hash Table, String","You are given the strings key and message; which represent a cipher key and a secret message; respectively. The steps to decode message are as follows: Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table. Align the substitution table with the regular English alphabet. Each letter in message is then substituted using the table. Spaces ' ' are transformed to themselves. For example; given key = ""happy boy"" (actual key would have at least one instance of each letter in the alphabet); we have the partial substitution table of ('h' -> 'a'; 'a' -> 'b'; 'p' -> 'c'; 'y' -> 'd'; 'b' -> 'e'; 'o' -> 'f'). Return the decoded message. Example 1: Input: key = ""the quick brown fox jumps over the lazy dog""; message = ""vkbs bs t suepuv"" Output: ""this is a secret"" Explanation: The diagram above shows the substitution table. It is obtained by taking the first appearance of each letter in ""the quick brown fox jumps over the lazy dog"". Example 2: Input: key = ""eljuxhpwnyrdgtqkviszcfmabo""; message = ""zwx hnfx lqantp mnoeius ycgk vcnjrdb"" Output: ""the five boxing wizards jump quickly"" Explanation: The diagram above shows the substitution table. It is obtained by taking the first appearance of each letter in ""eljuxhpwnyrdgtqkviszcfmabo"". Constraints: 26 <= key.length <= 2000 key consists of lowercase English letters and ' '. key contains every letter in the English alphabet ('a' to 'z') at least once. 1 <= message.length <= 2000 message consists of lowercase English letters and ' '."278Meta,3011,Find if Array Can Be Sorted,Med,,279Meta,3097,Shortest Subarray With OR at Least K II,Med,Database,280Meta,3133,Minimum Array End,Med,,281Meta,6,Zigzag Conversion,Med,String,"The string ""PAYPALISHIRING"" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: ""PAHNAPLSIIGYIR"" Write the code that will take a string and make this conversion given a number of rows: string convert(string s; int numRows); Example 1: Input: s = ""PAYPALISHIRING""; numRows = 3 Output: ""PAHNAPLSIIGYIR"" Example 2: Input: s = ""PAYPALISHIRING""; numRows = 4 Output: ""PINALSIGYAHRPI"" Explanation: P I N A L S I G Y A H R P I Example 3: Input: s = ""A""; numRows = 1 Output: ""A"" Constraints: 1 <= s.length <= 1000 s consists of English letters (lower-case and upper-case); ';' and '.'. 1 <= numRows <= 1000"282Meta,18,4Sum,Med,"Array, Two Pointers, Sorting",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. Example 1: Input: nums = [1;0;-1;0;-2;2]; target = 0 Output: [[-2;-1;1;2];[-2;0;0;2];[-1;0;0;1]] Example 2: Input: nums = [2;2;2;2;2]; target = 8 Output: [[2;2;2;2]] Constraints: 1 <= nums.length <= 200 -109 <= nums[i] <= 109 -109 <= target <= 109283Meta,24,Swap Nodes in Pairs,Med,"Linked List, Recursion",Given a linked list; swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e.; only nodes themselves may be changed.) Example 1: Input: head = [1;2;3;4] Output: [2;1;4;3] Explanation: Example 2: Input: head = [] Output: [] Example 3: Input: head = [1] Output: [1] Example 4: Input: head = [1;2;3] Output: [2;1;3] Constraints: The number of nodes in the list is in the range [0; 100]. 0 <= Node.val <= 100284Meta,32,Longest Valid Parentheses,Hard,"String, Dynamic Programming, Stack","Given a string containing just the characters '(' and ')'; return the length of the longest valid (well-formed) parentheses substring. Example 1: Input: s = ""(()"" Output: 2 Explanation: The longest valid parentheses substring is ""()"". Example 2: Input: s = "")()())"" Output: 4 Explanation: The longest valid parentheses substring is ""()()"". Example 3: Input: s = """" Output: 0 Constraints: 0 <= s.length <= 3 * 104 s[i] is '('; or ')'."285Meta,45,Jump Game II,Med,"Array, Dynamic Programming, Greedy",You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0]. Each element nums[i] represents the maximum length of a forward jump from index i. In other words; if you are at nums[i]; you can jump to any nums[i + j] where: 0 <= j <= nums[i] and i + j < n Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1]. Example 1: 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. Example 2: Input: nums = [2;3;0;1;4] Output: 2 Constraints: 1 <= nums.length <= 104 0 <= nums[i] <= 1000 It's guaranteed that you can reach nums[n - 1].286Meta,46,Permutations,Med,"Array, Backtracking",Given an array nums of distinct integers; return all the possible permutations. You can return the answer in any order. Example 1: Input: nums = [1;2;3] Output: [[1;2;3];[1;3;2];[2;1;3];[2;3;1];[3;1;2];[3;2;1]] Example 2: Input: nums = [0;1] Output: [[0;1];[1;0]] Example 3: Input: nums = [1] Output: [[1]] Constraints: 1 <= nums.length <= 6 -10 <= nums[i] <= 10 All the integers of nums are unique.287Meta,67,Add Binary,Easy,"Math, String, Bit Manipulation, Simulation","Given two binary strings a and b; return their sum as a binary string. Example 1: Input: a = ""11""; b = ""1"" Output: ""100"" Example 2: Input: a = ""1010""; b = ""1011"" Output: ""10101"" Constraints: 1 <= a.length; b.length <= 104 a and b consist only of '0' or '1' characters. Each string does not contain leading zeros except for the zero itself."288Meta,69,Sqrt(x),Easy,"Math, Binary Search",Given a non-negative integer x; return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well. You must not use any built-in exponent function or operator. For example; do not use pow(x; 0.5) in c++ or x ** 0.5 in python. Example 1: Input: x = 4 Output: 2 Explanation: The square root of 4 is 2; so we return 2. Example 2: Input: x = 8 Output: 2 Explanation: The square root of 8 is 2.82842...; and since we round it down to the nearest integer; 2 is returned. Constraints: 0 <= x <= 231 - 1289Meta,73,Set Matrix Zeroes,Med,"Array, Hash Table, Matrix",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. Example 1: Input: matrix = [[1;1;1];[1;0;1];[1;1;1]] Output: [[1;0;1];[0;0;0];[1;0;1]] Example 2: Input: matrix = [[0;1;2;0];[3;4;5;2];[1;3;1;5]] Output: [[0;0;0;0];[0;4;5;0];[0;3;1;0]] Constraints: m == matrix.length n == matrix[0].length 1 <= m; n <= 200 -231 <= matrix[i][j] <= 231 - 1 Follow up: A straightforward solution using O(mn) space is probably a bad idea. A simple improvement uses O(m + n) space; but still not the best solution. Could you devise a constant space solution?290Meta,74,Search a 2D Matrix,Med,"Array, Binary Search, Matrix",You are given an m x n integer matrix matrix with the following two properties: Each row is sorted in non-decreasing order. The first integer of each row is greater than the last integer of the previous row. Given an integer target; return true if target is in matrix or false otherwise. You must write a solution in O(log(m * n)) time complexity. Example 1: Input: matrix = [[1;3;5;7];[10;11;16;20];[23;30;34;60]]; target = 3 Output: true Example 2: Input: matrix = [[1;3;5;7];[10;11;16;20];[23;30;34;60]]; target = 13 Output: false Constraints: m == matrix.length n == matrix[i].length 1 <= m; n <= 100 -104 <= matrix[i][j]; target <= 104291Meta,79,Word Search,Med,"Array, String, Backtracking, Matrix","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. Example 1: Input: board = [[""A"";""B"";""C"";""E""];[""S"";""F"";""C"";""S""];[""A"";""D"";""E"";""E""]]; word = ""ABCCED"" Output: true Example 2: Input: board = [[""A"";""B"";""C"";""E""];[""S"";""F"";""C"";""S""];[""A"";""D"";""E"";""E""]]; word = ""SEE"" Output: true Example 3: Input: board = [[""A"";""B"";""C"";""E""];[""S"";""F"";""C"";""S""];[""A"";""D"";""E"";""E""]]; word = ""ABCB"" Output: false Constraints: m == board.length n = board[i].length 1 <= m; n <= 6 1 <= word.length <= 15 board and word consists of only lowercase and uppercase English letters. Follow up: Could you use search pruning to make your solution faster with a larger board?"292Meta,82,Remove Duplicates from Sorted List II,Med,"Linked List, Two Pointers",Given the head of a sorted linked list; delete all nodes that have duplicate numbers; leaving only distinct numbers from the original list. Return the linked list sorted as well. Example 1: Input: head = [1;2;3;3;4;4;5] Output: [1;2;5] Example 2: Input: head = [1;1;1;2;3] Output: [2;3] Constraints: The number of nodes in the list is in the range [0; 300]. -100 <= Node.val <= 100 The list is guaranteed to be sorted in ascending order.293Meta,93,Restore IP Addresses,Med,"String, Backtracking","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 ""192.168@1.1"" 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. Example 1: Input: s = ""25525511135"" Output: [""255.255.11.135"";""255.255.111.35""] Example 2: Input: s = ""0000"" Output: [""0.0.0.0""] Example 3: Input: s = ""101023"" Output: [""1.0.10.23"";""1.0.102.3"";""10.1.0.23"";""10.10.2.3"";""101.0.2.3""] Constraints: 1 <= s.length <= 20 s consists of digits only."294Meta,112,Path Sum,Easy,"Tree, Depth-First Search, Breadth-First Search, Binary Tree",Given the root of a binary tree and an integer targetSum; return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. A leaf is a node with no children. Example 1: Input: root = [5;4;8;11;null;13;4;7;2;null;null;null;1]; targetSum = 22 Output: true Explanation: The root-to-leaf path with the target sum is shown. Example 2: Input: root = [1;2;3]; targetSum = 5 Output: false Explanation: There are two root-to-leaf paths in the tree: (1 --> 2): The sum is 3. (1 --> 3): The sum is 4. There is no root-to-leaf path with sum = 5. Example 3: Input: root = []; targetSum = 0 Output: false Explanation: Since the tree is empty; there are no root-to-leaf paths. Constraints: The number of nodes in the tree is in the range [0; 5000]. -1000 <= Node.val <= 1000 -1000 <= targetSum <= 1000295Meta,117,Populating Next Right Pointers in Each Node II,Med,"Linked List, Tree, Depth-First Search, Breadth-First Search, Binary Tree",Given a binary tree struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node; the next pointer should be set to NULL. Initially; all next pointers are set to NULL. Example 1: Input: root = [1;2;3;4;5;null;7] Output: [1;#;2;3;#;4;5;7;#] Explanation: Given the above binary tree (Figure A); your function should populate each next pointer to point to its next right node; just like in Figure B. The serialized output is in level order as connected by the next pointers; with '#' signifying the end of each level. Example 2: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0; 6000]. -100 <= Node.val <= 100 Follow-up: You may only use constant extra space. The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.296Meta,122,Best Time to Buy and Sell Stock II,Med,"Array, Dynamic Programming, Greedy",You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day; you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However; you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve. Example 1: Input: prices = [7;1;5;3;6;4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5); profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6); profit = 6-3 = 3. Total profit is 4 + 3 = 7. Example 2: Input: prices = [1;2;3;4;5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5); profit = 5-1 = 4. Total profit is 4. Example 3: Input: prices = [7;6;4;3;1] Output: 0 Explanation: There is no way to make a positive profit; so we never buy the stock to achieve the maximum profit of 0. Constraints: 1 <= prices.length <= 3 * 104 0 <= prices[i] <= 104297Meta,134,Gas Station,Med,"Array, Greedy",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. Example 1: 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. Example 2: Input: gas = [2;3;4]; cost = [3;4;3] Output: -1 Explanation: You can't start at station 0 or 1; as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2; as it requires 4 unit of gas but you only have 3. Therefore; you can't travel around the circuit once no matter where you start. Constraints: n == gas.length == cost.length 1 <= n <= 105 0 <= gas[i]; cost[i] <= 104298Meta,137,Single Number II,Med,"Array, Bit Manipulation",Given an integer array nums where every element appears three times except for one; which appears exactly once. Find the single element and return it. You must implement a solution with a linear runtime complexity and use only constant extra space. Example 1: Input: nums = [2;2;3;2] Output: 3 Example 2: Input: nums = [0;1;0;1;0;1;99] Output: 99 Constraints: 1 <= nums.length <= 3 * 104 -231 <= nums[i] <= 231 - 1 Each element in nums appears exactly three times except for one element which appears once.299Meta,149,Max Points on a Line,Hard,"Array, Hash Table, Math, Geometry",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. Example 1: Input: points = [[1;1];[2;2];[3;3]] Output: 3 Example 2: Input: points = [[1;1];[3;2];[5;3];[4;1];[2;3];[1;4]] Output: 4 Constraints: 1 <= points.length <= 300 points[i].length == 2 -104 <= xi; yi <= 104 All the points are unique.300Meta,150,Evaluate Reverse Polish Notation,Med,"Array, Math, Stack","You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation. Evaluate the expression. Return an integer that represents the value of the expression. Note that: The valid operators are '+'; '-'; '*'; and '/'. Each operand may be an integer or another expression. The division between two integers always truncates toward zero. There will not be any division by zero. The input represents a valid arithmetic expression in a reverse polish notation. The answer and all the intermediate calculations can be represented in a 32-bit integer. Example 1: Input: tokens = [""2"";""1"";""+"";""3"";""*""] Output: 9 Explanation: ((2 + 1) * 3) = 9 Example 2: Input: tokens = [""4"";""13"";""5"";""/"";""+""] Output: 6 Explanation: (4 + (13 / 5)) = 6 Example 3: Input: tokens = [""10"";""6"";""9"";""3"";""+"";""-11"";""*"";""/"";""*"";""17"";""+"";""5"";""+""] Output: 22 Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) + 17) + 5 = ((10 * (6 / -132)) + 17) + 5 = ((10 * 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22 Constraints: 1 <= tokens.length <= 104 tokens[i] is either an operator: ""+""; ""-""; ""*""; or ""/""; or an integer in the range [-200; 200]."301Meta,152,Maximum Product Subarray,Med,"Array, Dynamic Programming",Given an integer array nums; find a subarray that has the largest product; and return the product. The test cases are generated so that the answer will fit in a 32-bit integer. Example 1: Input: nums = [2;3;-2;4] Output: 6 Explanation: [2;3] has the largest product 6. Example 2: Input: nums = [-2;0;-1] Output: 0 Explanation: The result cannot be 2; because [-2;-1] is not a subarray. Constraints: 1 <= nums.length <= 2 * 104 -10 <= nums[i] <= 10 The product of any subarray of nums is guaranteed to fit in a 32-bit integer.302Meta,188,Best Time to Buy and Sell Stock IV,Hard,"Array, Dynamic Programming",You are given an integer array prices where prices[i] is the price of a given stock on the ith day; and an integer k. Find the maximum profit you can achieve. You may complete at most k transactions: i.e. you may buy at most k times and sell at most k times. Note: You may not engage in multiple transactions simultaneously (i.e.; you must sell the stock before you buy again). Example 1: Input: k = 2; prices = [2;4;1] Output: 2 Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4); profit = 4-2 = 2. Example 2: Input: k = 2; prices = [3;2;6;5;0;3] Output: 7 Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6); profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3); profit = 3-0 = 3. Constraints: 1 <= k <= 100 1 <= prices.length <= 1000 0 <= prices[i] <= 1000303Meta,195,Tenth Line,Easy,Shell,Given a text file file.txt; print just the 10th line of the file. Example: Assume that file.txt has the following content: Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10 Your script should output the tenth line; which is: Line 10 Note: 1. If the file contains less than 10 lines; what should you output? 2. There's at least three different solutions. Try to explore all possibilities.304Meta,202,Happy Number,Easy,"Hash Table, Math, Two Pointers",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. Example 1: Input: n = 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 Example 2: Input: n = 2 Output: false Constraints: 1 <= n <= 231 - 1305Meta,210,Course Schedule II,Med,"Depth-First Search, Breadth-First Search, Graph, Topological Sort",There are a total of numCourses courses you have to take; labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai; bi] indicates that you must take course bi first if you want to take course ai. For example; the pair [0; 1]; indicates that to take course 0 you have to first take course 1. Return the ordering of courses you should take to finish all courses. If there are many valid answers; return any of them. If it is impossible to finish all courses; return an empty array. Example 1: Input: numCourses = 2; prerequisites = [[1;0]] Output: [0;1] Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0;1]. Example 2: Input: numCourses = 4; prerequisites = [[1;0];[2;0];[3;1];[3;2]] Output: [0;2;1;3] Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0;1;2;3]. Another correct ordering is [0;2;1;3]. Example 3: Input: numCourses = 1; prerequisites = [] Output: [0] Constraints: 1 <= numCourses <= 2000 0 <= prerequisites.length <= numCourses * (numCourses - 1) prerequisites[i].length == 2 0 <= ai; bi < numCourses ai != bi All the pairs [ai; bi] are distinct.306Meta,212,Word Search II,Hard,"Array, String, Backtracking, Trie, Matrix","Given an m x n board of characters and a list of strings words; return all words on the board. Each word must 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 in a word. Example 1: Input: board = [[""o"";""a"";""a"";""n""];[""e"";""t"";""a"";""e""];[""i"";""h"";""k"";""r""];[""i"";""f"";""l"";""v""]]; words = [""oath"";""pea"";""eat"";""rain""] Output: [""eat"";""oath""] Example 2: Input: board = [[""a"";""b""];[""c"";""d""]]; words = [""abcb""] Output: [] Constraints: m == board.length n == board[i].length 1 <= m; n <= 12 board[i][j] is a lowercase English letter. 1 <= words.length <= 3 * 104 1 <= words[i].length <= 10 words[i] consists of lowercase English letters. All the strings of words are unique."307Meta,228,Summary Ranges,Easy,Array,"You are given a sorted unique integer array nums. A range [a;b] is the set of all integers from a to b (inclusive). Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is; each element of nums is covered by exactly one of the ranges; and there is no integer x such that x is in one of the ranges but not in nums. Each range [a;b] in the list should be output as: ""a->b"" if a != b ""a"" if a == b Example 1: Input: nums = [0;1;2;4;5;7] Output: [""0->2"";""4->5"";""7""] Explanation: The ranges are: [0;2] --> ""0->2"" [4;5] --> ""4->5"" [7;7] --> ""7"" Example 2: Input: nums = [0;2;3;4;6;8;9] Output: [""0"";""2->4"";""6"";""8->9""] Explanation: The ranges are: [0;0] --> ""0"" [2;4] --> ""2->4"" [6;6] --> ""6"" [8;9] --> ""8->9"" Constraints: 0 <= nums.length <= 20 -231 <= nums[i] <= 231 - 1 All the values of nums are unique. nums is sorted in ascending order."308Meta,234,Palindrome Linked List,Easy,"Linked List, Two Pointers, Stack, Recursion",Given the head of a singly linked list; return true if it is a palindrome or false otherwise. Example 1: Input: head = [1;2;2;1] Output: true Example 2: Input: head = [1;2] Output: false Constraints: The number of nodes in the list is in the range [1; 105]. 0 <= Node.val <= 9 Follow up: Could you do it in O(n) time and O(1) space?309Meta,235,Lowest Common Ancestor of a Binary Search Tree,Med,"Tree, Depth-First Search, Binary Search Tree, Binary Tree",Given a binary search tree (BST); find the lowest common ancestor (LCA) node of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Example 1: Input: root = [6;2;8;0;4;7;9;null;null;3;5]; p = 2; q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6. Example 2: Input: root = [6;2;8;0;4;7;9;null;null;3;5]; p = 2; q = 4 Output: 2 Explanation: The LCA of nodes 2 and 4 is 2; since a node can be a descendant of itself according to the LCA definition. Example 3: Input: root = [2;1]; p = 2; q = 1 Output: 2 Constraints: The number of nodes in the tree is in the range [2; 105]. -109 <= Node.val <= 109 All Node.val are unique. p != q p and q will exist in the BST.310Meta,240,Search a 2D Matrix II,Med,"Array, Binary Search, Divide and Conquer, Matrix",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. Example 1: 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 Example 2: 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 = 20 Output: false Constraints: m == matrix.length n == matrix[i].length 1 <= n; m <= 300 -109 <= matrix[i][j] <= 109 All the integers in each row are sorted in ascending order. All the integers in each column are sorted in ascending order. -109 <= target <= 109311Meta,242,Valid Anagram,Easy,"Hash Table, String, Sorting","Given two strings s and t; return true if t is an anagram of s; and false otherwise. Example 1: Input: s = ""anagram""; t = ""nagaram"" Output: true Example 2: Input: s = ""rat""; t = ""car"" Output: false Constraints: 1 <= s.length; t.length <= 5 * 104 s and t consist of lowercase English letters. Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?"312Meta,252,Meeting Rooms,Easy,"Array, Sorting",313Meta,286,Walls and Gates,Med,"Array, Breadth-First Search, Matrix",314Meta,287,Find the Duplicate Number,Med,"Array, Two Pointers, Binary Search, Bit Manipulation",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 using only constant extra space. Example 1: Input: nums = [1;3;4;2;2] Output: 2 Example 2: Input: nums = [3;1;3;4;2] Output: 3 Example 3: Input: nums = [3;3;3;3;3] Output: 3 Constraints: 1 <= n <= 105 nums.length == n + 1 1 <= nums[i] <= n All the integers in nums appear only once except for precisely one integer which appears two or more times. Follow up: How can we prove that at least one duplicate number must exist in nums? Can you solve the problem in linear runtime complexity?315Meta,297,Serialize and Deserialize Binary Tree,Hard,"String, Tree, Depth-First Search, Breadth-First Search, Design, Binary Tree",Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer; or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format; so please be creative and come up with different approaches yourself. Example 1: Input: root = [1;2;3;null;null;4;5] Output: [1;2;3;null;null;4;5] Example 2: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0; 104]. -1000 <= Node.val <= 1000316Meta,303,Range Sum Query - Immutable,Easy,"Array, Design, Prefix Sum","Given an integer array nums; handle multiple queries of the following type: Calculate the sum of the elements of nums between indices left and right inclusive where left <= right. Implement the NumArray class: NumArray(int[] nums) Initializes the object with the integer array nums. int sumRange(int left; int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]). Example 1: Input [""NumArray""; ""sumRange""; ""sumRange""; ""sumRange""] [[[-2; 0; 3; -5; 2; -1]]; [0; 2]; [2; 5]; [0; 5]] Output [null; 1; -1; -3] Explanation NumArray numArray = new NumArray([-2; 0; 3; -5; 2; -1]); numArray.sumRange(0; 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2; 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0; 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 Constraints: 1 <= nums.length <= 104 -105 <= nums[i] <= 105 0 <= left <= right < nums.length At most 104 calls will be made to sumRange."317Meta,316,Remove Duplicate Letters,Med,"String, Stack, Greedy, Monotonic Stack","Given a string s; remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. Example 1: Input: s = ""bcabc"" Output: ""abc"" Example 2: Input: s = ""cbacdcbc"" Output: ""acdb"" Constraints: 1 <= s.length <= 104 s consists of lowercase English letters. Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/"318Meta,328,Odd Even Linked List,Med,Linked List,Given the head of a singly linked list; group all the nodes with odd indices together followed by the nodes with even indices; and return the reordered list. The first node is considered odd; and the second node is even; and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in O(1) extra space complexity and O(n) time complexity. Example 1: Input: head = [1;2;3;4;5] Output: [1;3;5;2;4] Example 2: Input: head = [2;1;3;5;6;4;7] Output: [2;3;6;7;1;5;4] Constraints: The number of nodes in the linked list is in the range [0; 104]. -106 <= Node.val <= 106319Meta,334,Increasing Triplet Subsequence,Med,"Array, Greedy",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. Example 1: Input: nums = [1;2;3;4;5] Output: true Explanation: Any triplet where i < j < k is valid. Example 2: Input: nums = [5;4;3;2;1] Output: false Explanation: No triplet exists. Example 3: 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. Constraints: 1 <= nums.length <= 5 * 105 -231 <= nums[i] <= 231 - 1 Follow up: Could you implement a solution that runs in O(n) time complexity and O(1) space complexity?320Meta,338,Counting Bits,Easy,"Dynamic Programming, Bit Manipulation",Given an integer n; return an array ans of length n + 1 such that for each i (0 <= i <= n); ans[i] is the number of 1's in the binary representation of i. Example 1: Input: n = 2 Output: [0;1;1] Explanation: 0 --> 0 1 --> 1 2 --> 10 Example 2: Input: n = 5 Output: [0;1;1;2;1;2] Explanation: 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101 Constraints: 0 <= n <= 105 Follow up: It is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass? Can you do it without using any built-in function (i.e.; like __builtin_popcount in C++)?321Meta,340,Longest Substring with At Most K Distinct Characters,Med,"Hash Table, String, Sliding Window",322Meta,344,Reverse String,Easy,"Two Pointers, String","Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory. Example 1: Input: s = [""h"";""e"";""l"";""l"";""o""] Output: [""o"";""l"";""l"";""e"";""h""] Example 2: Input: s = [""H"";""a"";""n"";""n"";""a"";""h""] Output: [""h"";""a"";""n"";""n"";""a"";""H""] Constraints: 1 <= s.length <= 105 s[i] is a printable ascii character."323Meta,387,First Unique Character in a String,Easy,"Hash Table, String, Queue, Counting","Given a string s; find the first non-repeating character in it and return its index. If it does not exist; return -1. Example 1: Input: s = ""leetcode"" Output: 0 Explanation: The character 'l' at index 0 is the first character that does not occur at any other index. Example 2: Input: s = ""loveleetcode"" Output: 2 Example 3: Input: s = ""aabb"" Output: -1 Constraints: 1 <= s.length <= 105 s consists of only lowercase English letters."324Meta,410,Split Array Largest Sum,Hard,"Array, Binary Search, Dynamic Programming, Greedy, Prefix Sum",Given an integer array nums and an integer k; split nums into k non-empty subarrays such that the largest sum of any subarray is minimized. Return the minimized largest sum of the split. A subarray is a contiguous part of the array. Example 1: Input: nums = [7;2;5;10;8]; k = 2 Output: 18 Explanation: There are four ways to split nums into two subarrays. The best way is to split it into [7;2;5] and [10;8]; where the largest sum among the two subarrays is only 18. Example 2: Input: nums = [1;2;3;4;5]; k = 2 Output: 9 Explanation: There are four ways to split nums into two subarrays. The best way is to split it into [1;2;3] and [4;5]; where the largest sum among the two subarrays is only 9. Constraints: 1 <= nums.length <= 1000 0 <= nums[i] <= 106 1 <= k <= min(50; nums.length)325Meta,416,Partition Equal Subset Sum,Med,"Array, Dynamic Programming",Given an integer array nums; return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise. Example 1: Input: nums = [1;5;11;5] Output: true Explanation: The array can be partitioned as [1; 5; 5] and [11]. Example 2: Input: nums = [1;2;3;5] Output: false Explanation: The array cannot be partitioned into equal sum subsets. Constraints: 1 <= nums.length <= 200 1 <= nums[i] <= 100326Meta,435,Non-overlapping Intervals,Med,"Array, Dynamic Programming, Greedy, Sorting",Given an array of intervals intervals where intervals[i] = [starti; endi]; return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. Note that intervals which only touch at a point are non-overlapping. For example; [1; 2] and [2; 3] are non-overlapping. Example 1: Input: intervals = [[1;2];[2;3];[3;4];[1;3]] Output: 1 Explanation: [1;3] can be removed and the rest of the intervals are non-overlapping. Example 2: Input: intervals = [[1;2];[1;2];[1;2]] Output: 2 Explanation: You need to remove two [1;2] to make the rest of the intervals non-overlapping. Example 3: Input: intervals = [[1;2];[2;3]] Output: 0 Explanation: You don't need to remove any of the intervals since they're already non-overlapping. Constraints: 1 <= intervals.length <= 105 intervals[i].length == 2 -5 * 104 <= starti < endi <= 5 * 104327Meta,437,Path Sum III,Med,"Tree, Depth-First Search, Binary Tree",Given the root of a binary tree and an integer targetSum; return the number of paths where the sum of the values along the path equals targetSum. The path does not need to start or end at the root or a leaf; but it must go downwards (i.e.; traveling only from parent nodes to child nodes). Example 1: Input: root = [10;5;-3;3;2;null;11;3;-2;null;1]; targetSum = 8 Output: 3 Explanation: The paths that sum to 8 are shown. Example 2: Input: root = [5;4;8;11;null;13;4;7;2;null;null;5;1]; targetSum = 22 Output: 3 Constraints: The number of nodes in the tree is in the range [0; 1000]. -109 <= Node.val <= 109 -1000 <= targetSum <= 1000328Meta,451,Sort Characters By Frequency,Med,"Hash Table, String, Sorting, Heap (Priority Queue), Bucket Sort, Counting","Given a string s; sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. Return the sorted string. If there are multiple answers; return any of them. Example 1: Input: s = ""tree"" Output: ""eert"" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore ""eetr"" is also a valid answer. Example 2: Input: s = ""cccaaa"" Output: ""aaaccc"" Explanation: Both 'c' and 'a' appear three times; so both ""cccaaa"" and ""aaaccc"" are valid answers. Note that ""cacaca"" is incorrect; as the same characters must be together. Example 3: Input: s = ""Aabb"" Output: ""bbAa"" Explanation: ""bbaA"" is also a valid answer; but ""Aabb"" is incorrect. Note that 'A' and 'a' are treated as two different characters. Constraints: 1 <= s.length <= 5 * 105 s consists of uppercase and lowercase English letters and digits."329Meta,453,Minimum Moves to Equal Array Elements,Med,"Array, Math",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. Example 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] Example 2: Input: nums = [1;1;1] Output: 0 Constraints: n == nums.length 1 <= nums.length <= 105 -109 <= nums[i] <= 109 The answer is guaranteed to fit in a 32-bit integer.330Meta,455,Assign Cookies,Easy,"Array, Two Pointers, Greedy, Sorting",Assume you are an awesome parent and want to give your children some cookies. But; you should give each child at most one cookie. Each child i has a greed factor g[i]; which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i]; we can assign the cookie j to the child i; and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number. Example 1: Input: g = [1;2;3]; s = [1;1] Output: 1 Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1; 2; 3. And even though you have 2 cookies; since their size is both 1; you could only make the child whose greed factor is 1 content. You need to output 1. Example 2: Input: g = [1;2]; s = [1;2;3] Output: 2 Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1; 2. You have 3 cookies and their sizes are big enough to gratify all of the children; You need to output 2. Constraints: 1 <= g.length <= 3 * 104 0 <= s.length <= 3 * 104 1 <= g[i]; s[j] <= 231 - 1 Note: This question is the same as 2410: Maximum Matching of Players With Trainers.331Meta,468,Validate IP Address,Med,String,"Given a string queryIP; return ""IPv4"" if IP is a valid IPv4 address; ""IPv6"" if IP is a valid IPv6 address or ""Neither"" if IP is not a correct IP of any type. A valid IPv4 address is an IP in the form ""x1.x2.x3.x4"" where 0 <= xi <= 255 and xi cannot contain leading zeros. For example; ""192.168.1.1"" and ""192.168.1.0"" are valid IPv4 addresses while ""192.168.01.1""; ""192.168.1.00""; and ""192.168@1.1"" are invalid IPv4 addresses. A valid IPv6 address is an IP in the form ""x1:x2:x3:x4:x5:x6:x7:x8"" where: 1 <= xi.length <= 4 xi is a hexadecimal string which may contain digits; lowercase English letter ('a' to 'f') and upper-case English letters ('A' to 'F'). Leading zeros are allowed in xi. For example; ""2001:0db8:85a3:0000:0000:8a2e:0370:7334"" and ""2001:db8:85a3:0:0:8A2E:0370:7334"" are valid IPv6 addresses; while ""2001:0db8:85a3::8A2E:037j:7334"" and ""02001:0db8:85a3:0000:0000:8a2e:0370:7334"" are invalid IPv6 addresses. Example 1: Input: queryIP = ""172.16.254.1"" Output: ""IPv4"" Explanation: This is a valid IPv4 address; return ""IPv4"". Example 2: Input: queryIP = ""2001:0db8:85a3:0:0:8A2E:0370:7334"" Output: ""IPv6"" Explanation: This is a valid IPv6 address; return ""IPv6"". Example 3: Input: queryIP = ""256.256.256.256"" Output: ""Neither"" Explanation: This is neither a IPv4 address nor a IPv6 address. Constraints: queryIP consists only of English letters; digits and the characters '.' and ':'."332Meta,493,Reverse Pairs,Hard,"Array, Binary Search, Divide and Conquer, Binary Indexed Tree, Segment Tree, Merge Sort, Ordered Set",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]. Example 1: 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 Example 2: Input: nums = [2;4;3;5;1] Output: 3 Explanation: The reverse pairs are: (1; 4) --> nums[1] = 4; nums[4] = 1; 4 > 2 * 1 (2; 4) --> nums[2] = 3; nums[4] = 1; 3 > 2 * 1 (3; 4) --> nums[3] = 5; nums[4] = 1; 5 > 2 * 1 Constraints: 1 <= nums.length <= 5 * 104 -231 <= nums[i] <= 231 - 1333Meta,510,Inorder Successor in BST II,Med,"Array, Binary Search, Divide and Conquer, Binary Indexed Tree, Segment Tree, Merge Sort, Ordered Set",334Meta,525,Contiguous Array,Med,"Array, Hash Table, Prefix Sum",Given a binary array nums; return the maximum length of a contiguous subarray with an equal number of 0 and 1. Example 1: Input: nums = [0;1] Output: 2 Explanation: [0; 1] is the longest contiguous subarray with an equal number of 0 and 1. Example 2: Input: nums = [0;1;0] Output: 2 Explanation: [0; 1] (or [1; 0]) is a longest contiguous subarray with equal number of 0 and 1. Constraints: 1 <= nums.length <= 105 nums[i] is either 0 or 1.335Meta,1721,Swapping Nodes in a Linked List,Med,"Array, Simulation",You are the operator of a Centennial Wheel that has four gondolas; and each gondola has room for up to four people. You have the ability to rotate the gondolas counterclockwise; which costs you runningCost dollars. You are given an array customers of length n where customers[i] is the number of new customers arriving just before the ith rotation (0-indexed). This means you must rotate the wheel i times before the customers[i] customers arrive. You cannot make customers wait if there is room in the gondola. Each customer pays boardingCost dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again. You can stop the wheel at any time; including before serving all customers. If you decide to stop serving customers; all subsequent rotations are free in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel; only four will board the gondola; and the rest will wait for the next rotation. Return the minimum number of rotations you need to perform to maximize your profit. If there is no scenario where the profit is positive; return -1. Example 1: Input: customers = [8;3]; boardingCost = 5; runningCost = 6 Output: 3 Explanation: The numbers written on the gondolas are the number of people currently there. 1. 8 customers arrive; 4 board and 4 wait for the next gondola; the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14. 2. 3 customers arrive; the 4 waiting board the wheel and the other 3 wait; the wheel rotates. Current profit is 8 * $5 - 2 * $6 = $28. 3. The final 3 customers board the gondola; the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37. The highest profit was $37 after rotating the wheel 3 times. Example 2: Input: customers = [10;9;6]; boardingCost = 6; runningCost = 4 Output: 7 Explanation: 1. 10 customers arrive; 4 board and 6 wait for the next gondola; the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20. 2. 9 customers arrive; 4 board and 11 wait (2 originally waiting; 9 newly waiting); the wheel rotates. Current profit is 8 * $6 - 2 * $4 = $40. 3. The final 6 customers arrive; 4 board and 13 wait; the wheel rotates. Current profit is 12 * $6 - 3 * $4 = $60. 4. 4 board and 9 wait; the wheel rotates. Current profit is 16 * $6 - 4 * $4 = $80. 5. 4 board and 5 wait; the wheel rotates. Current profit is 20 * $6 - 5 * $4 = $100. 6. 4 board and 1 waits; the wheel rotates. Current profit is 24 * $6 - 6 * $4 = $120. 7. 1 boards; the wheel rotates. Current profit is 25 * $6 - 7 * $4 = $122. The highest profit was $122 after rotating the wheel 7 times. Example 3: Input: customers = [3;4;0;5;1]; boardingCost = 1; runningCost = 92 Output: -1 Explanation: 1. 3 customers arrive; 3 board and 0 wait; the wheel rotates. Current profit is 3 * $1 - 1 * $92 = -$89. 2. 4 customers arrive; 4 board and 0 wait; the wheel rotates. Current profit is 7 * $1 - 2 * $92 = -$177. 3. 0 customers arrive; 0 board and 0 wait; the wheel rotates. Current profit is 7 * $1 - 3 * $92 = -$269. 4. 5 customers arrive; 4 board and 1 waits; the wheel rotates. Current profit is 11 * $1 - 4 * $92 = -$357. 5. 1 customer arrives; 2 board and 0 wait; the wheel rotates. Current profit is 13 * $1 - 5 * $92 = -$447. The profit was never positive; so return -1. Constraints: n == customers.length 1 <= n <= 105 0 <= customers[i] <= 50 1 <= boardingCost; runningCost <= 100336Meta,530,Minimum Absolute Difference in BST,Easy,"Tree, Depth-First Search, Breadth-First Search, Binary Search Tree, Binary Tree",Given the root of a Binary Search Tree (BST); return the minimum absolute difference between the values of any two different nodes in the tree. Example 1: Input: root = [4;2;6;1;3] Output: 1 Example 2: Input: root = [1;0;48;null;null;12;49] Output: 1 Constraints: The number of nodes in the tree is in the range [2; 104]. 0 <= Node.val <= 105 Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/337Meta,556,Next Greater Element III,Med,"Math, Two Pointers, String",Given a positive integer n; find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists; return -1. Note that the returned integer should fit in 32-bit integer; if there is a valid answer but it does not fit in 32-bit integer; return -1. Example 1: Input: n = 12 Output: 21 Example 2: Input: n = 21 Output: -1 Constraints: 1 <= n <= 231 - 1338Meta,584,Find Customer Referee,Easy,Database,Table: Customer +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | | referee_id | int | +-------------+---------+ In SQL; id is the primary key column for this table. Each row of this table indicates the id of a customer; their name; and the id of the customer who referred them. Find the names of the customer that are not referred by the customer with id = 2. Return the result table in any order. The result format is in the following example. Example 1: Input: Customer table: +----+------+------------+ | id | name | referee_id | +----+------+------------+ | 1 | Will | null | | 2 | Jane | null | | 3 | Alex | 2 | | 4 | Bill | null | | 5 | Zack | 1 | | 6 | Mark | 2 | +----+------+------------+ Output: +------+ | name | +------+ | Will | | Jane | | Bill | | Zack | +------+339Meta,610,Triangle Judgement,Easy,Database,Table: Triangle +-------------+------+ | Column Name | Type | +-------------+------+ | x | int | | y | int | | z | int | +-------------+------+ In SQL; (x; y; z) is the primary key column for this table. Each row of this table contains the lengths of three line segments. Report for every three line segments whether they can form a triangle. Return the result table in any order. The result format is in the following example. Example 1: Input: Triangle table: +----+----+----+ | x | y | z | +----+----+----+ | 13 | 15 | 30 | | 10 | 20 | 15 | +----+----+----+ Output: +----+----+----+----------+ | x | y | z | triangle | +----+----+----+----------+ | 13 | 15 | 30 | No | | 10 | 20 | 15 | Yes | +----+----+----+----------+340Meta,629,K Inverse Pairs Array,Hard,Dynamic Programming,For an integer array nums; an inverse pair is a pair of integers [i; j] where 0 <= i < j < nums.length and nums[i] > nums[j]. Given two integers n and k; return the number of different arrays consisting of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge; return it modulo 109 + 7. Example 1: Input: n = 3; k = 0 Output: 1 Explanation: Only the array [1;2;3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs. Example 2: Input: n = 3; k = 1 Output: 2 Explanation: The array [1;3;2] and [2;1;3] have exactly 1 inverse pair. Constraints: 1 <= n <= 1000 0 <= k <= 1000341Meta,632,Smallest Range Covering Elements from K Lists,Hard,"Array, Hash Table, Greedy, Sliding Window, Sorting, Heap (Priority Queue)",You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists. We define the range [a; b] is smaller than range [c; d] if b - a < d - c or a < c if b - a == d - c. Example 1: Input: nums = [[4;10;15;24;26];[0;9;12;20];[5;18;22;30]] Output: [20;24] Explanation: List 1: [4; 10; 15; 24;26]; 24 is in range [20;24]. List 2: [0; 9; 12; 20]; 20 is in range [20;24]. List 3: [5; 18; 22; 30]; 22 is in range [20;24]. Example 2: Input: nums = [[1;2;3];[1;2;3];[1;2;3]] Output: [1;1] Constraints: nums.length == k 1 <= k <= 3500 1 <= nums[i].length <= 50 -105 <= nums[i][j] <= 105 nums[i] is sorted in non-decreasing order.342Meta,725,Split Linked List in Parts,Med,Linked List,Given the head of a singly linked list and an integer k; split the linked list into k consecutive linked list parts. The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null. The parts should be in the order of occurrence in the input list; and parts occurring earlier should always have a size greater than or equal to parts occurring later. Return an array of the k parts. Example 1: Input: head = [1;2;3]; k = 5 Output: [[1];[2];[3];[];[]] Explanation: The first element output[0] has output[0].val = 1; output[0].next = null. The last element output[4] is null; but its string representation as a ListNode is []. Example 2: Input: head = [1;2;3;4;5;6;7;8;9;10]; k = 3 Output: [[1;2;3;4];[5;6;7];[8;9;10]] Explanation: The input has been split into consecutive parts with size difference at most 1; and earlier parts are a larger size than the later parts. Constraints: The number of nodes in the list is in the range [0; 1000]. 0 <= Node.val <= 1000 1 <= k <= 50343Meta,700,Search in a Binary Search Tree,Easy,,344Meta,703,Kth Largest Element in a Stream,Easy,,345Meta,787,Cheapest Flights Within K Stops,Med,"Array, Breadth-First Search, Matrix",On an 2 x 3 board; there are five tiles labeled from 1 to 5; and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. The state of the board is solved if and only if the board is [[1;2;3];[4;5;0]]. Given the puzzle board board; return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved; return -1. Example 1: Input: board = [[1;2;3];[4;0;5]] Output: 1 Explanation: Swap the 0 and the 5 in one move. Example 2: Input: board = [[1;2;3];[5;4;0]] Output: -1 Explanation: No number of moves will make the board solved. Example 3: Input: board = [[4;1;2];[5;0;3]] Output: 5 Explanation: 5 is the smallest number of moves that solves the board. An example path: After move 0: [[4;1;2];[5;0;3]] After move 1: [[4;1;2];[0;5;3]] After move 2: [[0;1;2];[4;5;3]] After move 3: [[1;0;2];[4;5;3]] After move 4: [[1;2;0];[4;5;3]] After move 5: [[1;2;3];[4;5;0]] Constraints: board.length == 2 board[i].length == 3 0 <= board[i][j] <= 5 Each value board[i][j] is unique.346Meta,814,Binary Tree Pruning,Med,"Array, Prefix Sum",You are given an array nums. You can rotate it by a non-negative integer k so that the array becomes [nums[k]; nums[k + 1]; ... nums[nums.length - 1]; nums[0]; nums[1]; ...; nums[k-1]]. Afterward; any entries that are less than or equal to their index are worth one point. For example; if we have nums = [2;4;1;3;0]; and we rotate by k = 2; it becomes [1;3;0;2;4]. This is worth 3 points because 1 > 0 [no points]; 3 > 1 [no points]; 0 <= 2 [one point]; 2 <= 3 [one point]; 4 <= 4 [one point]. Return the rotation index k that corresponds to the highest score we can achieve if we rotated nums by it. If there are multiple answers; return the smallest such index k. Example 1: Input: nums = [2;3;1;4;0] Output: 3 Explanation: Scores for each k are listed below: k = 0; nums = [2;3;1;4;0]; score 2 k = 1; nums = [3;1;4;0;2]; score 3 k = 2; nums = [1;4;0;2;3]; score 3 k = 3; nums = [4;0;2;3;1]; score 4 k = 4; nums = [0;2;3;1;4]; score 3 So we should choose k = 3; which has the highest score. Example 2: Input: nums = [1;3;0;2;4] Output: 0 Explanation: nums will always have 3 points no matter how it shifts. So we will choose the smallest k; which is 0. Constraints: 1 <= nums.length <= 105 0 <= nums[i] < nums.length347Meta,622,Design Circular Queue,Med,,348Meta,489,Robot Room Cleaner,Hard,"Array, Math, Dynamic Programming, Combinatorics","Bob is standing at cell (0; 0); and he wants to reach destination: (row; column). He can only travel right and down. You are going to help Bob by providing instructions for him to reach destination. The instructions are represented as a string; where each character is either: 'H'; meaning move horizontally (go right); or 'V'; meaning move vertically (go down). Multiple instructions will lead Bob to destination. For example; if destination is (2; 3); both ""HHHVV"" and ""HVHVH"" are valid instructions. However; Bob is very picky. Bob has a lucky number k; and he wants the kth lexicographically smallest instructions that will lead him to destination. k is 1-indexed. Given an integer array destination and an integer k; return the kth lexicographically smallest instructions that will take Bob to destination. Example 1: Input: destination = [2;3]; k = 1 Output: ""HHHVV"" Explanation: All the instructions that reach (2; 3) in lexicographic order are as follows: [""HHHVV""; ""HHVHV""; ""HHVVH""; ""HVHHV""; ""HVHVH""; ""HVVHH""; ""VHHHV""; ""VHHVH""; ""VHVHH""; ""VVHHH""]. Example 2: Input: destination = [2;3]; k = 2 Output: ""HHVHV"" Example 3: Input: destination = [2;3]; k = 3 Output: ""HHVVH"" Constraints: destination.length == 2 1 <= row; column <= 15 1 <= k <= nCr(row + column; row); where nCr(a; b) denotes a choose b​​​​​."349Meta,876,Middle of the Linked List,Easy,"Array, Hash Table, Greedy, Sorting",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. Example 1: 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] Example 2: Input: hand = [1;2;3;4;5]; groupSize = 4 Output: false Explanation: Alice's hand can not be rearranged into groups of 4. Constraints: 1 <= hand.length <= 104 0 <= hand[i] <= 109 1 <= groupSize <= hand.length Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/350Meta,912,Sort an Array,Med,"Array, Math, Binary Search, Prefix Sum, Randomized","You are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index. You need to implement the function pickIndex(); which randomly picks an index in the range [0; w.length - 1] (inclusive) and returns it. The probability of picking an index i is w[i] / sum(w). For example; if w = [1; 3]; the probability of picking index 0 is 1 / (1 + 3) = 0.25 (i.e.; 25%); and the probability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e.; 75%). Example 1: Input [""Solution"";""pickIndex""] [[[1]];[]] Output [null;0] Explanation Solution solution = new Solution([1]); solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. Example 2: Input [""Solution"";""pickIndex"";""pickIndex"";""pickIndex"";""pickIndex"";""pickIndex""] [[[1;3]];[];[];[];[];[]] Output [null;1;1;1;1;0] Explanation Solution solution = new Solution([1; 3]); solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. Since this is a randomization problem; multiple answers are allowed. All of the following outputs can be considered correct: [null;1;1;1;1;0] [null;1;1;1;1;1] [null;1;1;1;0;0] [null;1;1;1;0;1] [null;1;0;1;0;0] ...... and so on. Constraints: 1 <= w.length <= 104 1 <= w[i] <= 105 pickIndex will be called at most 104 times."351Meta,509,Fibonacci Number,Easy,"Tree, Binary Search Tree, Binary Tree",352Meta,1071,Greatest Common Divisor of Strings,Easy,"Array, Bit Manipulation",You are given a binary array nums (0-indexed). We define xi as the number whose binary representation is the subarray nums[0..i] (from most-significant-bit to least-significant-bit). For example; if nums = [1;0;1]; then x0 = 1; x1 = 2; and x2 = 5. Return an array of booleans answer where answer[i] is true if xi is divisible by 5. Example 1: Input: nums = [0;1;1] Output: [true;false;false] Explanation: The input numbers in binary are 0; 01; 011; which are 0; 1; and 3 in base-10. Only the first number is divisible by 5; so answer[0] is true. Example 2: Input: nums = [1;1;1] Output: [false;false;false] Constraints: 1 <= nums.length <= 105 nums[i] is either 0 or 1.353Meta,1382,Balance a Binary Search Tree,Med,"Array, Simulation",You are given a 0-indexed 2D integer array brackets where brackets[i] = [upperi; percenti] means that the ith tax bracket has an upper bound of upperi and is taxed at a rate of percenti. The brackets are sorted by upper bound (i.e. upperi-1 < upperi for 0 < i < brackets.length). Tax is calculated as follows: The first upper0 dollars earned are taxed at a rate of percent0. The next upper1 - upper0 dollars earned are taxed at a rate of percent1. The next upper2 - upper1 dollars earned are taxed at a rate of percent2. And so on. You are given an integer income representing the amount of money you earned. Return the amount of money that you have to pay in taxes. Answers within 10-5 of the actual answer will be accepted. Example 1: Input: brackets = [[3;50];[7;10];[12;25]]; income = 10 Output: 2.65000 Explanation: Based on your income; you have 3 dollars in the 1st tax bracket; 4 dollars in the 2nd tax bracket; and 3 dollars in the 3rd tax bracket. The tax rate for the three tax brackets is 50%; 10%; and 25%; respectively. In total; you pay $3 * 50% + $4 * 10% + $3 * 25% = $2.65 in taxes. Example 2: Input: brackets = [[1;0];[4;25];[5;50]]; income = 2 Output: 0.25000 Explanation: Based on your income; you have 1 dollar in the 1st tax bracket and 1 dollar in the 2nd tax bracket. The tax rate for the two tax brackets is 0% and 25%; respectively. In total; you pay $1 * 0% + $1 * 25% = $0.25 in taxes. Example 3: Input: brackets = [[2;50]]; income = 0 Output: 0.00000 Explanation: You have no income to tax; so you have to pay a total of $0 in taxes. Constraints: 1 <= brackets.length <= 100 1 <= upperi <= 1000 0 <= percenti <= 100 0 <= income <= 1000 upperi is sorted in ascending order. All the values of upperi are unique. The upper bound of the last tax bracket is greater than or equal to income.354Meta,1514,Path with Maximum Probability,Med,"Array, Prefix Sum",Given an array of integers nums; you start with an initial positive value startValue. In each iteration; you calculate the step by step sum of startValue plus elements in nums (from left to right). Return the minimum positive value of startValue such that the step by step sum is never less than 1. Example 1: Input: nums = [-3;2;-3;4;2] Output: 5 Explanation: If you choose startValue = 4; in the third iteration your step by step sum is less than 1. step by step sum startValue = 4 | startValue = 5 | nums (4 -3 ) = 1 | (5 -3 ) = 2 | -3 (1 +2 ) = 3 | (2 +2 ) = 4 | 2 (3 -3 ) = 0 | (4 -3 ) = 1 | -3 (0 +4 ) = 4 | (1 +4 ) = 5 | 4 (4 +2 ) = 6 | (5 +2 ) = 7 | 2 Example 2: Input: nums = [1;2] Output: 1 Explanation: Minimum start value should be positive. Example 3: Input: nums = [1;-2;-3] Output: 5 Constraints: 1 <= nums.length <= 100 -100 <= nums[i] <= 100355Meta,1428,Leftmost Column with at Least a One,Med,"Array, Depth-First Search, Breadth-First Search",Given an array of non-negative integers arr; you are initially positioned at start index of the array. When you are at index i; you can jump to i + arr[i] or i - arr[i]; check if you can reach any index with value 0. Notice that you can not jump outside of the array at any time. Example 1: Input: arr = [4;2;3;0;3;1;2]; start = 5 Output: true Explanation: All possible ways to reach at index 3 with value 0 are: index 5 -> index 4 -> index 1 -> index 3 index 5 -> index 6 -> index 4 -> index 1 -> index 3 Example 2: Input: arr = [4;2;3;0;3;1;2]; start = 0 Output: true Explanation: One possible way to reach at index 3 with value 0 is: index 0 -> index 4 -> index 1 -> index 3 Example 3: Input: arr = [3;0;2;1;2]; start = 2 Output: false Explanation: There is no way to reach at index 1 with value 0. Constraints: 1 <= arr.length <= 5 * 104 0 <= arr[i] < arr.length 0 <= start < arr.length356Meta,2303,Calculate Amount Paid in Taxes,Easy,"Hash Table, String, Rolling Hash, Counting, Hash Function",357Meta,1251,Average Selling Price,Easy,"Two Pointers, String, Dynamic Programming, Greedy, Rolling Hash, Hash Function","You are given a string text. You should split it to k substrings (subtext1; subtext2; ...; subtextk) such that: subtexti is a non-empty string. The concatenation of all the substrings is equal to text (i.e.; subtext1 + subtext2 + ... + subtextk == text). subtexti == subtextk - i + 1 for all valid values of i (i.e.; 1 <= i <= k). Return the largest possible value of k. Example 1: Input: text = ""ghiabcdefhelloadamhelloabcdefghi"" Output: 7 Explanation: We can split the string on ""(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)"". Example 2: Input: text = ""merchant"" Output: 1 Explanation: We can split the string on ""(merchant)"". Example 3: Input: text = ""antaprezatepzapreanta"" Output: 11 Explanation: We can split the string on ""(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)"". Constraints: 1 <= text.length <= 1000 text consists only of lowercase English characters."358Meta,1280,Students and Examinations,Easy,"Array, Sliding Window",359Meta,1378,Replace Employee ID With The Unique Identifier,Easy,"Array, Math, Simulation",There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [ri; ci] represents a 0-indexed location to perform some increment operations on the matrix. For each location indices[i]; do both of the following: Increment all the cells on row ri. Increment all the cells on column ci. Given m; n; and indices; return the number of odd-valued cells in the matrix after applying the increment to all locations in indices. Example 1: Input: m = 2; n = 3; indices = [[0;1];[1;1]] Output: 6 Explanation: Initial matrix = [[0;0;0];[0;0;0]]. After applying first increment it becomes [[1;2;1];[0;1;0]]. The final matrix is [[1;3;1];[1;3;1]]; which contains 6 odd numbers. Example 2: Input: m = 2; n = 2; indices = [[1;1];[0;0]] Output: 0 Explanation: Final matrix = [[2;2];[2;2]]. There are no odd numbers in the final matrix. Constraints: 1 <= m; n <= 50 1 <= indices.length <= 100 0 <= ri < m 0 <= ci < n Follow up: Could you solve this in O(n + m + indices.length) time with only O(n + m) extra space?360Meta,1438,Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit,Med,Database,361Meta,1493,Longest Subarray of 1's After Deleting One Element,Med,"Tree, Depth-First Search, Breadth-First Search, Graph",Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second; the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices; it jumps randomly to one of them with the same probability. Otherwise; when the frog can not jump to any unvisited vertex; it jumps forever on the same vertex. The edges of the undirected tree are given in the array edges; where edges[i] = [ai; bi] means that exists an edge connecting the vertices ai and bi. Return the probability that after t seconds the frog is on the vertex target. Answers within 10-5 of the actual answer will be accepted. Example 1: Input: n = 7; edges = [[1;2];[1;3];[1;7];[2;4];[2;6];[3;5]]; t = 2; target = 4 Output: 0.16666666666666666 Explanation: The figure above shows the given graph. The frog starts at vertex 1; jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666. Example 2: Input: n = 7; edges = [[1;2];[1;3];[1;7];[2;4];[2;6];[3;5]]; t = 1; target = 7 Output: 0.3333333333333333 Explanation: The figure above shows the given graph. The frog starts at vertex 1; jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1. Constraints: 1 <= n <= 100 edges.length == n - 1 edges[i].length == 2 1 <= ai; bi <= n 1 <= t <= 50 1 <= target <= n362Meta,1512,Number of Good Pairs,Easy,"Hash Table, String, Design","An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another. Implement the UndergroundSystem class: void checkIn(int id; string stationName; int t) A customer with a card ID equal to id; checks in at the station stationName at time t. A customer can only be checked into one place at a time. void checkOut(int id; string stationName; int t) A customer with a card ID equal to id; checks out from the station stationName at time t. double getAverageTime(string startStation; string endStation) Returns the average time it takes to travel from startStation to endStation. The average time is computed from all the previous traveling times from startStation to endStation that happened directly; meaning a check in at startStation followed by a check out from endStation. The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation. There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called. You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t1 then checks out at time t2; then t1 < t2. All events happen in chronological order. Example 1: Input [""UndergroundSystem"";""checkIn"";""checkIn"";""checkIn"";""checkOut"";""checkOut"";""checkOut"";""getAverageTime"";""getAverageTime"";""checkIn"";""getAverageTime"";""checkOut"";""getAverageTime""] [[];[45;""Leyton"";3];[32;""Paradise"";8];[27;""Leyton"";10];[45;""Waterloo"";15];[27;""Waterloo"";20];[32;""Cambridge"";22];[""Paradise"";""Cambridge""];[""Leyton"";""Waterloo""];[10;""Leyton"";24];[""Leyton"";""Waterloo""];[10;""Waterloo"";38];[""Leyton"";""Waterloo""]] Output [null;null;null;null;null;null;null;14.00000;11.00000;null;11.00000;null;12.00000] Explanation UndergroundSystem undergroundSystem = new UndergroundSystem(); undergroundSystem.checkIn(45; ""Leyton""; 3); undergroundSystem.checkIn(32; ""Paradise""; 8); undergroundSystem.checkIn(27; ""Leyton""; 10); undergroundSystem.checkOut(45; ""Waterloo""; 15); // Customer 45 ""Leyton"" -> ""Waterloo"" in 15-3 = 12 undergroundSystem.checkOut(27; ""Waterloo""; 20); // Customer 27 ""Leyton"" -> ""Waterloo"" in 20-10 = 10 undergroundSystem.checkOut(32; ""Cambridge""; 22); // Customer 32 ""Paradise"" -> ""Cambridge"" in 22-8 = 14 undergroundSystem.getAverageTime(""Paradise""; ""Cambridge""); // return 14.00000. One trip ""Paradise"" -> ""Cambridge""; (14) / 1 = 14 undergroundSystem.getAverageTime(""Leyton""; ""Waterloo""); // return 11.00000. Two trips ""Leyton"" -> ""Waterloo""; (10 + 12) / 2 = 11 undergroundSystem.checkIn(10; ""Leyton""; 24); undergroundSystem.getAverageTime(""Leyton""; ""Waterloo""); // return 11.00000 undergroundSystem.checkOut(10; ""Waterloo""; 38); // Customer 10 ""Leyton"" -> ""Waterloo"" in 38-24 = 14 undergroundSystem.getAverageTime(""Leyton""; ""Waterloo""); // return 12.00000. Three trips ""Leyton"" -> ""Waterloo""; (10 + 12 + 14) / 3 = 12 Example 2: Input [""UndergroundSystem"";""checkIn"";""checkOut"";""getAverageTime"";""checkIn"";""checkOut"";""getAverageTime"";""checkIn"";""checkOut"";""getAverageTime""] [[];[10;""Leyton"";3];[10;""Paradise"";8];[""Leyton"";""Paradise""];[5;""Leyton"";10];[5;""Paradise"";16];[""Leyton"";""Paradise""];[2;""Leyton"";21];[2;""Paradise"";30];[""Leyton"";""Paradise""]] Output [null;null;null;5.00000;null;null;5.50000;null;null;6.66667] Explanation UndergroundSystem undergroundSystem = new UndergroundSystem(); undergroundSystem.checkIn(10; ""Leyton""; 3); undergroundSystem.checkOut(10; ""Paradise""; 8); // Customer 10 ""Leyton"" -> ""Paradise"" in 8-3 = 5 undergroundSystem.getAverageTime(""Leyton""; ""Paradise""); // return 5.00000; (5) / 1 = 5 undergroundSystem.checkIn(5; ""Leyton""; 10); undergroundSystem.checkOut(5; ""Paradise""; 16); // Customer 5 ""Leyton"" -> ""Paradise"" in 16-10 = 6 undergroundSystem.getAverageTime(""Leyton""; ""Paradise""); // return 5.50000; (5 + 6) / 2 = 5.5 undergroundSystem.checkIn(2; ""Leyton""; 21); undergroundSystem.checkOut(2; ""Paradise""; 30); // Customer 2 ""Leyton"" -> ""Paradise"" in 30-21 = 9 undergroundSystem.getAverageTime(""Leyton""; ""Paradise""); // return 6.66667; (5 + 6 + 9) / 3 = 6.66667 Constraints: 1 <= id; t <= 106 1 <= stationName.length; startStation.length; endStation.length <= 10 All strings consist of uppercase and lowercase English letters and digits. There will be at most 2 * 104 calls in total to checkIn; checkOut; and getAverageTime. Answers within 10-5 of the actual value will be accepted."363Meta,1545,Find Kth Bit in Nth Binary String,Med,"Array, Dynamic Programming","Given an array of integers cost and an integer target; return the maximum integer you can paint under the following rules: The cost of painting a digit (i + 1) is given by cost[i] (0-indexed). The total cost used must be equal to target. The integer does not have 0 digits. Since the answer may be very large; return it as a string. If there is no way to paint any integer given the condition; return ""0"". Example 1: Input: cost = [4;3;2;5;6;7;2;5;5]; target = 9 Output: ""7772"" Explanation: The cost to paint the digit '7' is 2; and the digit '2' is 3. Then cost(""7772"") = 2*3+ 3*1 = 9. You could also paint ""977""; but ""7772"" is the largest number. Digit cost 1 -> 4 2 -> 3 3 -> 2 4 -> 5 5 -> 6 6 -> 7 7 -> 2 8 -> 5 9 -> 5 Example 2: Input: cost = [7;6;5;5;5;6;8;7;8]; target = 12 Output: ""85"" Explanation: The cost to paint the digit '8' is 7; and the digit '5' is 5. Then cost(""85"") = 7 + 5 = 12. Example 3: Input: cost = [2;4;6;2;4;6;4;4;4]; target = 5 Output: ""0"" Explanation: It is impossible to paint any integer with total cost equal to target. Constraints: cost.length == 9 1 <= cost[i]; target <= 5000"364Meta,1574,Shortest Subarray to be Removed to Make Array Sorted,Med,"Array, Sorting, Heap (Priority Queue)",Given the array of integers nums; you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). Example 1: Input: nums = [3;4;5;2] Output: 12 Explanation: If you choose the indices i=1 and j=2 (indexed from 0); you will get the maximum value; that is; (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. Example 2: Input: nums = [1;5;4;5] Output: 16 Explanation: Choosing the indices i=1 and j=3 (indexed from 0); you will get the maximum value of (5-1)*(5-1) = 16. Example 3: Input: nums = [3;7] Output: 12 Constraints: 2 <= nums.length <= 500 1 <= nums[i] <= 10^3365Meta,1579,Remove Max Number of Edges to Keep Graph Fully Traversable,Hard,Database,366Meta,1593,Split a String Into the Max Number of Unique Substrings,Med,,367Meta,1639,Number of Ways to Form a Target String Given a Dictionary,Hard,Database,368Meta,1671,Minimum Number of Removals to Make Mountain Array,Hard,Database,369Meta,1667,Fix Names in a Table,Easy,"String, Recursion, Simulation","Given two positive integers n and k; the binary string Sn is formed as follows: S1 = ""0"" Si = Si - 1 + ""1"" + reverse(invert(Si - 1)) for i > 1 Where + denotes the concatenation operation; reverse(x) returns the reversed string x; and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0). For example; the first four strings in the above sequence are: S1 = ""0"" S2 = ""011"" S3 = ""0111001"" S4 = ""011100110110001"" Return the kth bit in Sn. It is guaranteed that k is valid for the given n. Example 1: Input: n = 3; k = 1 Output: ""0"" Explanation: S3 is ""0111001"". The 1st bit is ""0"". Example 2: Input: n = 4; k = 11 Output: ""1"" Explanation: S4 is ""011100110110001"". The 11th bit is ""1"". Constraints: 1 <= n <= 20 1 <= k <= 2n - 1"370Meta,1845,Seat Reservation Manager,Med,"Array, Greedy, Sorting, Matrix",You are given a binary matrix matrix of size m x n; and you are allowed to rearrange the columns of the matrix in any order. Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally. Example 1: Input: matrix = [[0;0;1];[1;1;1];[1;0;1]] Output: 4 Explanation: You can rearrange the columns as shown above. The largest submatrix of 1s; in bold; has an area of 4. Example 2: Input: matrix = [[1;0;1;0;1]] Output: 3 Explanation: You can rearrange the columns as shown above. The largest submatrix of 1s; in bold; has an area of 3. Example 3: Input: matrix = [[1;1;0];[1;0;1]] Output: 2 Explanation: Notice that you must rearrange entire columns; and there is no way to make a submatrix of 1s larger than an area of 2. Constraints: m == matrix.length n == matrix[i].length 1 <= m * n <= 105 matrix[i][j] is either 0 or 1.371Meta,1891,Cutting Ribbons,Med,"Array, Two Pointers, Binary Search, Graph, Sorting",You are given an undirected graph defined by an integer n; the number of nodes; and a 2D integer array edges; the edges in the graph; where edges[i] = [ui; vi] indicates that there is an undirected edge between ui and vi. You are also given an integer array queries. Let incident(a; b) be defined as the number of edges that are connected to either node a or b. The answer to the jth query is the number of pairs of nodes (a; b) that satisfy both of the following conditions: a < b incident(a; b) > queries[j] Return an array answers such that answers.length == queries.length and answers[j] is the answer of the jth query. Note that there can be multiple edges between the same two nodes. Example 1: Input: n = 4; edges = [[1;2];[2;4];[1;3];[2;3];[2;1]]; queries = [2;3] Output: [6;5] Explanation: The calculations for incident(a; b) are shown in the table above. The answers for each of the queries are as follows: - answers[0] = 6. All the pairs have an incident(a; b) value greater than 2. - answers[1] = 5. All the pairs except (3; 4) have an incident(a; b) value greater than 3. Example 2: Input: n = 5; edges = [[1;5];[1;5];[3;4];[2;5];[1;3];[5;1];[2;3];[2;5]]; queries = [1;2;3;4;5] Output: [10;10;9;8;6] Constraints: 2 <= n <= 2 * 104 1 <= edges.length <= 105 1 <= ui; vi <= n ui != vi 1 <= queries.length <= 20 0 <= queries[j] < edges.length372Meta,2022,Convert 1D Array Into 2D Array,Easy,"Array, Dynamic Programming",The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices. For example; the alternating sum of [4;2;5;3] is (4 + 5) - (2 + 3) = 4. Given an array nums; return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence). A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example; [2;7;4] is a subsequence of [4;2;3;7;2;1;4] (the underlined elements); while [2;4;2] is not. Example 1: Input: nums = [4;2;5;3] Output: 7 Explanation: It is optimal to choose the subsequence [4;2;5] with alternating sum (4 + 5) - 2 = 7. Example 2: Input: nums = [5;6;7;8] Output: 8 Explanation: It is optimal to choose the subsequence [8] with alternating sum 8. Example 3: Input: nums = [6;2;1;2;4;5] Output: 10 Explanation: It is optimal to choose the subsequence [6;1;5] with alternating sum (6 + 5) - 1 = 10. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 105373Meta,2034,Stock Price Fluctuation,Med,"Array, Hash Table",The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|; where 0 <= i < j < a.length and a[i] != a[j]. If all elements of a are the same; the minimum absolute difference is -1. For example; the minimum absolute difference of the array [5;2;3;7;2] is |2 - 3| = 1. Note that it is not 0 because a[i] and a[j] must be different. You are given an integer array nums and the array queries where queries[i] = [li; ri]. For each query i; compute the minimum absolute difference of the subarray nums[li...ri] containing the elements of nums between the 0-based indices li and ri (inclusive). Return an array ans where ans[i] is the answer to the ith query. A subarray is a contiguous sequence of elements in an array. The value of |x| is defined as: x if x >= 0. -x if x < 0. Example 1: Input: nums = [1;3;4;8]; queries = [[0;1];[1;2];[2;3];[0;3]] Output: [2;1;4;1] Explanation: The queries are processed as follows: - queries[0] = [0;1]: The subarray is [1;3] and the minimum absolute difference is |1-3| = 2. - queries[1] = [1;2]: The subarray is [3;4] and the minimum absolute difference is |3-4| = 1. - queries[2] = [2;3]: The subarray is [4;8] and the minimum absolute difference is |4-8| = 4. - queries[3] = [0;3]: The subarray is [1;3;4;8] and the minimum absolute difference is |3-4| = 1. Example 2: Input: nums = [4;5;2;2;7;10]; queries = [[2;3];[0;2];[0;5];[3;5]] Output: [-1;1;1;3] Explanation: The queries are processed as follows: - queries[0] = [2;3]: The subarray is [2;2] and the minimum absolute difference is -1 because all the elements are the same. - queries[1] = [0;2]: The subarray is [4;5;2] and the minimum absolute difference is |4-5| = 1. - queries[2] = [0;5]: The subarray is [4;5;2;2;7;10] and the minimum absolute difference is |4-5| = 1. - queries[3] = [3;5]: The subarray is [2;7;10] and the minimum absolute difference is |7-10| = 3. Constraints: 2 <= nums.length <= 105 1 <= nums[i] <= 100 1 <= queries.length <= 2 * 104 0 <= li < ri < nums.length374Meta,2035,Partition Array Into Two Arrays to Minimize Sum Difference,Hard,"Array, Depth-First Search, Breadth-First Search, Union Find, Matrix",You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2. Return the number of islands in grid2 that are considered sub-islands. Example 1: Input: grid1 = [[1;1;1;0;0];[0;1;1;1;1];[0;0;0;0;0];[1;0;0;0;0];[1;1;0;1;1]]; grid2 = [[1;1;1;0;0];[0;0;1;1;1];[0;1;0;0;0];[1;0;1;1;0];[0;1;0;1;0]] Output: 3 Explanation: In the picture above; the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands. Example 2: Input: grid1 = [[1;0;1;0;1];[1;1;1;1;1];[0;0;0;0;0];[1;1;1;1;1];[1;0;1;0;1]]; grid2 = [[0;0;0;0;0];[1;1;1;1;1];[0;1;0;1;0];[0;1;0;1;0];[1;0;0;0;1]] Output: 2 Explanation: In the picture above; the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands. Constraints: m == grid1.length == grid2.length n == grid1[i].length == grid2[i].length 1 <= m; n <= 500 grid1[i][j] and grid2[i][j] are either 0 or 1.375Meta,2419,Longest Subarray With Maximum Bitwise AND,Med,"Array, Stack, Union Find, Monotonic Stack",You are given an integer array nums and an integer threshold. Find any subarray of nums of length k such that every element in the subarray is greater than threshold / k. Return the size of any such subarray. If there is no such subarray; return -1. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: nums = [1;3;4;3;1]; threshold = 6 Output: 3 Explanation: The subarray [3;4;3] has a size of 3; and every element is greater than 6 / 3 = 2. Note that this is the only valid subarray. Example 2: Input: nums = [6;5;6;5;8]; threshold = 7 Output: 1 Explanation: The subarray [8] has a size of 1; and 8 > 7 / 1 = 7. So 1 is returned. Note that the subarray [6;5] has a size of 2; and every element is greater than 7 / 2 = 3.5. Similarly; the subarrays [6;5;6]; [6;5;6;5]; [6;5;6;5;8] also satisfy the given conditions. Therefore; 2; 3; 4; or 5 may also be returned. Constraints: 1 <= nums.length <= 105 1 <= nums[i]; threshold <= 109376Meta,2427,Number of Common Factors,Easy,"Hash Table, String, Bit Manipulation, Counting","Given a string s consisting of lowercase English letters; return the first letter to appear twice. Note: A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b. s will contain at least one letter that appears twice. Example 1: Input: s = ""abccbaacz"" Output: ""c"" Explanation: The letter 'a' appears on the indexes 0; 5 and 6. The letter 'b' appears on the indexes 1 and 4. The letter 'c' appears on the indexes 2; 3 and 7. The letter 'z' appears on the index 8. The letter 'c' is the first letter to appear twice; because out of all the letters the index of its second occurrence is the smallest. Example 2: Input: s = ""abcdd"" Output: ""d"" Explanation: The only letter that appears twice is 'd' so we return 'd'. Constraints: 2 <= s.length <= 100 s consists of lowercase English letters. s has at least one repeated letter."377Meta,2501,Longest Square Streak in an Array,Med,Database,378Meta,2707,Extra Characters in a String,Med,"Array, Hash Table, Two Pointers",You are given two 2D integer arrays nums1 and nums2. nums1[i] = [idi; vali] indicate that the number with the id idi has a value equal to vali. nums2[i] = [idi; vali] indicate that the number with the id idi has a value equal to vali. Each array contains unique ids and is sorted in ascending order by id. Merge the two arrays into one array that is sorted in ascending order by id; respecting the following conditions: Only ids that appear in at least one of the two arrays should be included in the resulting array. Each id should be included only once and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays then its value in that array is considered to be 0. Return the resulting array. The returned array must be sorted in ascending order by id. Example 1: Input: nums1 = [[1;2];[2;3];[4;5]]; nums2 = [[1;4];[3;2];[4;1]] Output: [[1;6];[2;3];[3;2];[4;6]] Explanation: The resulting array contains the following: - id = 1; the value of this id is 2 + 4 = 6. - id = 2; the value of this id is 3. - id = 3; the value of this id is 2. - id = 4; the value of this id is 5 + 1 = 6. Example 2: Input: nums1 = [[2;4];[3;6];[5;5]]; nums2 = [[1;3];[4;3]] Output: [[1;3];[2;4];[3;6];[4;3];[5;5]] Explanation: There are no common ids; so we just include each id with its value in the resulting list. Constraints: 1 <= nums1.length; nums2.length <= 200 nums1[i].length == nums2[j].length == 2 1 <= idi; vali <= 1000 Both arrays contain unique ids. Both arrays are in strictly ascending order by id.379Meta,2723,Add Two Promises,Easy,String,"You are given a binary string s consisting only of zeroes and ones. A substring of s is considered balanced if all zeroes are before ones and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring. Return the length of the longest balanced substring of s. A substring is a contiguous sequence of characters within a string. Example 1: Input: s = ""01000111"" Output: 6 Explanation: The longest balanced substring is ""000111""; which has length 6. Example 2: Input: s = ""00111"" Output: 4 Explanation: The longest balanced substring is ""0011""; which has length 4. Example 3: Input: s = ""111"" Output: 0 Explanation: There is no balanced substring except the empty substring; so the answer is 0. Constraints: 1 <= s.length <= 50 '0' <= s[i] <= '1'"380Meta,2807,Insert Greatest Common Divisors in Linked List,Med,,"Given an array of asynchronous functions functions; return a new promise promise. Each function in the array accepts no arguments and returns a promise. All the promises should be executed in parallel. promise resolves: When all the promises returned from functions were resolved successfully in parallel. The resolved value of promise should be an array of all the resolved values of promises in the same order as they were in the functions. The promise should resolve when all the asynchronous functions in the array have completed execution in parallel. promise rejects: When any of the promises returned from functions were rejected. promise should also reject with the reason of the first rejection. Please solve it without using the built-in Promise.all function. Example 1: Input: functions = [ () => new Promise(resolve => setTimeout(() => resolve(5); 200)) ] Output: {""t"": 200; ""resolved"": [5]} Explanation: promiseAll(functions).then(console.log); // [5] The single function was resolved at 200ms with a value of 5. Example 2: Input: functions = [ () => new Promise(resolve => setTimeout(() => resolve(1); 200)); () => new Promise((resolve; reject) => setTimeout(() => reject(""Error""); 100)) ] Output: {""t"": 100; ""rejected"": ""Error""} Explanation: Since one of the promises rejected; the returned promise also rejected with the same error at the same time. Example 3: Input: functions = [ () => new Promise(resolve => setTimeout(() => resolve(4); 50)); () => new Promise(resolve => setTimeout(() => resolve(10); 150)); () => new Promise(resolve => setTimeout(() => resolve(16); 100)) ] Output: {""t"": 150; ""resolved"": [4; 10; 16]} Explanation: All the promises resolved with a value. The returned promise resolved when the last promise resolved. Constraints: functions is an array of functions that returns promises 1 <= functions.length <= 10"381Meta,2877,Create a DataFrame from List,Easy,"String, Greedy, Enumeration","Given three strings a; b; and c; your task is to find a string that has the minimum length and contains all three strings as substrings. If there are multiple such strings; return the lexicographically smallest one. Return a string denoting the answer to the problem. Notes A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ; string a has a letter that appears earlier in the alphabet than the corresponding letter in b. A substring is a contiguous sequence of characters within a string. Example 1: Input: a = ""abc""; b = ""bca""; c = ""aaa"" Output: ""aaabca"" Explanation: We show that ""aaabca"" contains all the given strings: a = ans[2...4]; b = ans[3..5]; c = ans[0..2]. It can be shown that the length of the resulting string would be at least 6 and ""aaabca"" is the lexicographically smallest one. Example 2: Input: a = ""ab""; b = ""ba""; c = ""aba"" Output: ""aba"" Explanation: We show that the string ""aba"" contains all the given strings: a = ans[0..1]; b = ans[1..2]; c = ans[0..2]. Since the length of c is 3; the length of the resulting string would be at least 3. It can be shown that ""aba"" is the lexicographically smallest one. Constraints: 1 <= a.length; b.length; c.length <= 100 a; b; c consist only of lowercase English letters."382Google,1,Two Sum,Easy,"Array, Hash Table",Given an array of integers nums and an integer target; return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution; and you may not use the same element twice. You can return the answer in any order. Example 1: Input: nums = [2;7;11;15]; target = 9 Output: [0;1] Explanation: Because nums[0] + nums[1] == 9; we return [0; 1]. Example 2: Input: nums = [3;2;4]; target = 6 Output: [1;2] Example 3: Input: nums = [3;3]; target = 6 Output: [0;1] Constraints: 2 <= nums.length <= 104 -109 <= nums[i] <= 109 -109 <= target <= 109 Only one valid answer exists. Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?383Google,2995,Viewers Turned Streamers,Hard,"Union Find, Interactive, Counting",384Google,1526,Minimum Number of Increments on Subarrays to Form a Target Array,Hard,"Hash Table, String","HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself. The special characters and their entities for HTML are: Quotation Mark: the entity is "" and symbol character is "". Single Quote Mark: the entity is ' and symbol character is '. Ampersand: the entity is & and symbol character is &. Greater Than Sign: the entity is > and symbol character is >. Less Than Sign: the entity is < and symbol character is <. Slash: the entity is ⁄ and symbol character is /. Given the input text string to the HTML parser; you have to implement the entity parser. Return the text after replacing the entities by the special characters. Example 1: Input: text = ""& is an HTML entity but &ambassador; is not."" Output: ""& is an HTML entity but &ambassador; is not."" Explanation: The parser will replace the & entity by & Example 2: Input: text = ""and I quote: ""..."""" Output: ""and I quote: \""...\"""" Constraints: 1 <= text.length <= 105 The string may contain any possible characters out of all the 256 ASCII characters."385Google,88,Merge Sorted Array,Easy,"Array, Two Pointers, Sorting",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. Example 1: 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. Example 2: Input: nums1 = [1]; m = 1; nums2 = []; n = 0 Output: [1] Explanation: The arrays we are merging are [1] and []. The result of the merge is [1]. Example 3: Input: nums1 = [0]; m = 0; nums2 = [1]; n = 1 Output: [1] Explanation: The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0; there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. Constraints: nums1.length == m + n nums2.length == n 0 <= m; n <= 200 1 <= m + n <= 200 -109 <= nums1[i]; nums2[j] <= 109 Follow up: Can you come up with an algorithm that runs in O(m + n) time?386Google,2667,Create Hello World Function,Easy,"Array, Hash Table, Math, Stack, Sliding Window",387Google,1768,Merge Strings Alternately,Easy,"Array, Math, Stack, Tree, Design, Binary Tree",388Google,1757,Recyclable and Low Fat Products,Easy,"Array, Dynamic Programming, Breadth-First Search",A certain bug's home is on the x-axis at position x. Help them get there from position 0. The bug jumps according to the following rules: It can jump exactly a positions forward (to the right). It can jump exactly b positions backward (to the left). It cannot jump backward twice in a row. It cannot jump to any forbidden positions. The bug may jump forward beyond its home; but it cannot jump to positions numbered with negative integers. Given an array of integers forbidden; where forbidden[i] means that the bug cannot jump to the position forbidden[i]; and integers a; b; and x; return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x; return -1. Example 1: Input: forbidden = [14;4;18;1;15]; a = 3; b = 15; x = 9 Output: 3 Explanation: 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home. Example 2: Input: forbidden = [8;3;16;6;12;20]; a = 15; b = 13; x = 11 Output: -1 Example 3: Input: forbidden = [1;6;2;14;5;17;4]; a = 16; b = 9; x = 7 Output: 2 Explanation: One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home. Constraints: 1 <= forbidden.length <= 1000 1 <= a; b; forbidden[i] <= 2000 0 <= x <= 2000 All the elements in forbidden are distinct. Position x is not forbidden.389Google,2,Add Two Numbers,Med,"Linked List, Math, Recursion",You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order; and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero; except the number 0 itself. Example 1: Input: l1 = [2;4;3]; l2 = [5;6;4] Output: [7;0;8] Explanation: 342 + 465 = 807. Example 2: Input: l1 = [0]; l2 = [0] Output: [0] Example 3: Input: l1 = [9;9;9;9;9;9;9]; l2 = [9;9;9;9] Output: [8;9;9;9;0;0;0;1] Constraints: The number of nodes in each linked list is in the range [1; 100]. 0 <= Node.val <= 9 It is guaranteed that the list represents a number that does not have leading zeros.390Google,42,Trapping Rain Water,Hard,"Array, Two Pointers, Dynamic Programming, Stack, Monotonic Stack",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. Example 1: 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. Example 2: Input: height = [4;2;0;3;2;5] Output: 9 Constraints: n == height.length 1 <= n <= 2 * 104 0 <= height[i] <= 105391Google,200,Number of Islands,Med,"Array, Depth-First Search, Breadth-First Search, Union Find, Matrix","Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water); return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: grid = [ [""1"";""1"";""1"";""1"";""0""]; [""1"";""1"";""0"";""1"";""0""]; [""1"";""1"";""0"";""0"";""0""]; [""0"";""0"";""0"";""0"";""0""] ] Output: 1 Example 2: Input: grid = [ [""1"";""1"";""0"";""0"";""0""]; [""1"";""1"";""0"";""0"";""0""]; [""0"";""0"";""1"";""0"";""0""]; [""0"";""0"";""0"";""1"";""1""] ] Output: 3 Constraints: m == grid.length n == grid[i].length 1 <= m; n <= 300 grid[i][j] is '0' or '1'."392Google,5,Longest Palindromic Substring,Med,"Two Pointers, String, Dynamic Programming","Given a string s; return the longest palindromic substring in s. Example 1: Input: s = ""babad"" Output: ""bab"" Explanation: ""aba"" is also a valid answer. Example 2: Input: s = ""cbbd"" Output: ""bb"" Constraints: 1 <= s.length <= 1000 s consist of only digits and English letters."393Google,13,Roman to Integer,Easy,"Hash Table, Math, String","Roman numerals are represented by seven different symbols: I; V; X; L; C; D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example; 2 is written as II in Roman numeral; just two ones added together. 12 is written as XII; which is simply X + II. The number 27 is written as XXVII; which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However; the numeral for four is not IIII. Instead; the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine; which is written as IX. There are six instances where subtraction is used: I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900. Given a roman numeral; convert it to an integer. Example 1: Input: s = ""III"" Output: 3 Explanation: III = 3. Example 2: Input: s = ""LVIII"" Output: 58 Explanation: L = 50; V= 5; III = 3. Example 3: Input: s = ""MCMXCIV"" Output: 1994 Explanation: M = 1000; CM = 900; XC = 90 and IV = 4. Constraints: 1 <= s.length <= 15 s contains only the characters ('I'; 'V'; 'X'; 'L'; 'C'; 'D'; 'M'). It is guaranteed that s is a valid roman numeral in the range [1; 3999]."394Google,70,Climbing Stairs,Easy,"Math, Dynamic Programming, Memoization",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? Example 1: Input: n = 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: Input: n = 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step Constraints: 1 <= n <= 45395Google,15,3Sum,Med,"Array, Two Pointers, Sorting",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. Example 1: Input: nums = [-1;0;1;2;-1;-4] Output: [[-1;-1;2];[-1;0;1]] Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1;0;1] and [-1;-1;2]. Notice that the order of the output and the order of the triplets does not matter. Example 2: Input: nums = [0;1;1] Output: [] Explanation: The only possible triplet does not sum up to 0. Example 3: Input: nums = [0;0;0] Output: [[0;0;0]] Explanation: The only possible triplet sums up to 0. Constraints: 3 <= nums.length <= 3000 -105 <= nums[i] <= 105396Google,121,Best Time to Buy and Sell Stock,Easy,"Array, Dynamic Programming",You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit; return 0. Example 1: Input: prices = [7;1;5;3;6;4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6); profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. Example 2: Input: prices = [7;6;4;3;1] Output: 0 Explanation: In this case; no transactions are done and the max profit = 0. Constraints: 1 <= prices.length <= 105 0 <= prices[i] <= 104397Google,9,Palindrome Number,Easy,Math,Given an integer x; return true if x is a palindrome; and false otherwise. Example 1: Input: x = 121 Output: true Explanation: 121 reads as 121 from left to right and from right to left. Example 2: Input: x = -121 Output: false Explanation: From left to right; it reads -121. From right to left; it becomes 121-. Therefore it is not a palindrome. Example 3: Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Constraints: -231 <= x <= 231 - 1 Follow up: Could you solve it without converting the integer to a string?398Google,53,Maximum Subarray,Med,"Array, Divide and Conquer, Dynamic Programming",Given an integer array nums; find the subarray with the largest sum; and return its sum. Example 1: Input: nums = [-2;1;-3;4;-1;2;1;-5;4] Output: 6 Explanation: The subarray [4;-1;2;1] has the largest sum 6. Example 2: Input: nums = [1] Output: 1 Explanation: The subarray [1] has the largest sum 1. Example 3: Input: nums = [5;4;-1;7;8] Output: 23 Explanation: The subarray [5;4;-1;7;8] has the largest sum 23. Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 Follow up: If you have figured out the O(n) solution; try coding another solution using the divide and conquer approach; which is more subtle.399Google,56,Merge Intervals,Med,"Array, Sorting",Given an array of intervals where intervals[i] = [starti; endi]; merge all overlapping intervals; and return an array of the non-overlapping intervals that cover all the intervals in the input. Example 1: Input: intervals = [[1;3];[2;6];[8;10];[15;18]] Output: [[1;6];[8;10];[15;18]] Explanation: Since intervals [1;3] and [2;6] overlap; merge them into [1;6]. Example 2: Input: intervals = [[1;4];[4;5]] Output: [[1;5]] Explanation: Intervals [1;4] and [4;5] are considered overlapping. Constraints: 1 <= intervals.length <= 104 intervals[i].length == 2 0 <= starti <= endi <= 104400Google,3,Longest Substring Without Repeating Characters,Med,"Hash Table, String, Sliding Window","Given a string s; find the length of the longest substring without repeating characters. Example 1: Input: s = ""abcabcbb"" Output: 3 Explanation: The answer is ""abc""; with the length of 3. Example 2: Input: s = ""bbbbb"" Output: 1 Explanation: The answer is ""b""; with the length of 1. Example 3: Input: s = ""pwwkew"" Output: 3 Explanation: The answer is ""wke""; with the length of 3. Notice that the answer must be a substring; ""pwke"" is a subsequence and not a substring. Constraints: 0 <= s.length <= 5 * 104 s consists of English letters; digits; symbols and spaces."401Google,169,Majority Element,Easy,"Array, Hash Table, Divide and Conquer, Sorting, Counting",Given an array nums of size n; return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. Example 1: Input: nums = [3;2;3] Output: 3 Example 2: Input: nums = [2;2;1;1;1;2;2] Output: 2 Constraints: n == nums.length 1 <= n <= 5 * 104 -109 <= nums[i] <= 109 Follow-up: Could you solve the problem in linear time and in O(1) space?402Google,14,Longest Common Prefix,Easy,"String, Trie","Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix; return an empty string """". Example 1: Input: strs = [""flower"";""flow"";""flight""] Output: ""fl"" Example 2: Input: strs = [""dog"";""racecar"";""car""] Output: """" Explanation: There is no common prefix among the input strings. Constraints: 1 <= strs.length <= 200 0 <= strs[i].length <= 200 strs[i] consists of only lowercase English letters."403Google,2235,Add Two Integers,Easy,String,"You are given a string title consisting of one or more words separated by a single space; where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that: If the length of the word is 1 or 2 letters; change all letters to lowercase. Otherwise; change the first letter to uppercase and the remaining letters to lowercase. Return the capitalized title. Example 1: Input: title = ""capiTalIze tHe titLe"" Output: ""Capitalize The Title"" Explanation: Since all the words have a length of at least 3; the first letter of each word is uppercase; and the remaining letters are lowercase. Example 2: Input: title = ""First leTTeR of EACH Word"" Output: ""First Letter of Each Word"" Explanation: The word ""of"" has length 2; so it is all lowercase. The remaining words have a length of at least 3; so the first letter of each remaining word is uppercase; and the remaining letters are lowercase. Example 3: Input: title = ""i lOve leetcode"" Output: ""i Love Leetcode"" Explanation: The word ""i"" has length 1; so it is lowercase. The remaining words have a length of at least 3; so the first letter of each remaining word is uppercase; and the remaining letters are lowercase. Constraints: 1 <= title.length <= 100 title consists of words separated by a single space without any leading or trailing spaces. Each word consists of uppercase and lowercase English letters and is non-empty."404Google,3355,Zero Array Transformation I,Med,"Array, Prefix Sum",You are given a binary array possible of length n. Alice and Bob are playing a game that consists of n levels. Some of the levels in the game are impossible to clear while others can always be cleared. In particular; if possible[i] == 0; then the ith level is impossible to clear for both the players. A player gains 1 point on clearing a level and loses 1 point if the player fails to clear it. At the start of the game; Alice will play some levels in the given order starting from the 0th level; after which Bob will play for the rest of the levels. Alice wants to know the minimum number of levels she should play to gain more points than Bob; if both players play optimally to maximize their points. Return the minimum number of levels Alice should play to gain more points. If this is not possible; return -1. Note that each player must play at least 1 level. Example 1: Input: possible = [1;0;1;0] Output: 1 Explanation: Let's look at all the levels that Alice can play up to: If Alice plays only level 0 and Bob plays the rest of the levels; Alice has 1 point; while Bob has -1 + 1 - 1 = -1 point. If Alice plays till level 1 and Bob plays the rest of the levels; Alice has 1 - 1 = 0 points; while Bob has 1 - 1 = 0 points. If Alice plays till level 2 and Bob plays the rest of the levels; Alice has 1 - 1 + 1 = 1 point; while Bob has -1 point. Alice must play a minimum of 1 level to gain more points. Example 2: Input: possible = [1;1;1;1;1] Output: 3 Explanation: Let's look at all the levels that Alice can play up to: If Alice plays only level 0 and Bob plays the rest of the levels; Alice has 1 point; while Bob has 4 points. If Alice plays till level 1 and Bob plays the rest of the levels; Alice has 2 points; while Bob has 3 points. If Alice plays till level 2 and Bob plays the rest of the levels; Alice has 3 points; while Bob has 2 points. If Alice plays till level 3 and Bob plays the rest of the levels; Alice has 4 points; while Bob has 1 point. Alice must play a minimum of 3 levels to gain more points. Example 3: Input: possible = [0;0] Output: -1 Explanation: The only possible way is for both players to play 1 level each. Alice plays level 0 and loses 1 point. Bob plays level 1 and loses 1 point. As both players have equal points; Alice can't gain more points than Bob. Constraints: 2 <= n == possible.length <= 105 possible[i] is either 0 or 1.405Google,4,Median of Two Sorted Arrays,Hard,"Array, Binary Search, Divide and Conquer",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)). Example 1: Input: nums1 = [1;3]; nums2 = [2] Output: 2.00000 Explanation: merged array = [1;2;3] and median is 2. Example 2: Input: nums1 = [1;2]; nums2 = [3;4] Output: 2.50000 Explanation: merged array = [1;2;3;4] and median is (2 + 3) / 2 = 2.5. Constraints: nums1.length == m nums2.length == n 0 <= m <= 1000 0 <= n <= 1000 1 <= m + n <= 2000 -106 <= nums1[i]; nums2[i] <= 106406Google,128,Longest Consecutive Sequence,Med,"Array, Hash Table, Union Find",Given an unsorted array of integers nums; return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time. Example 1: Input: nums = [100;4;200;1;3;2] Output: 4 Explanation: The longest consecutive elements sequence is [1; 2; 3; 4]. Therefore its length is 4. Example 2: Input: nums = [0;3;7;2;5;8;4;6;0;1] Output: 9 Constraints: 0 <= nums.length <= 105 -109 <= nums[i] <= 109407Google,253,Meeting Rooms II,Med,"Array, Two Pointers, Greedy, Sorting, Heap (Priority Queue), Prefix Sum",408Google,2663,Lexicographically Smallest Beautiful String,Hard,"Math, Greedy",You are given an integer money denoting the amount of money (in dollars) that you have and another integer children denoting the number of children that you must distribute the money to. You have to distribute the money according to the following rules: All money must be distributed. Everyone must receive at least 1 dollar. Nobody receives 4 dollars. Return the maximum number of children who may receive exactly 8 dollars if you distribute the money according to the aforementioned rules. If there is no way to distribute the money; return -1. Example 1: Input: money = 20; children = 3 Output: 1 Explanation: The maximum number of children with 8 dollars will be 1. One of the ways to distribute the money is: - 8 dollars to the first child. - 9 dollars to the second child. - 3 dollars to the third child. It can be proven that no distribution exists such that number of children getting 8 dollars is greater than 1. Example 2: Input: money = 16; children = 2 Output: 2 Explanation: Each child can be given 8 dollars. Constraints: 1 <= money <= 200 2 <= children <= 30409Google,11,Container With Most Water,Med,"Array, Two Pointers, Greedy",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. Example 1: 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. Example 2: Input: height = [1;1] Output: 1 Constraints: n == height.length 2 <= n <= 105 0 <= height[i] <= 104410Google,359,Logger Rate Limiter,Easy,"Hash Table, Design, Data Stream",411Google,179,Largest Number,Med,"Array, String, Greedy, Sorting","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. Example 1: Input: nums = [10;2] Output: ""210"" Example 2: Input: nums = [3;30;34;5;9] Output: ""9534330"" Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 109"412Google,7,Reverse Integer,Med,Math,Given a signed 32-bit integer x; return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231; 231 - 1]; then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). Example 1: Input: x = 123 Output: 321 Example 2: Input: x = -123 Output: -321 Example 3: Input: x = 120 Output: 21 Constraints: -231 <= x <= 231 - 1413Google,20,Valid Parentheses,Easy,"String, Stack","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. Example 1: Input: s = ""()"" Output: true Example 2: Input: s = ""()[]{}"" Output: true Example 3: Input: s = ""(]"" Output: false Example 4: Input: s = ""([])"" Output: true Constraints: 1 <= s.length <= 104 s consists of parentheses only '()[]{}'."414Google,28,Find the Index of the First Occurrence in a String,Easy,"Two Pointers, String, String Matching","Given two strings needle and haystack; return the index of the first occurrence of needle in haystack; or -1 if needle is not part of haystack. Example 1: Input: haystack = ""sadbutsad""; needle = ""sad"" Output: 0 Explanation: ""sad"" occurs at index 0 and 6. The first occurrence is at index 0; so we return 0. Example 2: Input: haystack = ""leetcode""; needle = ""leeto"" Output: -1 Explanation: ""leeto"" did not occur in ""leetcode""; so we return -1. Constraints: 1 <= haystack.length; needle.length <= 104 haystack and needle consist of only lowercase English characters."415Google,939,Minimum Area Rectangle,Med,"String, Dynamic Programming, Prefix Sum","You are given a string s of length n where s[i] is either: 'D' means decreasing; or 'I' means increasing. A permutation perm of n + 1 integers of all the integers in the range [0; n] is called a valid permutation if for all valid i: If s[i] == 'D'; then perm[i] > perm[i + 1]; and If s[i] == 'I'; then perm[i] < perm[i + 1]. Return the number of valid permutations perm. Since the answer may be large; return it modulo 109 + 7. Example 1: Input: s = ""DID"" Output: 5 Explanation: The 5 valid permutations of (0; 1; 2; 3) are: (1; 0; 3; 2) (2; 0; 3; 1) (2; 1; 3; 0) (3; 0; 2; 1) (3; 1; 2; 0) Example 2: Input: s = ""D"" Output: 1 Constraints: n == s.length 1 <= n <= 200 s[i] is either 'I' or 'D'."416Google,27,Remove Element,Easy,"Array, Two Pointers",Given an integer array nums and an integer val; remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val. Consider the number of elements in nums which are not equal to val be k; to get accepted; you need to do the following things: Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums. Return k. Custom Judge: The judge will test your solution with the following code: int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums; val); // Calls your implementation assert k == expectedNums.length; sort(nums; 0; k); // Sort the first k elements of nums for (int i = 0; i < actualLength; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass; then your solution will be accepted. Example 1: Input: nums = [3;2;2;3]; val = 3 Output: 2; nums = [2;2;_;_] Explanation: Your function should return k = 2; with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). Example 2: Input: nums = [0;1;2;2;3;0;4;2]; val = 2 Output: 5; nums = [0;1;4;0;3;_;_;_] Explanation: Your function should return k = 5; with the first five elements of nums containing 0; 0; 1; 3; and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). Constraints: 0 <= nums.length <= 100 0 <= nums[i] <= 50 0 <= val <= 100417Google,49,Group Anagrams,Med,"Array, Hash Table, String, Sorting","Given an array of strings strs; group the anagrams together. You can return the answer in any order. Example 1: Input: strs = [""eat"";""tea"";""tan"";""ate"";""nat"";""bat""] Output: [[""bat""];[""nat"";""tan""];[""ate"";""eat"";""tea""]] Explanation: There is no string in strs that can be rearranged to form ""bat"". The strings ""nat"" and ""tan"" are anagrams as they can be rearranged to form each other. The strings ""ate""; ""eat""; and ""tea"" are anagrams as they can be rearranged to form each other. Example 2: Input: strs = [""""] Output: [[""""]] Example 3: Input: strs = [""a""] Output: [[""a""]] Constraints: 1 <= strs.length <= 104 0 <= strs[i].length <= 100 strs[i] consists of lowercase English letters."418Google,394,Decode String,Med,"String, Stack, Recursion","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. Example 1: Input: s = ""3[a]2[bc]"" Output: ""aaabcbc"" Example 2: Input: s = ""3[a2[c]]"" Output: ""accaccacc"" Example 3: Input: s = ""2[abc]3[cd]ef"" Output: ""abcabccdcdcdef"" Constraints: 1 <= s.length <= 30 s consists of lowercase English letters; digits; and square brackets '[]'. s is guaranteed to be a valid input. All the integers in s are in the range [1; 300]."419Google,3318,Find X-Sum of All K-Long Subarrays I,Easy,"Array, Dynamic Programming, Memoization",Given an array of integers called nums; you can perform any of the following operation while nums contains at least 2 elements: Choose the first two elements of nums and delete them. Choose the last two elements of nums and delete them. Choose the first and the last elements of nums and delete them. The score of the operation is the sum of the deleted elements. Your task is to find the maximum number of operations that can be performed; such that all operations have the same score. Return the maximum number of operations possible that satisfy the condition mentioned above. Example 1: Input: nums = [3;2;1;2;3;4] Output: 3 Explanation: We perform the following operations: - Delete the first two elements; with score 3 + 2 = 5; nums = [1;2;3;4]. - Delete the first and the last elements; with score 1 + 4 = 5; nums = [2;3]. - Delete the first and the last elements; with score 2 + 3 = 5; nums = []. We are unable to perform any more operations as nums is empty. Example 2: Input: nums = [3;2;6;1;4] Output: 2 Explanation: We perform the following operations: - Delete the first two elements; with score 3 + 2 = 5; nums = [6;1;4]. - Delete the last two elements; with score 1 + 4 = 5; nums = [6]. It can be proven that we can perform at most 2 operations. Constraints: 2 <= nums.length <= 2000 1 <= nums[i] <= 1000420Google,3356,Zero Array Transformation II,Med,"Array, Hash Table, String, Trie","You are given an array arr of size n consisting of non-empty strings. Find a string array answer of size n such that: answer[i] is the shortest substring of arr[i] that does not occur as a substring in any other string in arr. If multiple such substrings exist; answer[i] should be the lexicographically smallest. And if no such substring exists; answer[i] should be an empty string. Return the array answer. Example 1: Input: arr = [""cab"";""ad"";""bad"";""c""] Output: [""ab"";"""";""ba"";""""] Explanation: We have the following: - For the string ""cab""; the shortest substring that does not occur in any other string is either ""ca"" or ""ab""; we choose the lexicographically smaller substring; which is ""ab"". - For the string ""ad""; there is no substring that does not occur in any other string. - For the string ""bad""; the shortest substring that does not occur in any other string is ""ba"". - For the string ""c""; there is no substring that does not occur in any other string. Example 2: Input: arr = [""abc"";""bcd"";""abcd""] Output: ["""";"""";""abcd""] Explanation: We have the following: - For the string ""abc""; there is no substring that does not occur in any other string. - For the string ""bcd""; there is no substring that does not occur in any other string. - For the string ""abcd""; the shortest substring that does not occur in any other string is ""abcd"". Constraints: n == arr.length 2 <= n <= 100 1 <= arr[i].length <= 20 arr[i] consists only of lowercase English letters."421Google,26,Remove Duplicates from Sorted Array,Easy,"Array, Two Pointers",Given an integer array nums sorted in non-decreasing order; remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums. Consider the number of unique elements of nums to be k; to get accepted; you need to do the following things: Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums. Return k. Custom Judge: The judge will test your solution with the following code: int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass; then your solution will be accepted. Example 1: Input: nums = [1;1;2] Output: 2; nums = [1;2;_] Explanation: Your function should return k = 2; with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). Example 2: Input: nums = [0;0;1;1;1;2;2;3;3;4] Output: 5; nums = [0;1;2;3;4;_;_;_;_;_] Explanation: Your function should return k = 5; with the first five elements of nums being 0; 1; 2; 3; and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). Constraints: 1 <= nums.length <= 3 * 104 -100 <= nums[i] <= 100 nums is sorted in non-decreasing order.422Google,55,Jump Game,Med,"Array, Dynamic Programming, Greedy",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. Example 1: 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. Example 2: 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. Constraints: 1 <= nums.length <= 104 0 <= nums[i] <= 105423Google,1381,Design a Stack With Increment Operation,Med,"Array, String, Dynamic Programming, Backtracking, Bit Manipulation, Bitmask","Given a list of words; list of single letters (might be repeating) and score of every character. Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times). It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a'; 'b'; 'c'; ... ;'z' is given by score[0]; score[1]; ... ; score[25] respectively. Example 1: Input: words = [""dog"";""cat"";""dad"";""good""]; letters = [""a"";""a"";""c"";""d"";""d"";""d"";""g"";""o"";""o""]; score = [1;0;9;5;0;0;3;0;0;0;0;0;0;0;2;0;0;0;0;0;0;0;0;0;0;0] Output: 23 Explanation: Score a=1; c=9; d=5; g=3; o=2 Given letters; we can form the words ""dad"" (5+1+5) and ""good"" (3+2+2+5) with a score of 23. Words ""dad"" and ""dog"" only get a score of 21. Example 2: Input: words = [""xxxz"";""ax"";""bx"";""cx""]; letters = [""z"";""a"";""b"";""c"";""x"";""x"";""x""]; score = [4;4;4;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;5;0;10] Output: 27 Explanation: Score a=4; b=4; c=4; x=5; z=10 Given letters; we can form the words ""ax"" (4+5); ""bx"" (4+5) and ""cx"" (4+5) with a score of 27. Word ""xxxz"" only get a score of 25. Example 3: Input: words = [""leetcode""]; letters = [""l"";""e"";""t"";""c"";""o"";""d""]; score = [0;0;1;1;1;0;0;0;0;0;0;1;0;0;1;0;0;0;0;1;0;0;0;0;0;0] Output: 0 Explanation: Letter ""e"" can only be used once. Constraints: 1 <= words.length <= 14 1 <= words[i].length <= 15 1 <= letters.length <= 100 letters[i].length == 1 score.length == 26 0 <= score[i] <= 10 words[i]; letters[i] contains only lower case English letters."424Google,3349,Adjacent Increasing Subarrays Detection I,Easy,"Hash Table, String, Sliding Window","Given a string s; return the maximum length of a substring such that it contains at most two occurrences of each character. Example 1: Input: s = ""bcbbbcba"" Output: 4 Explanation: The following substring has a length of 4 and contains at most two occurrences of each character: ""bcbbbcba"". Example 2: Input: s = ""aaaa"" Output: 2 Explanation: The following substring has a length of 2 and contains at most two occurrences of each character: ""aaaa"". Constraints: 2 <= s.length <= 100 s consists only of lowercase English letters."425Google,3346,Maximum Frequency of an Element After Performing Operations I,Med,"String, Greedy","You are given a string s and an integer k. Define a function distance(s1; s2) between two strings s1 and s2 of the same length n as: The sum of the minimum distance between s1[i] and s2[i] when the characters from 'a' to 'z' are placed in a cyclic order; for all i in the range [0; n - 1]. For example; distance(""ab""; ""cd"") == 4; and distance(""a""; ""z"") == 1. You can change any letter of s to any other lowercase English letter; any number of times. Return a string denoting the lexicographically smallest string t you can get after some changes; such that distance(s; t) <= k. Example 1: Input: s = ""zbbz""; k = 3 Output: ""aaaz"" Explanation: Change s to ""aaaz"". The distance between ""zbbz"" and ""aaaz"" is equal to k = 3. Example 2: Input: s = ""xaxcd""; k = 4 Output: ""aawcd"" Explanation: The distance between ""xaxcd"" and ""aawcd"" is equal to k = 4. Example 3: Input: s = ""lol""; k = 0 Output: ""lol"" Explanation: It's impossible to change any character as k = 0. Constraints: 1 <= s.length <= 100 0 <= k <= 2000 s consists only of lowercase English letters."426Google,3347,Maximum Frequency of an Element After Performing Operations II,Hard,"Array, Simulation",You are given a 1-indexed array of distinct integers nums of length n. You need to distribute all the elements of nums between two arrays arr1 and arr2 using n operations. In the first operation; append nums[1] to arr1. In the second operation; append nums[2] to arr2. Afterwards; in the ith operation: If the last element of arr1 is greater than the last element of arr2; append nums[i] to arr1. Otherwise; append nums[i] to arr2. The array result is formed by concatenating the arrays arr1 and arr2. For example; if arr1 == [1;2;3] and arr2 == [4;5;6]; then result = [1;2;3;4;5;6]. Return the array result. Example 1: Input: nums = [2;1;3] Output: [2;3;1] Explanation: After the first 2 operations; arr1 = [2] and arr2 = [1]. In the 3rd operation; as the last element of arr1 is greater than the last element of arr2 (2 > 1); append nums[3] to arr1. After 3 operations; arr1 = [2;3] and arr2 = [1]. Hence; the array result formed by concatenation is [2;3;1]. Example 2: Input: nums = [5;4;3;8] Output: [5;3;4;8] Explanation: After the first 2 operations; arr1 = [5] and arr2 = [4]. In the 3rd operation; as the last element of arr1 is greater than the last element of arr2 (5 > 4); append nums[3] to arr1; hence arr1 becomes [5;3]. In the 4th operation; as the last element of arr2 is greater than the last element of arr1 (4 > 3); append nums[4] to arr2; hence arr2 becomes [4;8]. After 4 operations; arr1 = [5;3] and arr2 = [4;8]. Hence; the array result formed by concatenation is [5;3;4;8]. Constraints: 3 <= n <= 50 1 <= nums[i] <= 100 All elements in nums are distinct.427Google,84,Largest Rectangle in Histogram,Hard,"Array, Stack, Monotonic Stack",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 1: Input: heights = [2;1;5;6;2;3] Output: 10 Explanation: The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area; which has an area = 10 units. Example 2: Input: heights = [2;4] Output: 4 Constraints: 1 <= heights.length <= 105 0 <= heights[i] <= 104428Google,206,Reverse Linked List,Easy,"Linked List, Recursion",Given the head of a singly linked list; reverse the list; and return the reversed list. Example 1: Input: head = [1;2;3;4;5] Output: [5;4;3;2;1] Example 2: Input: head = [1;2] Output: [2;1] Example 3: Input: head = [] Output: [] Constraints: The number of nodes in the list is the range [0; 5000]. -5000 <= Node.val <= 5000 Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?429Google,300,Longest Increasing Subsequence,Med,"Array, Binary Search, Dynamic Programming",Given an integer array nums; return the length of the longest strictly increasing subsequence. Example 1: 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. Example 2: Input: nums = [0;1;0;3;2;3] Output: 4 Example 3: Input: nums = [7;7;7;7;7;7;7] Output: 1 Constraints: 1 <= nums.length <= 2500 -104 <= nums[i] <= 104 Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?430Google,994,Rotting Oranges,Med,"Array, Hash Table, Math, Bit Manipulation",There are 8 prison cells in a row and each cell is either occupied or vacant. Each day; whether the cell is occupied or vacant changes according to the following rules: If a cell has two adjacent neighbors that are both occupied or both vacant; then the cell becomes occupied. Otherwise; it becomes vacant. Note that because the prison is a row; the first and the last cells in the row can't have two adjacent neighbors. You are given an integer array cells where cells[i] == 1 if the ith cell is occupied and cells[i] == 0 if the ith cell is vacant; and you are given an integer n. Return the state of the prison after n days (i.e.; n such changes described above). Example 1: Input: cells = [0;1;0;1;1;0;0;1]; n = 7 Output: [0;0;1;1;0;0;0;0] Explanation: The following table summarizes the state of the prison on each day: Day 0: [0; 1; 0; 1; 1; 0; 0; 1] Day 1: [0; 1; 1; 0; 0; 0; 0; 0] Day 2: [0; 0; 0; 0; 1; 1; 1; 0] Day 3: [0; 1; 1; 0; 0; 1; 0; 0] Day 4: [0; 0; 0; 0; 0; 1; 0; 0] Day 5: [0; 1; 1; 1; 0; 1; 0; 0] Day 6: [0; 0; 1; 0; 1; 1; 0; 0] Day 7: [0; 0; 1; 1; 0; 0; 0; 0] Example 2: Input: cells = [1;0;0;1;0;0;1;0]; n = 1000000000 Output: [0;0;1;1;1;1;1;0] Constraints: cells.length == 8 cells[i] is either 0 or 1. 1 <= n <= 109431Google,3026,Maximum Good Subarray Sum,Med,"Math, Greedy",You are given positive integers n and target. An array nums is beautiful if it meets the following conditions: nums.length == n. nums consists of pairwise distinct positive integers. There doesn't exist two distinct indices; i and j; in the range [0; n - 1]; such that nums[i] + nums[j] == target. Return the minimum possible sum that a beautiful array could have modulo 109 + 7. Example 1: Input: n = 2; target = 3 Output: 4 Explanation: We can see that nums = [1;3] is beautiful. - The array nums has length n = 2. - The array nums consists of pairwise distinct positive integers. - There doesn't exist two distinct indices; i and j; with nums[i] + nums[j] == 3. It can be proven that 4 is the minimum possible sum that a beautiful array could have. Example 2: Input: n = 3; target = 3 Output: 8 Explanation: We can see that nums = [1;3;4] is beautiful. - The array nums has length n = 3. - The array nums consists of pairwise distinct positive integers. - There doesn't exist two distinct indices; i and j; with nums[i] + nums[j] == 3. It can be proven that 8 is the minimum possible sum that a beautiful array could have. Example 3: Input: n = 1; target = 1 Output: 1 Explanation: We can see; that nums = [1] is beautiful. Constraints: 1 <= n <= 109 1 <= target <= 109432Google,3020,Find the Maximum Number of Elements in Subset,Med,,433Google,3350,Adjacent Increasing Subarrays Detection II,Med,"Array, Binary Indexed Tree, Segment Tree, Simulation",You are given a 1-indexed array of integers nums of length n. We define a function greaterCount such that greaterCount(arr; val) returns the number of elements in arr that are strictly greater than val. You need to distribute all the elements of nums between two arrays arr1 and arr2 using n operations. In the first operation; append nums[1] to arr1. In the second operation; append nums[2] to arr2. Afterwards; in the ith operation: If greaterCount(arr1; nums[i]) > greaterCount(arr2; nums[i]); append nums[i] to arr1. If greaterCount(arr1; nums[i]) < greaterCount(arr2; nums[i]); append nums[i] to arr2. If greaterCount(arr1; nums[i]) == greaterCount(arr2; nums[i]); append nums[i] to the array with a lesser number of elements. If there is still a tie; append nums[i] to arr1. The array result is formed by concatenating the arrays arr1 and arr2. For example; if arr1 == [1;2;3] and arr2 == [4;5;6]; then result = [1;2;3;4;5;6]. Return the integer array result. Example 1: Input: nums = [2;1;3;3] Output: [2;3;1;3] Explanation: After the first 2 operations; arr1 = [2] and arr2 = [1]. In the 3rd operation; the number of elements greater than 3 is zero in both arrays. Also; the lengths are equal; hence; append nums[3] to arr1. In the 4th operation; the number of elements greater than 3 is zero in both arrays. As the length of arr2 is lesser; hence; append nums[4] to arr2. After 4 operations; arr1 = [2;3] and arr2 = [1;3]. Hence; the array result formed by concatenation is [2;3;1;3]. Example 2: Input: nums = [5;14;3;1;2] Output: [5;3;1;2;14] Explanation: After the first 2 operations; arr1 = [5] and arr2 = [14]. In the 3rd operation; the number of elements greater than 3 is one in both arrays. Also; the lengths are equal; hence; append nums[3] to arr1. In the 4th operation; the number of elements greater than 1 is greater in arr1 than arr2 (2 > 1). Hence; append nums[4] to arr1. In the 5th operation; the number of elements greater than 2 is greater in arr1 than arr2 (2 > 1). Hence; append nums[5] to arr1. After 5 operations; arr1 = [5;3;1;2] and arr2 = [14]. Hence; the array result formed by concatenation is [5;3;1;2;14]. Example 3: Input: nums = [3;3;3;3] Output: [3;3;3;3] Explanation: At the end of 4 operations; arr1 = [3;3] and arr2 = [3;3]. Hence; the array result formed by concatenation is [3;3;3;3]. Constraints: 3 <= n <= 105 1 <= nums[i] <= 109434Google,3351,Sum of Good Subsequences,Hard,"Array, Greedy, Sorting",You are given an array happiness of length n; and a positive integer k. There are n children standing in a queue; where the ith child has happiness value happiness[i]. You want to select k children from these n children in k turns. In each turn; when you select a child; the happiness value of all the children that have not been selected till now decreases by 1. Note that the happiness value cannot become negative and gets decremented only if it is positive. Return the maximum sum of the happiness values of the selected children you can achieve by selecting k children. Example 1: Input: happiness = [1;2;3]; k = 2 Output: 4 Explanation: We can pick 2 children in the following way: - Pick the child with the happiness value == 3. The happiness value of the remaining children becomes [0;1]. - Pick the child with the happiness value == 1. The happiness value of the remaining child becomes [0]. Note that the happiness value cannot become less than 0. The sum of the happiness values of the selected children is 3 + 1 = 4. Example 2: Input: happiness = [1;1;1;1]; k = 2 Output: 1 Explanation: We can pick 2 children in the following way: - Pick any child with the happiness value == 1. The happiness value of the remaining children becomes [0;0;0]. - Pick the child with the happiness value == 0. The happiness value of the remaining child becomes [0;0]. The sum of the happiness values of the selected children is 1 + 0 = 1. Example 3: Input: happiness = [2;3;4;5]; k = 1 Output: 5 Explanation: We can pick 1 child in the following way: - Pick the child with the happiness value == 5. The happiness value of the remaining children becomes [1;2;3]. The sum of the happiness values of the selected children is 5. Constraints: 1 <= n == happiness.length <= 2 * 105 1 <= happiness[i] <= 108 1 <= k <= n435Google,50,"Pow(x, n)",Med,"Math, Recursion",Implement pow(x; n); which calculates x raised to the power n (i.e.; xn). Example 1: Input: x = 2.00000; n = 10 Output: 1024.00000 Example 2: Input: x = 2.10000; n = 3 Output: 9.26100 Example 3: Input: x = 2.00000; n = -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25 Constraints: -100.0 < x < 100.0 -231 <= n <= 231-1 n is an integer. Either x is not zero or n > 0. -104 <= xn <= 104436Google,67,Add Binary,Easy,"Math, String, Bit Manipulation, Simulation","Given two binary strings a and b; return their sum as a binary string. Example 1: Input: a = ""11""; b = ""1"" Output: ""100"" Example 2: Input: a = ""1010""; b = ""1011"" Output: ""10101"" Constraints: 1 <= a.length; b.length <= 104 a and b consist only of '0' or '1' characters. Each string does not contain leading zeros except for the zero itself."437Google,136,Single Number,Easy,"Array, Bit Manipulation",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. Example 1: Input: nums = [2;2;1] Output: 1 Example 2: Input: nums = [4;1;2;1;2] Output: 4 Example 3: Input: nums = [1] Output: 1 Constraints: 1 <= nums.length <= 3 * 104 -3 * 104 <= nums[i] <= 3 * 104 Each element in the array appears twice except for one element which appears only once.438Google,207,Course Schedule,Med,"Depth-First Search, Breadth-First Search, Graph, Topological Sort",There are a total of numCourses courses you have to take; labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai; bi] indicates that you must take course bi first if you want to take course ai. For example; the pair [0; 1]; indicates that to take course 0 you have to first take course 1. Return true if you can finish all courses. Otherwise; return false. Example 1: Input: numCourses = 2; prerequisites = [[1;0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. Example 2: Input: numCourses = 2; prerequisites = [[1;0];[0;1]] Output: false Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0; and to take course 0 you should also have finished course 1. So it is impossible. Constraints: 1 <= numCourses <= 2000 0 <= prerequisites.length <= 5000 prerequisites[i].length == 2 0 <= ai; bi < numCourses All the pairs prerequisites[i] are unique.439Google,242,Valid Anagram,Easy,"Hash Table, String, Sorting","Given two strings s and t; return true if t is an anagram of s; and false otherwise. Example 1: Input: s = ""anagram""; t = ""nagaram"" Output: true Example 2: Input: s = ""rat""; t = ""car"" Output: false Constraints: 1 <= s.length; t.length <= 5 * 104 s and t consist of lowercase English letters. Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?"440Google,567,Permutation in String,Med,"Hash Table, Two Pointers, String, Sliding Window","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. Example 1: Input: s1 = ""ab""; s2 = ""eidbaooo"" Output: true Explanation: s2 contains one permutation of s1 (""ba""). Example 2: Input: s1 = ""ab""; s2 = ""eidboaoo"" Output: false Constraints: 1 <= s1.length; s2.length <= 104 s1 and s2 consist of lowercase English letters."441Google,584,Find Customer Referee,Easy,Database,Table: Customer +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | | referee_id | int | +-------------+---------+ In SQL; id is the primary key column for this table. Each row of this table indicates the id of a customer; their name; and the id of the customer who referred them. Find the names of the customer that are not referred by the customer with id = 2. Return the result table in any order. The result format is in the following example. Example 1: Input: Customer table: +----+------+------------+ | id | name | referee_id | +----+------+------------+ | 1 | Will | null | | 2 | Jane | null | | 3 | Alex | 2 | | 4 | Bill | null | | 5 | Zack | 1 | | 6 | Mark | 2 | +----+------+------------+ Output: +------+ | name | +------+ | Will | | Jane | | Bill | | Zack | +------+442Google,1101,The Earliest Moment When Everyone Become Friends,Med,"Graph, Topological Sort",443Google,2458,Height of Binary Tree After Subtree Removal Queries,Hard,"Array, Greedy, Sorting",444Google,2981,Find Longest Special Substring That Occurs Thrice I,Med,,445Google,2985,Calculate Compressed Mean,Easy,,446Google,2987,Find Expensive Cities,Easy,,447Google,2989,Class Performance,Med,,448Google,2990,Loan Types,Easy,,449Google,2991,Top Three Wineries,Hard,,450Google,3008,Find Beautiful Indices in the Given Array II,Hard,,451Google,3028,Ant on the Boundary,Easy,,452Google,3024,Type of Triangle,Easy,"Math, String, Dynamic Programming, String Matching","You are given two strings s and t of equal length n. You can perform the following operation on the string s: Remove a suffix of s of length l where 0 < l < n and append it at the start of s. For example; let s = 'abcd' then in one operation you can remove the suffix 'cd' and append it in front of s making s = 'cdab'. You are also given an integer k. Return the number of ways in which s can be transformed into t in exactly k operations. Since the answer can be large; return it modulo 109 + 7. Example 1: Input: s = ""abcd""; t = ""cdab""; k = 2 Output: 2 Explanation: First way: In first operation; choose suffix from index = 3; so resulting s = ""dabc"". In second operation; choose suffix from index = 3; so resulting s = ""cdab"". Second way: In first operation; choose suffix from index = 1; so resulting s = ""bcda"". In second operation; choose suffix from index = 1; so resulting s = ""cdab"". Example 2: Input: s = ""ababab""; t = ""ababab""; k = 1 Output: 2 Explanation: First way: Choose suffix from index = 2; so resulting s = ""ababab"". Second way: Choose suffix from index = 4; so resulting s = ""ababab"". Constraints: 2 <= s.length <= 5 * 105 1 <= k <= 1015 s.length == t.length s and t consist of only lowercase English alphabets."453Google,73,Set Matrix Zeroes,Med,"Array, Hash Table, Matrix",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. Example 1: Input: matrix = [[1;1;1];[1;0;1];[1;1;1]] Output: [[1;0;1];[0;0;0];[1;0;1]] Example 2: Input: matrix = [[0;1;2;0];[3;4;5;2];[1;3;1;5]] Output: [[0;0;0;0];[0;4;5;0];[0;3;1;0]] Constraints: m == matrix.length n == matrix[0].length 1 <= m; n <= 200 -231 <= matrix[i][j] <= 231 - 1 Follow up: A straightforward solution using O(mn) space is probably a bad idea. A simple improvement uses O(m + n) space; but still not the best solution. Could you devise a constant space solution?454Google,118,Pascal's Triangle,Easy,"Array, Dynamic Programming",Given an integer numRows; return the first numRows of Pascal's triangle. In Pascal's triangle; each number is the sum of the two numbers directly above it as shown: Example 1: Input: numRows = 5 Output: [[1];[1;1];[1;2;1];[1;3;3;1];[1;4;6;4;1]] Example 2: Input: numRows = 1 Output: [[1]] Constraints: 1 <= numRows <= 30455Google,146,LRU Cache,Med,"Hash Table, Linked List, Design, Doubly-Linked List","Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class: LRUCache(int capacity) Initialize the LRU cache with positive size capacity. int get(int key) Return the value of the key if the key exists; otherwise return -1. void put(int key; int value) Update the value of the key if the key exists. Otherwise; add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation; evict the least recently used key. The functions get and put must each run in O(1) average time complexity. Example 1: Input [""LRUCache""; ""put""; ""put""; ""get""; ""put""; ""get""; ""put""; ""get""; ""get""; ""get""] [[2]; [1; 1]; [2; 2]; [1]; [3; 3]; [2]; [4; 4]; [1]; [3]; [4]] Output [null; null; null; 1; null; -1; null; -1; 3; 4] Explanation LRUCache lRUCache = new LRUCache(2); lRUCache.put(1; 1); // cache is {1=1} lRUCache.put(2; 2); // cache is {1=1; 2=2} lRUCache.get(1); // return 1 lRUCache.put(3; 3); // LRU key was 2; evicts key 2; cache is {1=1; 3=3} lRUCache.get(2); // returns -1 (not found) lRUCache.put(4; 4); // LRU key was 1; evicts key 1; cache is {4=4; 3=3} lRUCache.get(1); // return -1 (not found) lRUCache.get(3); // return 3 lRUCache.get(4); // return 4 Constraints: 1 <= capacity <= 3000 0 <= key <= 104 0 <= value <= 105 At most 2 * 105 calls will be made to get and put."456Google,162,Find Peak Element,Med,"Array, Binary Search",A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums; find a peak element; and return its index. If the array contains multiple peaks; return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -∞. In other words; an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in O(log n) time. Example 1: Input: nums = [1;2;3;1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2. Example 2: Input: nums = [1;2;1;3;5;6;4] Output: 5 Explanation: Your function can return either index number 1 where the peak element is 2; or index number 5 where the peak element is 6. Constraints: 1 <= nums.length <= 1000 -231 <= nums[i] <= 231 - 1 nums[i] != nums[i + 1] for all valid i.457Google,215,Kth Largest Element in an Array,Med,"Array, Divide and Conquer, Sorting, Heap (Priority Queue), Quickselect",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. Can you solve it without sorting? Example 1: Input: nums = [3;2;1;5;6;4]; k = 2 Output: 5 Example 2: Input: nums = [3;2;3;1;2;4;5;5;6]; k = 4 Output: 4 Constraints: 1 <= k <= nums.length <= 105 -104 <= nums[i] <= 104458Google,231,Power of Two,Easy,"Math, Bit Manipulation, Recursion",Given an integer n; return true if it is a power of two. Otherwise; return false. An integer n is a power of two; if there exists an integer x such that n == 2x. Example 1: Input: n = 1 Output: true Explanation: 20 = 1 Example 2: Input: n = 16 Output: true Explanation: 24 = 16 Example 3: Input: n = 3 Output: false Constraints: -231 <= n <= 231 - 1 Follow up: Could you solve it without loops/recursion?459Google,238,Product of Array Except Self,Med,"Array, Prefix Sum",Given an integer array nums; return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation. Example 1: Input: nums = [1;2;3;4] Output: [24;12;8;6] Example 2: Input: nums = [-1;1;0;-3;3] Output: [0;0;9;0;0] Constraints: 2 <= nums.length <= 105 -30 <= nums[i] <= 30 The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)460Google,349,Intersection of Two Arrays,Easy,"Array, Hash Table, Two Pointers, Binary Search, Sorting",Given two integer arrays nums1 and nums2; return an array of their intersection. Each element in the result must be unique and you may return the result in any order. Example 1: Input: nums1 = [1;2;2;1]; nums2 = [2;2] Output: [2] Example 2: Input: nums1 = [4;9;5]; nums2 = [9;4;9;8;4] Output: [9;4] Explanation: [4;9] is also accepted. Constraints: 1 <= nums1.length; nums2.length <= 1000 0 <= nums1[i]; nums2[i] <= 1000461Google,595,Big Countries,Easy,Database,Table: World +-------------+---------+ | Column Name | Type | +-------------+---------+ | name | varchar | | continent | varchar | | area | int | | population | int | | gdp | bigint | +-------------+---------+ name is the primary key (column with unique values) for this table. Each row of this table gives information about the name of a country; the continent to which it belongs; its area; the population; and its GDP value. A country is big if: it has an area of at least three million (i.e.; 3000000 km2); or it has a population of at least twenty-five million (i.e.; 25000000). Write a solution to find the name; population; and area of the big countries. Return the result table in any order. The result format is in the following example. Example 1: Input: World table: +-------------+-----------+---------+------------+--------------+ | name | continent | area | population | gdp | +-------------+-----------+---------+------------+--------------+ | Afghanistan | Asia | 652230 | 25500100 | 20343000000 | | Albania | Europe | 28748 | 2831741 | 12960000000 | | Algeria | Africa | 2381741 | 37100000 | 188681000000 | | Andorra | Europe | 468 | 78115 | 3712000000 | | Angola | Africa | 1246700 | 20609294 | 100990000000 | +-------------+-----------+---------+------------+--------------+ Output: +-------------+------------+---------+ | name | population | area | +-------------+------------+---------+ | Afghanistan | 25500100 | 652230 | | Algeria | 37100000 | 2381741 | +-------------+------------+---------+462Google,670,Maximum Swap,Med,"Math, Greedy",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. Example 1: Input: num = 2736 Output: 7236 Explanation: Swap the number 2 and the number 7. Example 2: Input: num = 9973 Output: 9973 Explanation: No swap. Constraints: 0 <= num <= 108463Google,715,Range Module,Hard,"Design, Segment Tree, Ordered Set","A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them. A half-open interval [left; right) denotes all the real numbers x where left <= x < right. Implement the RangeModule class: RangeModule() Initializes the object of the data structure. void addRange(int left; int right) Adds the half-open interval [left; right); tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval [left; right) that are not already tracked. boolean queryRange(int left; int right) Returns true if every real number in the interval [left; right) is currently being tracked; and false otherwise. void removeRange(int left; int right) Stops tracking every real number currently being tracked in the half-open interval [left; right). Example 1: Input [""RangeModule""; ""addRange""; ""removeRange""; ""queryRange""; ""queryRange""; ""queryRange""] [[]; [10; 20]; [14; 16]; [10; 14]; [13; 15]; [16; 17]] Output [null; null; null; true; false; true] Explanation RangeModule rangeModule = new RangeModule(); rangeModule.addRange(10; 20); rangeModule.removeRange(14; 16); rangeModule.queryRange(10; 14); // return True;(Every number in [10; 14) is being tracked) rangeModule.queryRange(13; 15); // return False;(Numbers like 14; 14.03; 14.17 in [13; 15) are not being tracked) rangeModule.queryRange(16; 17); // return True; (The number 16 in [16; 17) is still being tracked; despite the remove operation) Constraints: 1 <= left < right <= 109 At most 104 calls will be made to addRange; queryRange; and removeRange."464Google,962,Maximum Width Ramp,Med,"String, Dynamic Programming","A binary string is monotone increasing if it consists of some number of 0's (possibly none); followed by some number of 1's (also possibly none). You are given a binary string s. You can flip s[i] changing it from 0 to 1 or from 1 to 0. Return the minimum number of flips to make s monotone increasing. Example 1: Input: s = ""00110"" Output: 1 Explanation: We flip the last digit to get 00111. Example 2: Input: s = ""010110"" Output: 2 Explanation: We flip to get 011111; or alternatively 000111. Example 3: Input: s = ""00011000"" Output: 2 Explanation: We flip to get 00000000. Constraints: 1 <= s.length <= 105 s[i] is either '0' or '1'."465Google,1825,Finding MK Average,Hard,"Array, Dynamic Programming, Backtracking, Bit Manipulation, Bitmask",You are given an integer array jobs; where jobs[i] is the amount of time it takes to complete the ith job. There are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized. Return the minimum possible maximum working time of any assignment. Example 1: Input: jobs = [3;2;3]; k = 3 Output: 3 Explanation: By assigning each person one job; the maximum time is 3. Example 2: Input: jobs = [1;2;4;7;8]; k = 2 Output: 11 Explanation: Assign the jobs the following way: Worker 1: 1; 2; 8 (working time = 1 + 2 + 8 = 11) Worker 2: 4; 7 (working time = 4 + 7 = 11) The maximum working time is 11. Constraints: 1 <= k <= jobs.length <= 12 1 <= jobs[i] <= 107466Google,2877,Create a DataFrame from List,Easy,"String, Greedy, Enumeration","Given three strings a; b; and c; your task is to find a string that has the minimum length and contains all three strings as substrings. If there are multiple such strings; return the lexicographically smallest one. Return a string denoting the answer to the problem. Notes A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ; string a has a letter that appears earlier in the alphabet than the corresponding letter in b. A substring is a contiguous sequence of characters within a string. Example 1: Input: a = ""abc""; b = ""bca""; c = ""aaa"" Output: ""aaabca"" Explanation: We show that ""aaabca"" contains all the given strings: a = ans[2...4]; b = ans[3..5]; c = ans[0..2]. It can be shown that the length of the resulting string would be at least 6 and ""aaabca"" is the lexicographically smallest one. Example 2: Input: a = ""ab""; b = ""ba""; c = ""aba"" Output: ""aba"" Explanation: We show that the string ""aba"" contains all the given strings: a = ans[0..1]; b = ans[1..2]; c = ans[0..2]. Since the length of c is 3; the length of the resulting string would be at least 3. It can be shown that ""aba"" is the lexicographically smallest one. Constraints: 1 <= a.length; b.length; c.length <= 100 a; b; c consist only of lowercase English letters."467Google,6,Zigzag Conversion,Med,String,"The string ""PAYPALISHIRING"" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: ""PAHNAPLSIIGYIR"" Write the code that will take a string and make this conversion given a number of rows: string convert(string s; int numRows); Example 1: Input: s = ""PAYPALISHIRING""; numRows = 3 Output: ""PAHNAPLSIIGYIR"" Example 2: Input: s = ""PAYPALISHIRING""; numRows = 4 Output: ""PINALSIGYAHRPI"" Explanation: P I N A L S I G Y A H R P I Example 3: Input: s = ""A""; numRows = 1 Output: ""A"" Constraints: 1 <= s.length <= 1000 s consists of English letters (lower-case and upper-case); ';' and '.'. 1 <= numRows <= 1000"468Google,17,Letter Combinations of a Phone Number,Med,"Hash Table, String, Backtracking","Given a string containing digits from 2-9 inclusive; return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. Example 1: Input: digits = ""23"" Output: [""ad"";""ae"";""af"";""bd"";""be"";""bf"";""cd"";""ce"";""cf""] Example 2: Input: digits = """" Output: [] Example 3: Input: digits = ""2"" Output: [""a"";""b"";""c""] Constraints: 0 <= digits.length <= 4 digits[i] is a digit in the range ['2'; '9']."469Google,23,Merge k Sorted Lists,Hard,"Linked List, Divide and Conquer, Heap (Priority Queue), Merge Sort",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. Example 1: 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 Example 2: Input: lists = [] Output: [] Example 3: Input: lists = [[]] Output: [] Constraints: k == lists.length 0 <= k <= 104 0 <= lists[i].length <= 500 -104 <= lists[i][j] <= 104 lists[i] is sorted in ascending order. The sum of lists[i].length will not exceed 104.470Google,33,Search in Rotated Sorted Array,Med,"Array, Binary Search",There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function; nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k]; nums[k+1]; ...; nums[n-1]; nums[0]; nums[1]; ...; nums[k-1]] (0-indexed). For example; [0;1;2;4;5;6;7] might be rotated at pivot index 3 and become [4;5;6;7;0;1;2]. Given the array nums after the possible rotation and an integer target; return the index of target if it is in nums; or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [4;5;6;7;0;1;2]; target = 0 Output: 4 Example 2: Input: nums = [4;5;6;7;0;1;2]; target = 3 Output: -1 Example 3: Input: nums = [1]; target = 0 Output: -1 Constraints: 1 <= nums.length <= 5000 -104 <= nums[i] <= 104 All values of nums are unique. nums is an ascending array that is possibly rotated. -104 <= target <= 104471Google,35,Search Insert Position,Easy,"Array, Binary Search",Given a sorted array of distinct integers and a target value; return the index if the target is found. If not; return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [1;3;5;6]; target = 5 Output: 2 Example 2: Input: nums = [1;3;5;6]; target = 2 Output: 1 Example 3: Input: nums = [1;3;5;6]; target = 7 Output: 4 Constraints: 1 <= nums.length <= 104 -104 <= nums[i] <= 104 nums contains distinct values sorted in ascending order. -104 <= target <= 104472Google,37,Sudoku Solver,Hard,"Array, Hash Table, Backtracking, Matrix","Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: Each of the digits 1-9 must occur exactly once in each row. Each of the digits 1-9 must occur exactly once in each column. Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. The '.' character indicates empty cells. Example 1: Input: board = [[""5"";""3"";""."";""."";""7"";""."";""."";""."";"".""];[""6"";""."";""."";""1"";""9"";""5"";""."";""."";"".""];[""."";""9"";""8"";""."";""."";""."";""."";""6"";"".""];[""8"";""."";""."";""."";""6"";""."";""."";""."";""3""];[""4"";""."";""."";""8"";""."";""3"";""."";""."";""1""];[""7"";""."";""."";""."";""2"";""."";""."";""."";""6""];[""."";""6"";""."";""."";""."";""."";""2"";""8"";"".""];[""."";""."";""."";""4"";""1"";""9"";""."";""."";""5""];[""."";""."";""."";""."";""8"";""."";""."";""7"";""9""]] Output: [[""5"";""3"";""4"";""6"";""7"";""8"";""9"";""1"";""2""];[""6"";""7"";""2"";""1"";""9"";""5"";""3"";""4"";""8""];[""1"";""9"";""8"";""3"";""4"";""2"";""5"";""6"";""7""];[""8"";""5"";""9"";""7"";""6"";""1"";""4"";""2"";""3""];[""4"";""2"";""6"";""8"";""5"";""3"";""7"";""9"";""1""];[""7"";""1"";""3"";""9"";""2"";""4"";""8"";""5"";""6""];[""9"";""6"";""1"";""5"";""3"";""7"";""2"";""8"";""4""];[""2"";""8"";""7"";""4"";""1"";""9"";""6"";""3"";""5""];[""3"";""4"";""5"";""2"";""8"";""6"";""1"";""7"";""9""]] Explanation: The input board is shown above and the only valid solution is shown below: Constraints: board.length == 9 board[i].length == 9 board[i][j] is a digit or '.'. It is guaranteed that the input board has only one solution."473Google,45,Jump Game II,Med,"Array, Dynamic Programming, Greedy",You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0]. Each element nums[i] represents the maximum length of a forward jump from index i. In other words; if you are at nums[i]; you can jump to any nums[i + j] where: 0 <= j <= nums[i] and i + j < n Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1]. Example 1: 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. Example 2: Input: nums = [2;3;0;1;4] Output: 2 Constraints: 1 <= nums.length <= 104 0 <= nums[i] <= 1000 It's guaranteed that you can reach nums[n - 1].474Google,198,House Robber,Med,"Array, Dynamic Programming",You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed; the only constraint stopping you from robbing each of them is that adjacent houses have security systems 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. Example 1: 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. Example 2: Input: nums = [2;7;9;3;1] Output: 12 Explanation: Rob house 1 (money = 2); rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 400475Google,205,Isomorphic Strings,Easy,"Hash Table, String","Given two strings s and t; determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character; but a character may map to itself. Example 1: Input: s = ""egg""; t = ""add"" Output: true Explanation: The strings s and t can be made identical by: Mapping 'e' to 'a'. Mapping 'g' to 'd'. Example 2: Input: s = ""foo""; t = ""bar"" Output: false Explanation: The strings s and t can not be made identical as 'o' needs to be mapped to both 'a' and 'r'. Example 3: Input: s = ""paper""; t = ""title"" Output: true Constraints: 1 <= s.length <= 5 * 104 t.length == s.length s and t consist of any valid ascii character."476Google,295,Find Median from Data Stream,Hard,"Two Pointers, Design, Sorting, Heap (Priority Queue), 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. Example 1: 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 Constraints: -105 <= num <= 105 There will be at least one element in the data structure before calling findMedian. At most 5 * 104 calls will be made to addNum and findMedian. Follow up: If all integer numbers from the stream are in the range [0; 100]; how would you optimize your solution? If 99% of all integer numbers from the stream are in the range [0; 100]; how would you optimize your solution?"477Google,354,Russian Doll Envelopes,Hard,"Array, Binary Search, Dynamic Programming, Sorting",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. Example 1: 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]). Example 2: Input: envelopes = [[1;1];[1;1];[1;1]] Output: 1 Constraints: 1 <= envelopes.length <= 105 envelopes[i].length == 2 1 <= wi; hi <= 105478Google,410,Split Array Largest Sum,Hard,"Array, Binary Search, Dynamic Programming, Greedy, Prefix Sum",Given an integer array nums and an integer k; split nums into k non-empty subarrays such that the largest sum of any subarray is minimized. Return the minimized largest sum of the split. A subarray is a contiguous part of the array. Example 1: Input: nums = [7;2;5;10;8]; k = 2 Output: 18 Explanation: There are four ways to split nums into two subarrays. The best way is to split it into [7;2;5] and [10;8]; where the largest sum among the two subarrays is only 18. Example 2: Input: nums = [1;2;3;4;5]; k = 2 Output: 9 Explanation: There are four ways to split nums into two subarrays. The best way is to split it into [1;2;3] and [4;5]; where the largest sum among the two subarrays is only 9. Constraints: 1 <= nums.length <= 1000 0 <= nums[i] <= 106 1 <= k <= min(50; nums.length)479Google,796,Rotate String,Easy,Math,Given four integers sx; sy; tx; and ty; return true if it is possible to convert the point (sx; sy) to the point (tx; ty) through some operations; or false otherwise. The allowed operation on some point (x; y) is to convert it to either (x; x + y) or (x + y; y). Example 1: Input: sx = 1; sy = 1; tx = 3; ty = 5 Output: true Explanation: One series of moves that transforms the starting point to the target is: (1; 1) -> (1; 2) (1; 2) -> (3; 2) (3; 2) -> (3; 5) Example 2: Input: sx = 1; sy = 1; tx = 2; ty = 2 Output: false Example 3: Input: sx = 1; sy = 1; tx = 1; ty = 1 Output: true Constraints: 1 <= sx; sy; tx; ty <= 109480Google,843,Guess the Word,Hard,"Array, Hash Table, Dynamic Programming, Sorting",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. Example 1: Input: arr = [2;4] Output: 3 Explanation: We can make these trees: [2]; [4]; [4; 2; 2] Example 2: 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]. Constraints: 1 <= arr.length <= 1000 2 <= arr[i] <= 109 All the values of arr are unique.481Google,852,Peak Index in a Mountain Array,Med,"Array, Two Pointers, Binary Search, Sorting",There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the ith person. A Person x will not send a friend request to a person y (x != y) if any of the following conditions is true: age[y] <= 0.5 * age[x] + 7 age[y] > age[x] age[y] > 100 && age[x] < 100 Otherwise; x will send a friend request to y. Note that if x sends a request to y; y will not necessarily send a request to x. Also; a person will not send a friend request to themself. Return the total number of friend requests made. Example 1: Input: ages = [16;16] Output: 2 Explanation: 2 people friend request each other. Example 2: Input: ages = [16;17;18] Output: 2 Explanation: Friend requests are made 17 -> 16; 18 -> 17. Example 3: Input: ages = [20;30;100;110;120] Output: 3 Explanation: Friend requests are made 110 -> 100; 120 -> 110; 120 -> 100. Constraints: n == ages.length 1 <= n <= 2 * 104 1 <= ages[i] <= 120482Google,1110,Delete Nodes And Return Forest,Med,,483Google,18,4Sum,Med,"Array, Two Pointers, Sorting",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. Example 1: Input: nums = [1;0;-1;0;-2;2]; target = 0 Output: [[-2;-1;1;2];[-2;0;0;2];[-1;0;0;1]] Example 2: Input: nums = [2;2;2;2;2]; target = 8 Output: [[2;2;2;2]] Constraints: 1 <= nums.length <= 200 -109 <= nums[i] <= 109 -109 <= target <= 109484Google,22,Generate Parentheses,Med,"String, Dynamic Programming, Backtracking","Given n pairs of parentheses; write a function to generate all combinations of well-formed parentheses. Example 1: Input: n = 3 Output: [""((()))"";""(()())"";""(())()"";""()(())"";""()()()""] Example 2: Input: n = 1 Output: [""()""] Constraints: 1 <= n <= 8"485Google,41,First Missing Positive,Hard,"Array, Hash Table",Given an unsorted integer array nums. Return the smallest positive integer that is not present in nums. You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space. Example 1: Input: nums = [1;2;0] Output: 3 Explanation: The numbers in the range [1;2] are all in the array. Example 2: Input: nums = [3;4;-1;1] Output: 2 Explanation: 1 is in the array but 2 is missing. Example 3: Input: nums = [7;8;9;11;12] Output: 1 Explanation: The smallest positive integer 1 is missing. Constraints: 1 <= nums.length <= 105 -231 <= nums[i] <= 231 - 1486Google,54,Spiral Matrix,Med,"Array, Matrix, Simulation",Given an m x n matrix; return all elements of the matrix in spiral order. Example 1: Input: matrix = [[1;2;3];[4;5;6];[7;8;9]] Output: [1;2;3;6;9;8;7;4;5] Example 2: Input: matrix = [[1;2;3;4];[5;6;7;8];[9;10;11;12]] Output: [1;2;3;4;8;12;11;10;9;5;6;7] Constraints: m == matrix.length n == matrix[i].length 1 <= m; n <= 10 -100 <= matrix[i][j] <= 100487Google,61,Rotate List,Med,"Linked List, Two Pointers",Given the head of a linked list; rotate the list to the right by k places. Example 1: Input: head = [1;2;3;4;5]; k = 2 Output: [4;5;1;2;3] Example 2: Input: head = [0;1;2]; k = 4 Output: [2;0;1] Constraints: The number of nodes in the list is in the range [0; 500]. -100 <= Node.val <= 100 0 <= k <= 2 * 109488Google,189,Rotate Array,Med,"Array, Math, Two Pointers",Given an integer array nums; rotate the array to the right by k steps; where k is non-negative. Example 1: 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] Example 2: Input: nums = [-1;-100;3;99]; k = 2 Output: [3;99;-1;-100] Explanation: rotate 1 steps to the right: [99;-1;-100;3] rotate 2 steps to the right: [3;99;-1;-100] Constraints: 1 <= nums.length <= 105 -231 <= nums[i] <= 231 - 1 0 <= k <= 105 Follow up: Try to come up with as many solutions as you can. There are at least three different ways to solve this problem. Could you do it in-place with O(1) extra space?489Google,249,Group Shifted Strings,Med,"Array, Hash Table, String",490Google,347,Top K Frequent Elements,Med,"Array, Hash Table, Divide and Conquer, Sorting, Heap (Priority Queue), Bucket Sort, Counting, Quickselect",Given an integer array nums and an integer k; return the k most frequent elements. You may return the answer in any order. Example 1: Input: nums = [1;1;1;2;2;3]; k = 2 Output: [1;2] Example 2: Input: nums = [1]; k = 1 Output: [1] Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 k is in the range [1; the number of unique elements in the array]. It is guaranteed that the answer is unique. Follow up: Your algorithm's time complexity must be better than O(n log n); where n is the array's size.491Google,380,Insert Delete GetRandom O(1),Med,"Array, Hash Table, Math, Design, Randomized","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. Example 1: Input [""RandomizedSet""; ""insert""; ""remove""; ""insert""; ""getRandom""; ""remove""; ""insert""; ""getRandom""] [[]; [1]; [2]; [2]; []; [1]; [2]; []] Output [null; true; false; true; 2; true; false; 2] Explanation RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set; returns true. Set now contains [1;2]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set; returns true. Set now contains [2]. randomizedSet.insert(2); // 2 was already in the set; so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set; getRandom() will always return 2. Constraints: -231 <= val <= 231 - 1 At most 2 * 105 calls will be made to insert; remove; and getRandom. There will be at least one element in the data structure when getRandom is called."492Google,424,Longest Repeating Character Replacement,Med,"Hash Table, String, Sliding Window","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. Example 1: Input: s = ""ABAB""; k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa. Example 2: Input: s = ""AABABBA""; k = 1 Output: 4 Explanation: Replace the one 'A' in the middle with 'B' and form ""AABBBBA"". The substring ""BBBB"" has the longest repeating letters; which is 4. There may exists other ways to achieve this answer too. Constraints: 1 <= s.length <= 105 s consists of only uppercase English letters. 0 <= k <= s.length"493Google,432,All O`one Data Structure,Hard,"Hash Table, Linked List, Design, Doubly-Linked List","Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts. Implement the AllOne class: AllOne() Initializes the object of the data structure. inc(String key) Increments the count of the string key by 1. If key does not exist in the data structure; insert it with count 1. dec(String key) Decrements the count of the string key by 1. If the count of key is 0 after the decrement; remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement. getMaxKey() Returns one of the keys with the maximal count. If no element exists; return an empty string """". getMinKey() Returns one of the keys with the minimum count. If no element exists; return an empty string """". Note that each function must run in O(1) average time complexity. Example 1: Input [""AllOne""; ""inc""; ""inc""; ""getMaxKey""; ""getMinKey""; ""inc""; ""getMaxKey""; ""getMinKey""] [[]; [""hello""]; [""hello""]; []; []; [""leet""]; []; []] Output [null; null; null; ""hello""; ""hello""; null; ""hello""; ""leet""] Explanation AllOne allOne = new AllOne(); allOne.inc(""hello""); allOne.inc(""hello""); allOne.getMaxKey(); // return ""hello"" allOne.getMinKey(); // return ""hello"" allOne.inc(""leet""); allOne.getMaxKey(); // return ""hello"" allOne.getMinKey(); // return ""leet"" Constraints: 1 <= key.length <= 10 key consists of lowercase English letters. It is guaranteed that for each call to dec; key is existing in the data structure. At most 5 * 104 calls will be made to inc; dec; getMaxKey; and getMinKey."494Google,496,Next Greater Element I,Easy,"Array, Hash Table, Stack, Monotonic Stack",The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2; where nums1 is a subset of nums2. For each 0 <= i < nums1.length; find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element; then the answer for this query is -1. Return an array ans of length nums1.length such that ans[i] is the next greater element as described above. Example 1: Input: nums1 = [4;1;2]; nums2 = [1;3;4;2] Output: [-1;3;-1] Explanation: The next greater element for each value of nums1 is as follows: - 4 is underlined in nums2 = [1;3;4;2]. There is no next greater element; so the answer is -1. - 1 is underlined in nums2 = [1;3;4;2]. The next greater element is 3. - 2 is underlined in nums2 = [1;3;4;2]. There is no next greater element; so the answer is -1. Example 2: Input: nums1 = [2;4]; nums2 = [1;2;3;4] Output: [3;-1] Explanation: The next greater element for each value of nums1 is as follows: - 2 is underlined in nums2 = [1;2;3;4]. The next greater element is 3. - 4 is underlined in nums2 = [1;2;3;4]. There is no next greater element; so the answer is -1. Constraints: 1 <= nums1.length <= nums2.length <= 1000 0 <= nums1[i]; nums2[i] <= 104 All integers in nums1 and nums2 are unique. All the integers of nums1 also appear in nums2. Follow up: Could you find an O(nums1.length + nums2.length) solution?495Google,525,Contiguous Array,Med,"Array, Hash Table, Prefix Sum",Given a binary array nums; return the maximum length of a contiguous subarray with an equal number of 0 and 1. Example 1: Input: nums = [0;1] Output: 2 Explanation: [0; 1] is the longest contiguous subarray with an equal number of 0 and 1. Example 2: Input: nums = [0;1;0] Output: 2 Explanation: [0; 1] (or [1; 0]) is a longest contiguous subarray with equal number of 0 and 1. Constraints: 1 <= nums.length <= 105 nums[i] is either 0 or 1.496Google,539,Minimum Time Difference,Med,"Array, Math, String, Sorting","Given a list of 24-hour clock time points in ""HH:MM"" format; return the minimum minutes difference between any two time-points in the list. Example 1: Input: timePoints = [""23:59"";""00:00""] Output: 1 Example 2: Input: timePoints = [""00:00"";""23:59"";""00:00""] Output: 0 Constraints: 2 <= timePoints.length <= 2 * 104 timePoints[i] is in the format ""HH:MM""."497Google,632,Smallest Range Covering Elements from K Lists,Hard,"Array, Hash Table, Greedy, Sliding Window, Sorting, Heap (Priority Queue)",You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists. We define the range [a; b] is smaller than range [c; d] if b - a < d - c or a < c if b - a == d - c. Example 1: Input: nums = [[4;10;15;24;26];[0;9;12;20];[5;18;22;30]] Output: [20;24] Explanation: List 1: [4; 10; 15; 24;26]; 24 is in range [20;24]. List 2: [0; 9; 12; 20]; 20 is in range [20;24]. List 3: [5; 18; 22; 30]; 22 is in range [20;24]. Example 2: Input: nums = [[1;2;3];[1;2;3];[1;2;3]] Output: [1;1] Constraints: nums.length == k 1 <= k <= 3500 1 <= nums[i].length <= 50 -105 <= nums[i][j] <= 105 nums[i] is sorted in non-decreasing order.498Google,695,Max Area of Island,Med,"Array, Depth-First Search, Breadth-First Search, Union Find, Matrix",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. Example 1: Input: grid = [[0;0;1;0;0;0;0;1;0;0;0;0;0];[0;0;0;0;0;0;0;1;1;1;0;0;0];[0;1;1;0;1;0;0;0;0;0;0;0;0];[0;1;0;0;1;1;0;0;1;0;1;0;0];[0;1;0;0;1;1;0;0;1;1;1;0;0];[0;0;0;0;0;0;0;0;0;0;1;0;0];[0;0;0;0;0;0;0;1;1;1;0;0;0];[0;0;0;0;0;0;0;1;1;0;0;0;0]] Output: 6 Explanation: The answer is not 11; because the island must be connected 4-directionally. Example 2: Input: grid = [[0;0;0;0;0;0;0;0]] Output: 0 Constraints: m == grid.length n == grid[i].length 1 <= m; n <= 50 grid[i][j] is either 0 or 1.499Google,704,Binary Search,Easy,,500Google,818,Race Car,Hard,"Math, String, Enumeration",501Google,528,Random Pick with Weight,Med,"Linked List, Two Pointers",You are given the head of a linked list; and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). Example 1: Input: head = [1;2;3;4;5]; k = 2 Output: [1;4;3;2;5] Example 2: Input: head = [7;9;6;6;7;8;3;0;9;5]; k = 5 Output: [7;9;6;6;8;7;3;0;9;5] Constraints: The number of nodes in the list is n. 1 <= k <= n <= 105 0 <= Node.val <= 100502Google,1011,Capacity To Ship Packages Within D Days,Med,"Tree, Depth-First Search, Binary Tree",You are given the root of a binary tree with n nodes; where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage; which is the desired pre-order traversal of the binary tree. Any node in the binary tree can be flipped by swapping its left and right subtrees. For example; flipping node 1 will have the following effect: Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage. Return a list of the values of all flipped nodes. You may return the answer in any order. If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage; return the list [-1]. Example 1: Input: root = [1;2]; voyage = [2;1] Output: [-1] Explanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage. Example 2: Input: root = [1;2;3]; voyage = [1;3;2] Output: [1] Explanation: Flipping node 1 swaps nodes 2 and 3; so the pre-order traversal matches voyage. Example 3: Input: root = [1;2;3]; voyage = [1;2;3] Output: [] Explanation: The tree's pre-order traversal already matches voyage; so no nodes need to be flipped. Constraints: The number of nodes in the tree is n. n == voyage.length 1 <= n <= 100 1 <= Node.val; voyage[i] <= n All the values in the tree are unique. All the values in voyage are unique.503Google,1497,Check If Array Pairs Are Divisible by k,Med,"Array, Stack, Design","Design a stack that supports increment operations on its elements. Implement the CustomStack class: CustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack. void push(int x) Adds x to the top of the stack if the stack has not reached the maxSize. int pop() Pops and returns the top of the stack or -1 if the stack is empty. void inc(int k; int val) Increments the bottom k elements of the stack by val. If there are less than k elements in the stack; increment all the elements in the stack. Example 1: Input [""CustomStack"";""push"";""push"";""pop"";""push"";""push"";""push"";""increment"";""increment"";""pop"";""pop"";""pop"";""pop""] [[3];[1];[2];[];[2];[3];[4];[5;100];[2;100];[];[];[];[]] Output [null;null;null;2;null;null;null;null;null;103;202;201;-1] Explanation CustomStack stk = new CustomStack(3); // Stack is Empty [] stk.push(1); // stack becomes [1] stk.push(2); // stack becomes [1; 2] stk.pop(); // return 2 --> Return top of the stack 2; stack becomes [1] stk.push(2); // stack becomes [1; 2] stk.push(3); // stack becomes [1; 2; 3] stk.push(4); // stack still [1; 2; 3]; Do not add another elements as size is 4 stk.increment(5; 100); // stack becomes [101; 102; 103] stk.increment(2; 100); // stack becomes [201; 202; 103] stk.pop(); // return 103 --> Return top of the stack 103; stack becomes [201; 202] stk.pop(); // return 202 --> Return top of the stack 202; stack becomes [201] stk.pop(); // return 201 --> Return top of the stack 201; stack becomes [] stk.pop(); // return -1 --> Stack is empty return -1. Constraints: 1 <= maxSize; x; k <= 1000 0 <= val <= 100 At most 1000 calls will be made to each method of increment; push and pop each separately."504Google,3287,Find the Maximum Sequence Value of Array,Hard,Database,505Google,16,3Sum Closest,Med,"Array, Two Pointers, Sorting",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. Example 1: 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). Example 2: Input: nums = [0;0;0]; target = 1 Output: 0 Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0). Constraints: 3 <= nums.length <= 500 -1000 <= nums[i] <= 1000 -104 <= target <= 104506Google,21,Merge Two Sorted Lists,Easy,"Linked List, Recursion",You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list. Example 1: Input: list1 = [1;2;4]; list2 = [1;3;4] Output: [1;1;2;3;4;4] Example 2: Input: list1 = []; list2 = [] Output: [] Example 3: Input: list1 = []; list2 = [0] Output: [0] Constraints: The number of nodes in both lists is in the range [0; 50]. -100 <= Node.val <= 100 Both list1 and list2 are sorted in non-decreasing order.507Google,31,Next Permutation,Med,"Array, Two Pointers",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 all the permutations of arr: [1;2;3]; [1;3;2]; [2; 1; 3]; [2; 3; 1]; [3;1;2]; [3;2;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. The replacement must be in place and use only constant extra memory. Example 1: Input: nums = [1;2;3] Output: [1;3;2] Example 2: Input: nums = [3;2;1] Output: [1;2;3] Example 3: Input: nums = [1;1;5] Output: [1;5;1] Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 100508Google,34,Find First and Last Position of Element in Sorted Array,Med,"Array, Binary Search",Given an array of integers nums sorted in non-decreasing order; find the starting and ending position of a given target value. If target is not found in the array; return [-1; -1]. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [5;7;7;8;8;10]; target = 8 Output: [3;4] Example 2: Input: nums = [5;7;7;8;8;10]; target = 6 Output: [-1;-1] Example 3: Input: nums = []; target = 0 Output: [-1;-1] Constraints: 0 <= nums.length <= 105 -109 <= nums[i] <= 109 nums is a non-decreasing array. -109 <= target <= 109509Google,39,Combination Sum,Med,"Array, Backtracking",Given an array of distinct integers candidates and a target integer target; return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input. Example 1: Input: candidates = [2;3;6;7]; target = 7 Output: [[2;2;3];[7]] Explanation: 2 and 3 are candidates; and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate; and 7 = 7. These are the only two combinations. Example 2: Input: candidates = [2;3;5]; target = 8 Output: [[2;2;2;2];[2;3;3];[3;5]] Example 3: Input: candidates = [2]; target = 1 Output: [] Constraints: 1 <= candidates.length <= 30 2 <= candidates[i] <= 40 All elements of candidates are distinct. 1 <= target <= 40510Google,48,Rotate Image,Med,"Array, Math, Matrix",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. Example 1: Input: matrix = [[1;2;3];[4;5;6];[7;8;9]] Output: [[7;4;1];[8;5;2];[9;6;3]] Example 2: Input: matrix = [[5;1;9;11];[2;4;8;10];[13;3;6;7];[15;14;12;16]] Output: [[15;13;2;5];[14;3;4;1];[12;6;8;9];[16;7;10;11]] Constraints: n == matrix.length == matrix[i].length 1 <= n <= 20 -1000 <= matrix[i][j] <= 1000511Google,57,Insert Interval,Med,Array,You are given an array of non-overlapping intervals intervals where intervals[i] = [starti; endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start; end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion. Note that you don't need to modify intervals in-place. You can make a new array and return it. Example 1: Input: intervals = [[1;3];[6;9]]; newInterval = [2;5] Output: [[1;5];[6;9]] Example 2: Input: intervals = [[1;2];[3;5];[6;7];[8;10];[12;16]]; newInterval = [4;8] Output: [[1;2];[3;10];[12;16]] Explanation: Because the new interval [4;8] overlaps with [3;5];[6;7];[8;10]. Constraints: 0 <= intervals.length <= 104 intervals[i].length == 2 0 <= starti <= endi <= 105 intervals is sorted by starti in ascending order. newInterval.length == 2 0 <= start <= end <= 105512Google,66,Plus One,Easy,"Array, Math",You are given a large integer represented as an integer array digits; where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. Increment the large integer by one and return the resulting array of digits. Example 1: Input: digits = [1;2;3] Output: [1;2;4] Explanation: The array represents the integer 123. Incrementing by one gives 123 + 1 = 124. Thus; the result should be [1;2;4]. Example 2: Input: digits = [4;3;2;1] Output: [4;3;2;2] Explanation: The array represents the integer 4321. Incrementing by one gives 4321 + 1 = 4322. Thus; the result should be [4;3;2;2]. Example 3: Input: digits = [9] Output: [1;0] Explanation: The array represents the integer 9. Incrementing by one gives 9 + 1 = 10. Thus; the result should be [1;0]. Constraints: 1 <= digits.length <= 100 0 <= digits[i] <= 9 digits does not contain any leading 0's.513Google,72,Edit Distance,Med,"String, Dynamic Programming","Given two strings word1 and word2; return the minimum number of operations required to convert word1 to word2. You have the following three operations permitted on a word: Insert a character Delete a character Replace a character Example 1: Input: word1 = ""horse""; word2 = ""ros"" Output: 3 Explanation: horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') Example 2: Input: word1 = ""intention""; word2 = ""execution"" Output: 5 Explanation: intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') Constraints: 0 <= word1.length; word2.length <= 500 word1 and word2 consist of lowercase English letters."514Google,100,Same Tree,Easy,"Tree, Depth-First Search, Breadth-First Search, Binary Tree",Given the roots of two binary trees p and q; write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical; and the nodes have the same value. Example 1: Input: p = [1;2;3]; q = [1;2;3] Output: true Example 2: Input: p = [1;2]; q = [1;null;2] Output: false Example 3: Input: p = [1;2;1]; q = [1;1;2] Output: false Constraints: The number of nodes in both trees is in the range [0; 100]. -104 <= Node.val <= 104515Google,101,Symmetric Tree,Easy,"Tree, Depth-First Search, Breadth-First Search, Binary Tree",Given the root of a binary tree; check whether it is a mirror of itself (i.e.; symmetric around its center). Example 1: Input: root = [1;2;2;3;4;4;3] Output: true Example 2: Input: root = [1;2;2;null;3;null;3] Output: false Constraints: The number of nodes in the tree is in the range [1; 1000]. -100 <= Node.val <= 100 Follow up: Could you solve it both recursively and iteratively?516Google,122,Best Time to Buy and Sell Stock II,Med,"Array, Dynamic Programming, Greedy",You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day; you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However; you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve. Example 1: Input: prices = [7;1;5;3;6;4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5); profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6); profit = 6-3 = 3. Total profit is 4 + 3 = 7. Example 2: Input: prices = [1;2;3;4;5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5); profit = 5-1 = 4. Total profit is 4. Example 3: Input: prices = [7;6;4;3;1] Output: 0 Explanation: There is no way to make a positive profit; so we never buy the stock to achieve the maximum profit of 0. Constraints: 1 <= prices.length <= 3 * 104 0 <= prices[i] <= 104517Google,124,Binary Tree Maximum Path Sum,Hard,"Dynamic Programming, Tree, Depth-First Search, Binary Tree",A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree; return the maximum path sum of any non-empty path. Example 1: Input: root = [1;2;3] Output: 6 Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. Example 2: Input: root = [-10;9;20;null;null;15;7] Output: 42 Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42. Constraints: The number of nodes in the tree is in the range [1; 3 * 104]. -1000 <= Node.val <= 1000518Google,125,Valid Palindrome,Easy,"Two Pointers, String","A phrase is a palindrome if; after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters; it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s; return true if it is a palindrome; or false otherwise. Example 1: Input: s = ""A man; a plan; a canal: Panama"" Output: true Explanation: ""amanaplanacanalpanama"" is a palindrome. Example 2: Input: s = ""race a car"" Output: false Explanation: ""raceacar"" is not a palindrome. Example 3: Input: s = "" "" Output: true Explanation: s is an empty string """" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward; it is a palindrome. Constraints: 1 <= s.length <= 2 * 105 s consists only of printable ASCII characters."519Google,141,Linked List Cycle,Easy,"Hash Table, Linked List, Two Pointers",Given head; the head of a linked list; determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally; pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter. Return true if there is a cycle in the linked list. Otherwise; return false. Example 1: Input: head = [3;2;0;-4]; pos = 1 Output: true Explanation: There is a cycle in the linked list; where the tail connects to the 1st node (0-indexed). Example 2: Input: head = [1;2]; pos = 0 Output: true Explanation: There is a cycle in the linked list; where the tail connects to the 0th node. Example 3: Input: head = [1]; pos = -1 Output: false Explanation: There is no cycle in the linked list. Constraints: The number of the nodes in the list is in the range [0; 104]. -105 <= Node.val <= 105 pos is -1 or a valid index in the linked-list. Follow up: Can you solve it using O(1) (i.e. constant) memory?520Google,150,Evaluate Reverse Polish Notation,Med,"Array, Math, Stack","You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation. Evaluate the expression. Return an integer that represents the value of the expression. Note that: The valid operators are '+'; '-'; '*'; and '/'. Each operand may be an integer or another expression. The division between two integers always truncates toward zero. There will not be any division by zero. The input represents a valid arithmetic expression in a reverse polish notation. The answer and all the intermediate calculations can be represented in a 32-bit integer. Example 1: Input: tokens = [""2"";""1"";""+"";""3"";""*""] Output: 9 Explanation: ((2 + 1) * 3) = 9 Example 2: Input: tokens = [""4"";""13"";""5"";""/"";""+""] Output: 6 Explanation: (4 + (13 / 5)) = 6 Example 3: Input: tokens = [""10"";""6"";""9"";""3"";""+"";""-11"";""*"";""/"";""*"";""17"";""+"";""5"";""+""] Output: 22 Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) + 17) + 5 = ((10 * (6 / -132)) + 17) + 5 = ((10 * 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22 Constraints: 1 <= tokens.length <= 104 tokens[i] is either an operator: ""+""; ""-""; ""*""; or ""/""; or an integer in the range [-200; 200]."521Google,152,Maximum Product Subarray,Med,"Array, Dynamic Programming",Given an integer array nums; find a subarray that has the largest product; and return the product. The test cases are generated so that the answer will fit in a 32-bit integer. Example 1: Input: nums = [2;3;-2;4] Output: 6 Explanation: [2;3] has the largest product 6. Example 2: Input: nums = [-2;0;-1] Output: 0 Explanation: The result cannot be 2; because [-2;-1] is not a subarray. Constraints: 1 <= nums.length <= 2 * 104 -10 <= nums[i] <= 10 The product of any subarray of nums is guaranteed to fit in a 32-bit integer.522Google,217,Contains Duplicate,Easy,"Array, Hash Table, Sorting",Given an integer array nums; return true if any value appears at least twice in the array; and return false if every element is distinct. Example 1: Input: nums = [1;2;3;1] Output: true Explanation: The element 1 occurs at the indices 0 and 3. Example 2: Input: nums = [1;2;3;4] Output: false Explanation: All elements are distinct. Example 3: Input: nums = [1;1;1;3;3;4;3;2;4;2] Output: true Constraints: 1 <= nums.length <= 105 -109 <= nums[i] <= 109523Google,221,Maximal Square,Med,"Array, Dynamic Programming, Matrix","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. Example 1: Input: matrix = [[""1"";""0"";""1"";""0"";""0""];[""1"";""0"";""1"";""1"";""1""];[""1"";""1"";""1"";""1"";""1""];[""1"";""0"";""0"";""1"";""0""]] Output: 4 Example 2: Input: matrix = [[""0"";""1""];[""1"";""0""]] Output: 1 Example 3: Input: matrix = [[""0""]] Output: 0 Constraints: m == matrix.length n == matrix[i].length 1 <= m; n <= 300 matrix[i][j] is '0' or '1'."524Google,225,Implement Stack using Queues,Easy,"Stack, Design, Queue","Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push; top; pop; and empty). Implement the MyStack class: void push(int x) Pushes element x to the top of the stack. int pop() Removes the element on the top of the stack and returns it. int top() Returns the element on the top of the stack. boolean empty() Returns true if the stack is empty; false otherwise. Notes: You must use only standard operations of a queue; which means that only push to back; peek/pop from front; size and is empty operations are valid. Depending on your language; the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations. Example 1: Input [""MyStack""; ""push""; ""push""; ""top""; ""pop""; ""empty""] [[]; [1]; [2]; []; []; []] Output [null; null; null; 2; 2; false] Explanation MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False Constraints: 1 <= x <= 9 At most 100 calls will be made to push; pop; top; and empty. All the calls to pop and top are valid. Follow-up: Can you implement the stack using only one queue?"525Google,278,First Bad Version,Easy,"Binary Search, Interactive",You are a product manager and currently leading a team to develop a new product. Unfortunately; the latest version of your product fails the quality check. Since each version is developed based on the previous version; all the versions after a bad version are also bad. Suppose you have n versions [1; 2; ...; n] and you want to find out the first bad one; which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. Example 1: Input: n = 5; bad = 4 Output: 4 Explanation: call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version. Example 2: Input: n = 1; bad = 1 Output: 1 Constraints: 1 <= bad <= n <= 231 - 1526Google,386,Lexicographical Numbers,Med,"Depth-First Search, Trie",Given an integer n; return all the numbers in the range [1; n] sorted in lexicographical order. You must write an algorithm that runs in O(n) time and uses O(1) extra space. Example 1: Input: n = 13 Output: [1;10;11;12;13;2;3;4;5;6;7;8;9] Example 2: Input: n = 2 Output: [1;2] Constraints: 1 <= n <= 5 * 104527Google,416,Partition Equal Subset Sum,Med,"Array, Dynamic Programming",Given an integer array nums; return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise. Example 1: Input: nums = [1;5;11;5] Output: true Explanation: The array can be partitioned as [1; 5; 5] and [11]. Example 2: Input: nums = [1;2;3;5] Output: false Explanation: The array cannot be partitioned into equal sum subsets. Constraints: 1 <= nums.length <= 200 1 <= nums[i] <= 100528Google,560,Subarray Sum Equals K,Med,"Array, Hash Table, Prefix Sum",Given an array of integers nums and an integer k; return the total number of subarrays whose sum equals to k. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: nums = [1;1;1]; k = 2 Output: 2 Example 2: Input: nums = [1;2;3]; k = 3 Output: 2 Constraints: 1 <= nums.length <= 2 * 104 -1000 <= nums[i] <= 1000 -107 <= k <= 107529Google,862,Shortest Subarray with Sum at Least K,Hard,"Array, Hash Table, String, Sorting","You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays; indices; sources; and targets; all of length k. To complete the ith replacement operation: Check if the substring sources[i] occurs at index indices[i] in the original string s. If it does not occur; do nothing. Otherwise if it does occur; replace that substring with targets[i]. For example; if s = ""abcd""; indices[i] = 0; sources[i] = ""ab""; and targets[i] = ""eee""; then the result of this replacement will be ""eeecd"". All replacement operations must occur simultaneously; meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap. For example; a testcase with s = ""abc""; indices = [0; 1]; and sources = [""ab"";""bc""] will not be generated because the ""ab"" and ""bc"" replacements overlap. Return the resulting string after performing all replacement operations on s. A substring is a contiguous sequence of characters in a string. Example 1: Input: s = ""abcd""; indices = [0; 2]; sources = [""a""; ""cd""]; targets = [""eee""; ""ffff""] Output: ""eeebffff"" Explanation: ""a"" occurs at index 0 in s; so we replace it with ""eee"". ""cd"" occurs at index 2 in s; so we replace it with ""ffff"". Example 2: Input: s = ""abcd""; indices = [0; 2]; sources = [""ab"";""ec""]; targets = [""eee"";""ffff""] Output: ""eeecd"" Explanation: ""ab"" occurs at index 0 in s; so we replace it with ""eee"". ""ec"" does not occur at index 2 in s; so we do nothing. Constraints: 1 <= s.length <= 1000 k == indices.length == sources.length == targets.length 1 <= k <= 100 0 <= indexes[i] < s.length 1 <= sources[i].length; targets[i].length <= 50 s consists of only lowercase English letters. sources[i] and targets[i] consist of only lowercase English letters."530Google,975,Odd Even Jump,Hard,"Tree, Depth-First Search, Binary Search Tree, Binary Tree",Given the root node of a binary search tree and two integers low and high; return the sum of values of all nodes with a value in the inclusive range [low; high]. Example 1: Input: root = [10;5;15;3;7;null;18]; low = 7; high = 15 Output: 32 Explanation: Nodes 7; 10; and 15 are in the range [7; 15]. 7 + 10 + 15 = 32. Example 2: Input: root = [10;5;15;3;7;13;18;1;null;6]; low = 6; high = 10 Output: 23 Explanation: Nodes 6; 7; and 10 are in the range [6; 10]. 6 + 7 + 10 = 23. Constraints: The number of nodes in the tree is in the range [1; 2 * 104]. 1 <= Node.val <= 105 1 <= low <= high <= 105 All Node.val are unique.531Google,1071,Greatest Common Divisor of Strings,Easy,"Array, Bit Manipulation",You are given a binary array nums (0-indexed). We define xi as the number whose binary representation is the subarray nums[0..i] (from most-significant-bit to least-significant-bit). For example; if nums = [1;0;1]; then x0 = 1; x1 = 2; and x2 = 5. Return an array of booleans answer where answer[i] is true if xi is divisible by 5. Example 1: Input: nums = [0;1;1] Output: [true;false;false] Explanation: The input numbers in binary are 0; 01; 011; which are 0; 1; and 3 in base-10. Only the first number is divisible by 5; so answer[0] is true. Example 2: Input: nums = [1;1;1] Output: [false;false;false] Constraints: 1 <= nums.length <= 105 nums[i] is either 0 or 1.532Google,1331,Rank Transform of an Array,Easy,"Array, Backtracking, Matrix",In a gold mine grid of size m x n; each cell in this mine has an integer representing the amount of gold in that cell; 0 if it is empty. Return the maximum amount of gold you can collect under the conditions: Every time you are located in a cell you will collect all the gold in that cell. From your position; you can walk one step to the left; right; up; or down. You can't visit the same cell more than once. Never visit a cell with 0 gold. You can start and stop collecting gold from any position in the grid that has some gold. Example 1: Input: grid = [[0;6;0];[5;8;7];[0;9;0]] Output: 24 Explanation: [[0;6;0]; [5;8;7]; [0;9;0]] Path to get the maximum gold; 9 -> 8 -> 7. Example 2: Input: grid = [[1;0;7];[2;0;6];[3;4;5];[0;3;0];[9;0;20]] Output: 28 Explanation: [[1;0;7]; [2;0;6]; [3;4;5]; [0;3;0]; [9;0;20]] Path to get the maximum gold; 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. Constraints: m == grid.length n == grid[i].length 1 <= m; n <= 15 0 <= grid[i][j] <= 100 There are at most 25 cells containing gold.533Google,1405,Longest Happy String,Med,Database,534Google,1207,Unique Number of Occurrences,Easy,"Array, Hash Table, Tree, Depth-First Search, Binary Tree",Given the root of a binary tree; each node in the tree has a distinct value. After deleting all nodes with a value in to_delete; we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order. Example 1: Input: root = [1;2;3;4;5;6;7]; to_delete = [3;5] Output: [[1;2;null;4];[6];[7]] Example 2: Input: root = [1;2;4;null;3]; to_delete = [3] Output: [[1;2;4]] Constraints: The number of nodes in the given tree is at most 1000. Each node has a distinct value between 1 and 1000. to_delete.length <= 1000 to_delete contains distinct values between 1 and 1000.535Google,1963,Minimum Number of Swaps to Make the String Balanced,Med,"Array, Math, Bit Manipulation",The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element; then its XOR sum will be equal to this element. For example; the XOR sum of [1;2;3;4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4; and the XOR sum of [3] is equal to 3. You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers. Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i; j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length. Return the XOR sum of the aforementioned list. Example 1: Input: arr1 = [1;2;3]; arr2 = [6;5] Output: 0 Explanation: The list = [1 AND 6; 1 AND 5; 2 AND 6; 2 AND 5; 3 AND 6; 3 AND 5] = [0;1;2;0;2;1]. The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0. Example 2: Input: arr1 = [12]; arr2 = [4] Output: 4 Explanation: The list = [12 AND 4] = [4]. The XOR sum = 4. Constraints: 1 <= arr1.length; arr2.length <= 105 0 <= arr1[i]; arr2[j] <= 109536Google,2534,Time Taken to Cross the Door,Hard,Database,537Google,10,Regular Expression Matching,Hard,"String, Dynamic Programming, Recursion","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). Example 1: Input: s = ""aa""; p = ""a"" Output: false Explanation: ""a"" does not match the entire string ""aa"". Example 2: 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"". Example 3: Input: s = ""ab""; p = "".*"" Output: true Explanation: "".*"" means ""zero or more (*) of any character (.)"". Constraints: 1 <= s.length <= 20 1 <= p.length <= 20 s contains only lowercase English letters. p contains only lowercase English letters; '.'; and '*'. It is guaranteed for each appearance of the character '*'; there will be a previous valid character to match."538Google,29,Divide Two Integers,Med,"Math, Bit Manipulation",Given two integers dividend and divisor; divide two integers without using multiplication; division; and mod operator. The integer division should truncate toward zero; which means losing its fractional part. For example; 8.345 would be truncated to 8; and -2.7335 would be truncated to -2. Return the quotient after dividing dividend by divisor. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231; 231 − 1]. For this problem; if the quotient is strictly greater than 231 - 1; then return 231 - 1; and if the quotient is strictly less than -231; then return -231. Example 1: Input: dividend = 10; divisor = 3 Output: 3 Explanation: 10/3 = 3.33333.. which is truncated to 3. Example 2: Input: dividend = 7; divisor = -3 Output: -2 Explanation: 7/-3 = -2.33333.. which is truncated to -2. Constraints: -231 <= dividend; divisor <= 231 - 1 divisor != 0539Google,32,Longest Valid Parentheses,Hard,"String, Dynamic Programming, Stack","Given a string containing just the characters '(' and ')'; return the length of the longest valid (well-formed) parentheses substring. Example 1: Input: s = ""(()"" Output: 2 Explanation: The longest valid parentheses substring is ""()"". Example 2: Input: s = "")()())"" Output: 4 Explanation: The longest valid parentheses substring is ""()()"". Example 3: Input: s = """" Output: 0 Constraints: 0 <= s.length <= 3 * 104 s[i] is '('; or ')'."540Google,62,Unique Paths,Med,"Math, Dynamic Programming, Combinatorics",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. Example 1: Input: m = 3; n = 7 Output: 28 Example 2: Input: m = 3; n = 2 Output: 3 Explanation: From the top-left corner; there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down Constraints: 1 <= m; n <= 100541Google,69,Sqrt(x),Easy,"Math, Binary Search",Given a non-negative integer x; return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well. You must not use any built-in exponent function or operator. For example; do not use pow(x; 0.5) in c++ or x ** 0.5 in python. Example 1: Input: x = 4 Output: 2 Explanation: The square root of 4 is 2; so we return 2. Example 2: Input: x = 8 Output: 2 Explanation: The square root of 8 is 2.82842...; and since we round it down to the nearest integer; 2 is returned. Constraints: 0 <= x <= 231 - 1542Google,74,Search a 2D Matrix,Med,"Array, Binary Search, Matrix",You are given an m x n integer matrix matrix with the following two properties: Each row is sorted in non-decreasing order. The first integer of each row is greater than the last integer of the previous row. Given an integer target; return true if target is in matrix or false otherwise. You must write a solution in O(log(m * n)) time complexity. Example 1: Input: matrix = [[1;3;5;7];[10;11;16;20];[23;30;34;60]]; target = 3 Output: true Example 2: Input: matrix = [[1;3;5;7];[10;11;16;20];[23;30;34;60]]; target = 13 Output: false Constraints: m == matrix.length n == matrix[i].length 1 <= m; n <= 100 -104 <= matrix[i][j]; target <= 104543Google,83,Remove Duplicates from Sorted List,Easy,Linked List,Given the head of a sorted linked list; delete all duplicates such that each element appears only once. Return the linked list sorted as well. Example 1: Input: head = [1;1;2] Output: [1;2] Example 2: Input: head = [1;1;2;3;3] Output: [1;2;3] Constraints: The number of nodes in the list is in the range [0; 300]. -100 <= Node.val <= 100 The list is guaranteed to be sorted in ascending order.544Google,85,Maximal Rectangle,Hard,"Array, Dynamic Programming, Stack, Matrix, Monotonic Stack","Given a rows x cols binary matrix filled with 0's and 1's; find the largest rectangle containing only 1's and return its area. Example 1: Input: matrix = [[""1"";""0"";""1"";""0"";""0""];[""1"";""0"";""1"";""1"";""1""];[""1"";""1"";""1"";""1"";""1""];[""1"";""0"";""0"";""1"";""0""]] Output: 6 Explanation: The maximal rectangle is shown in the above picture. Example 2: Input: matrix = [[""0""]] Output: 0 Example 3: Input: matrix = [[""1""]] Output: 1 Constraints: rows == matrix.length cols == matrix[i].length 1 <= row; cols <= 200 matrix[i][j] is '0' or '1'."545Google,127,Word Ladder,Hard,"Hash Table, String, Breadth-First Search","A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Every adjacent pair of words differs by a single letter. Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. sk == endWord Given two words; beginWord and endWord; and a dictionary wordList; return the number of words in the shortest transformation sequence from beginWord to endWord; or 0 if no such sequence exists. Example 1: Input: beginWord = ""hit""; endWord = ""cog""; wordList = [""hot"";""dot"";""dog"";""lot"";""log"";""cog""] Output: 5 Explanation: One shortest transformation sequence is ""hit"" -> ""hot"" -> ""dot"" -> ""dog"" -> cog""; which is 5 words long. Example 2: Input: beginWord = ""hit""; endWord = ""cog""; wordList = [""hot"";""dot"";""dog"";""lot"";""log""] Output: 0 Explanation: The endWord ""cog"" is not in wordList; therefore there is no valid transformation sequence. Constraints: 1 <= beginWord.length <= 10 endWord.length == beginWord.length 1 <= wordList.length <= 5000 wordList[i].length == beginWord.length beginWord; endWord; and wordList[i] consist of lowercase English letters. beginWord != endWord All the words in wordList are unique."546Google,134,Gas Station,Med,"Array, Greedy",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. Example 1: 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. Example 2: Input: gas = [2;3;4]; cost = [3;4;3] Output: -1 Explanation: You can't start at station 0 or 1; as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2; as it requires 4 unit of gas but you only have 3. Therefore; you can't travel around the circuit once no matter where you start. Constraints: n == gas.length == cost.length 1 <= n <= 105 0 <= gas[i]; cost[i] <= 104547Google,138,Copy List with Random Pointer,Med,"Hash Table, Linked List",A linked list of length n is given such that each node contains an additional random pointer; which could point to any node in the list; or null. Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes; where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list. For example; if there are two nodes X and Y in the original list; where X.random --> Y; then for the corresponding two nodes x and y in the copied list; x.random --> y. Return the head of the copied linked list. The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val; random_index] where: val: an integer representing Node.val random_index: the index of the node (range from 0 to n-1) that the random pointer points to; or null if it does not point to any node. Your code will only be given the head of the original linked list. Example 1: Input: head = [[7;null];[13;0];[11;4];[10;2];[1;0]] Output: [[7;null];[13;0];[11;4];[10;2];[1;0]] Example 2: Input: head = [[1;1];[2;1]] Output: [[1;1];[2;1]] Example 3: Input: head = [[3;null];[3;0];[3;null]] Output: [[3;null];[3;0];[3;null]] Constraints: 0 <= n <= 1000 -104 <= Node.val <= 104 Node.random is null or is pointing to some node in the linked list.548Google,139,Word Break,Med,"Array, Hash Table, String, Dynamic Programming, Trie, Memoization","Given a string s and a dictionary of strings wordDict; return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation. Example 1: Input: s = ""leetcode""; wordDict = [""leet"";""code""] Output: true Explanation: Return true because ""leetcode"" can be segmented as ""leet code"". Example 2: Input: s = ""applepenapple""; wordDict = [""apple"";""pen""] Output: true Explanation: Return true because ""applepenapple"" can be segmented as ""apple pen apple"". Note that you are allowed to reuse a dictionary word. Example 3: Input: s = ""catsandog""; wordDict = [""cats"";""dog"";""sand"";""and"";""cat""] Output: false Constraints: 1 <= s.length <= 300 1 <= wordDict.length <= 1000 1 <= wordDict[i].length <= 20 s and wordDict[i] consist of only lowercase English letters. All the strings of wordDict are unique."549Google,202,Happy Number,Easy,"Hash Table, Math, Two Pointers",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. Example 1: Input: n = 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 Example 2: Input: n = 2 Output: false Constraints: 1 <= n <= 231 - 1550Google,204,Count Primes,Med,"Array, Math, Enumeration, Number Theory",Given an integer n; return the number of prime numbers that are strictly less than n. Example 1: Input: n = 10 Output: 4 Explanation: There are 4 prime numbers less than 10; they are 2; 3; 5; 7. Example 2: Input: n = 0 Output: 0 Example 3: Input: n = 1 Output: 0 Constraints: 0 <= n <= 5 * 106551Google,214,Shortest Palindrome,Hard,"String, Rolling Hash, String Matching, Hash Function","You are given a string s. You can convert s to a palindrome by adding characters in front of it. Return the shortest palindrome you can find by performing this transformation. Example 1: Input: s = ""aacecaaa"" Output: ""aaacecaaa"" Example 2: Input: s = ""abcd"" Output: ""dcbabcd"" Constraints: 0 <= s.length <= 5 * 104 s consists of lowercase English letters only."552Google,224,Basic Calculator,Hard,"Math, String, Stack, Recursion","Given a string s representing a valid expression; implement a basic calculator to evaluate it; and return the result of the evaluation. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions; such as eval(). Example 1: Input: s = ""1 + 1"" Output: 2 Example 2: Input: s = "" 2-1 + 2 "" Output: 3 Example 3: Input: s = ""(1+(4+5+2)-3)+(6+8)"" Output: 23 Constraints: 1 <= s.length <= 3 * 105 s consists of digits; '+'; '-'; '('; ')'; and ' '. s represents a valid expression. '+' is not used as a unary operation (i.e.; ""+1"" and ""+(2 + 3)"" is invalid). '-' could be used as a unary operation (i.e.; ""-1"" and ""-(2 + 3)"" is valid). There will be no two consecutive operators in the input. Every number and running calculation will fit in a signed 32-bit integer."553Google,226,Invert Binary Tree,Easy,"Tree, Depth-First Search, Breadth-First Search, Binary Tree",Given the root of a binary tree; invert the tree; and return its root. Example 1: Input: root = [4;2;7;1;3;6;9] Output: [4;7;2;9;6;3;1] Example 2: Input: root = [2;1;3] Output: [2;3;1] Example 3: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0; 100]. -100 <= Node.val <= 100554Google,228,Summary Ranges,Easy,Array,"You are given a sorted unique integer array nums. A range [a;b] is the set of all integers from a to b (inclusive). Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is; each element of nums is covered by exactly one of the ranges; and there is no integer x such that x is in one of the ranges but not in nums. Each range [a;b] in the list should be output as: ""a->b"" if a != b ""a"" if a == b Example 1: Input: nums = [0;1;2;4;5;7] Output: [""0->2"";""4->5"";""7""] Explanation: The ranges are: [0;2] --> ""0->2"" [4;5] --> ""4->5"" [7;7] --> ""7"" Example 2: Input: nums = [0;2;3;4;6;8;9] Output: [""0"";""2->4"";""6"";""8->9""] Explanation: The ranges are: [0;0] --> ""0"" [2;4] --> ""2->4"" [6;6] --> ""6"" [8;9] --> ""8->9"" Constraints: 0 <= nums.length <= 20 -231 <= nums[i] <= 231 - 1 All the values of nums are unique. nums is sorted in ascending order."555Google,234,Palindrome Linked List,Easy,"Linked List, Two Pointers, Stack, Recursion",Given the head of a singly linked list; return true if it is a palindrome or false otherwise. Example 1: Input: head = [1;2;2;1] Output: true Example 2: Input: head = [1;2] Output: false Constraints: The number of nodes in the list is in the range [1; 105]. 0 <= Node.val <= 9 Follow up: Could you do it in O(n) time and O(1) space?556Google,239,Sliding Window Maximum,Hard,"Array, Queue, Sliding Window, Heap (Priority Queue), Monotonic Queue",You are given an array of integers nums; 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 max sliding window. Example 1: Input: nums = [1;3;-1;-3;5;3;6;7]; k = 3 Output: [3;3;5;5;6;7] Explanation: Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 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 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 Example 2: Input: nums = [1]; k = 1 Output: [1] Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 1 <= k <= nums.length557Google,258,Add Digits,Easy,"Math, Simulation, Number Theory",Given an integer num; repeatedly add all its digits until the result has only one digit; and return it. Example 1: Input: num = 38 Output: 2 Explanation: The process is 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 Since 2 has only one digit; return it. Example 2: Input: num = 0 Output: 0 Constraints: 0 <= num <= 231 - 1 Follow up: Could you do it without any loop/recursion in O(1) runtime?558Google,346,Moving Average from Data Stream,Easy,"Array, Design, Queue, Data Stream",559Google,392,Is Subsequence,Easy,"Two Pointers, String, Dynamic Programming","Given two strings s and t; return true if s is a subsequence of t; or false otherwise. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e.; ""ace"" is a subsequence of ""abcde"" while ""aec"" is not). Example 1: Input: s = ""abc""; t = ""ahbgdc"" Output: true Example 2: Input: s = ""axc""; t = ""ahbgdc"" Output: false Constraints: 0 <= s.length <= 100 0 <= t.length <= 104 s and t consist only of lowercase English letters. Follow up: Suppose there are lots of incoming s; say s1; s2; ...; sk where k >= 109; and you want to check one by one to see if t has its subsequence. In this scenario; how would you change your code?"560Google,443,String Compression,Med,"Two Pointers, String","Given an array of characters chars; compress it using the following algorithm: Begin with an empty string s. For each group of consecutive repeating characters in chars: If the group's length is 1; append the character to s. Otherwise; append the character followed by the group's length. The compressed string s should not be returned separately; but instead; be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars. After you are done modifying the input array; return the new length of the array. You must write an algorithm that uses only constant extra space. Example 1: Input: chars = [""a"";""a"";""b"";""b"";""c"";""c"";""c""] Output: Return 6; and the first 6 characters of the input array should be: [""a"";""2"";""b"";""2"";""c"";""3""] Explanation: The groups are ""aa""; ""bb""; and ""ccc"". This compresses to ""a2b2c3"". Example 2: Input: chars = [""a""] Output: Return 1; and the first character of the input array should be: [""a""] Explanation: The only group is ""a""; which remains uncompressed since it's a single character. Example 3: Input: chars = [""a"";""b"";""b"";""b"";""b"";""b"";""b"";""b"";""b"";""b"";""b"";""b"";""b""] Output: Return 4; and the first 4 characters of the input array should be: [""a"";""b"";""1"";""2""]. Explanation: The groups are ""a"" and ""bbbbbbbbbbbb"". This compresses to ""ab12"". Constraints: 1 <= chars.length <= 2000 chars[i] is a lowercase English letter; uppercase English letter; digit; or symbol."561Google,540,Single Element in a Sorted Array,Med,"Array, Binary Search",You are given a sorted array consisting of only integers where every element appears exactly twice; except for one element which appears exactly once. Return the single element that appears only once. Your solution must run in O(log n) time and O(1) space. Example 1: Input: nums = [1;1;2;3;3;4;4;8;8] Output: 2 Example 2: Input: nums = [3;3;7;7;10;11;11] Output: 10 Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 105562Google,547,Number of Provinces,Med,"Depth-First Search, Breadth-First Search, Union Find, Graph",There are n cities. Some of them are connected; while some are not. If city a is connected directly with city b; and city b is connected directly with city c; then city a is connected indirectly with city c. A province is a group of directly or indirectly connected cities and no other cities outside of the group. You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected; and isConnected[i][j] = 0 otherwise. Return the total number of provinces. Example 1: Input: isConnected = [[1;1;0];[1;1;0];[0;0;1]] Output: 2 Example 2: Input: isConnected = [[1;0;0];[0;1;0];[0;0;1]] Output: 3 Constraints: 1 <= n <= 200 n == isConnected.length n == isConnected[i].length isConnected[i][j] is 1 or 0. isConnected[i][i] == 1 isConnected[i][j] == isConnected[j][i]563Google,570,Managers with at Least 5 Direct Reports,Med,Database,Table: Employee +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | | department | varchar | | managerId | int | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table indicates the name of an employee; their department; and the id of their manager. If managerId is null; then the employee does not have a manager. No employee will be the manager of themself. Write a solution to find managers with at least five direct reports. Return the result table in any order. The result format is in the following example. Example 1: Input: Employee table: +-----+-------+------------+-----------+ | id | name | department | managerId | +-----+-------+------------+-----------+ | 101 | John | A | null | | 102 | Dan | A | 101 | | 103 | James | A | 101 | | 104 | Amy | A | 101 | | 105 | Anne | A | 101 | | 106 | Ron | B | 101 | +-----+-------+------------+-----------+ Output: +------+ | name | +------+ | John | +------+564Google,652,Find Duplicate Subtrees,Med,"Hash Table, Tree, Depth-First Search, Binary Tree",Given the root of a binary tree; return all duplicate subtrees. For each kind of duplicate subtrees; you only need to return the root node of any one of them. Two trees are duplicate if they have the same structure with the same node values. Example 1: Input: root = [1;2;3;4;null;2;4;null;null;4] Output: [[2;4];[4]] Example 2: Input: root = [2;1;1] Output: [[1]] Example 3: Input: root = [2;2;2;3;null;3;null] Output: [[2;3];[3]] Constraints: The number of the nodes in the tree will be in the range [1; 5000] -200 <= Node.val <= 200565Google,721,Accounts Merge,Med,"Array, Hash Table, String, Depth-First Search, Breadth-First Search, Union Find, Sorting","Given a list of accounts where each element accounts[i] is a list of strings; where the first element accounts[i][0] is a name; and the rest of the elements are emails representing emails of the account. Now; we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name; they may belong to different people as people could have the same name. A person can have any number of accounts initially; but all of their accounts definitely have the same name. After merging the accounts; return the accounts in the following format: the first element of each account is the name; and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order. Example 1: Input: accounts = [[""John"";""johnsmith@mail.com"";""john_newyork@mail.com""];[""John"";""johnsmith@mail.com"";""john00@mail.com""];[""Mary"";""mary@mail.com""];[""John"";""johnnybravo@mail.com""]] Output: [[""John"";""john00@mail.com"";""john_newyork@mail.com"";""johnsmith@mail.com""];[""Mary"";""mary@mail.com""];[""John"";""johnnybravo@mail.com""]] Explanation: The first and second John's are the same person as they have the common email ""johnsmith@mail.com"". The third John and Mary are different people as none of their email addresses are used by other accounts. We could return these lists in any order; for example the answer [['Mary'; 'mary@mail.com']; ['John'; 'johnnybravo@mail.com']; ['John'; 'john00@mail.com'; 'john_newyork@mail.com'; 'johnsmith@mail.com']] would still be accepted. Example 2: Input: accounts = [[""Gabe"";""Gabe0@m.co"";""Gabe3@m.co"";""Gabe1@m.co""];[""Kevin"";""Kevin3@m.co"";""Kevin5@m.co"";""Kevin0@m.co""];[""Ethan"";""Ethan5@m.co"";""Ethan4@m.co"";""Ethan0@m.co""];[""Hanzo"";""Hanzo3@m.co"";""Hanzo1@m.co"";""Hanzo0@m.co""];[""Fern"";""Fern5@m.co"";""Fern1@m.co"";""Fern0@m.co""]] Output: [[""Ethan"";""Ethan0@m.co"";""Ethan4@m.co"";""Ethan5@m.co""];[""Gabe"";""Gabe0@m.co"";""Gabe1@m.co"";""Gabe3@m.co""];[""Hanzo"";""Hanzo0@m.co"";""Hanzo1@m.co"";""Hanzo3@m.co""];[""Kevin"";""Kevin0@m.co"";""Kevin3@m.co"";""Kevin5@m.co""];[""Fern"";""Fern0@m.co"";""Fern1@m.co"";""Fern5@m.co""]] Constraints: 1 <= accounts.length <= 1000 2 <= accounts[i].length <= 10 1 <= accounts[i][j].length <= 30 accounts[i][0] consists of English letters. accounts[i][j] (for j > 0) is a valid email."566Google,735,Asteroid Collision,Med,"Array, Stack, Simulation",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. Example 1: Input: asteroids = [5;10;-5] Output: [5;10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide. Example 2: Input: asteroids = [8;-8] Output: [] Explanation: The 8 and -8 collide exploding each other. Example 3: Input: asteroids = [10;2;-5] Output: [10] Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. Constraints: 2 <= asteroids.length <= 104 -1000 <= asteroids[i] <= 1000 asteroids[i] != 0567Google,739,Daily Temperatures,Med,"Array, Stack, Monotonic Stack",Given an array of integers temperatures represents the daily temperatures; return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible; keep answer[i] == 0 instead. Example 1: Input: temperatures = [73;74;75;71;69;72;76;73] Output: [1;1;4;2;1;1;0;0] Example 2: Input: temperatures = [30;40;50;60] Output: [1;1;1;0] Example 3: Input: temperatures = [30;60;90] Output: [1;1;0] Constraints: 1 <= temperatures.length <= 105 30 <= temperatures[i] <= 100568Google,703,Kth Largest Element in a Stream,Easy,,569Google,641,Design Circular Deque,Med,,570Google,875,Koko Eating Bananas,Med,"Array, Two Pointers, Dynamic Programming, Enumeration",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. Example 1: 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. Example 2: Input: arr = [2;2;2] Output: 0 Explanation: There is no mountain. Constraints: 1 <= arr.length <= 104 0 <= arr[i] <= 104 Follow up: Can you solve it using only one pass? Can you solve it in O(1) space?571Google,987,Vertical Order Traversal of a Binary Tree,Hard,"Array, Queue, Sorting, Simulation",You are given an integer array deck. There is a deck of cards where every card has a unique integer. The integer on the ith card is deck[i]. You can order the deck in any order you want. Initially; all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: Take the top card of the deck; reveal it; and take it out of the deck. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. If there are still unrevealed cards; go back to step 1. Otherwise; stop. Return an ordering of the deck that would reveal the cards in increasing order. Note that the first entry in the answer is considered to be the top of the deck. Example 1: Input: deck = [17;13;11;2;3;5;7] Output: [2;13;3;11;5;17;7] Explanation: We get the deck in the order [17;13;11;2;3;5;7] (this order does not matter); and reorder it. After reordering; the deck starts as [2;13;3;11;5;17;7]; where 2 is the top of the deck. We reveal 2; and move 13 to the bottom. The deck is now [3;11;5;17;7;13]. We reveal 3; and move 11 to the bottom. The deck is now [5;17;7;13;11]. We reveal 5; and move 17 to the bottom. The deck is now [7;13;11;17]. We reveal 7; and move 13 to the bottom. The deck is now [11;17;13]. We reveal 11; and move 17 to the bottom. The deck is now [13;17]. We reveal 13; and move 17 to the bottom. The deck is now [17]. We reveal 17. Since all the cards revealed are in increasing order; the answer is correct. Example 2: Input: deck = [1;1000] Output: [1;1000] Constraints: 1 <= deck.length <= 1000 1 <= deck[i] <= 106 All the values of deck are unique.572Google,1249,Minimum Remove to Make Valid Parentheses,Med,"Array, Hash Table, Binary Search, Design","Implement a SnapshotArray that supports the following interface: SnapshotArray(int length) initializes an array-like data structure with the given length. Initially; each element equals 0. void set(index; val) sets the element at the given index to be equal to val. int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1. int get(index; snap_id) returns the value at the given index; at the time we took the snapshot with the given snap_id Example 1: Input: [""SnapshotArray"";""set"";""snap"";""set"";""get""] [[3];[0;5];[];[0;6];[0;0]] Output: [null;null;0;null;5] Explanation: SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3 snapshotArr.set(0;5); // Set array[0] = 5 snapshotArr.snap(); // Take a snapshot; return snap_id = 0 snapshotArr.set(0;6); snapshotArr.get(0;0); // Get the value of array[0] with snap_id = 0; return 5 Constraints: 1 <= length <= 5 * 104 0 <= index < length 0 <= val <= 109 0 <= snap_id < (the total number of times we call snap()) At most 5 * 104 calls will be made to set; snap; and get."573Google,1277,Count Square Submatrices with All Ones,Med,"Array, Dynamic Programming, Greedy","Given an array of digits digits; return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string. Since the answer may not fit in an integer data type; return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros. Example 1: Input: digits = [8;1;9] Output: ""981"" Example 2: Input: digits = [8;6;7;1;0] Output: ""8760"" Example 3: Input: digits = [1] Output: """" Constraints: 1 <= digits.length <= 104 0 <= digits[i] <= 9"574Google,1492,The kth Factor of n,Med,"Tree, Depth-First Search, Breadth-First Search",A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID. Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee; manager[headID] = -1. Also; it is guaranteed that the subordination relationships have a tree structure. The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates; and they will inform their subordinates; and so on until all employees know about the urgent news. The i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e.; After informTime[i] minutes; all his direct subordinates can start spreading the news). Return the number of minutes needed to inform all the employees about the urgent news. Example 1: Input: n = 1; headID = 0; manager = [-1]; informTime = [0] Output: 0 Explanation: The head of the company is the only employee in the company. Example 2: Input: n = 6; headID = 2; manager = [2;2;-1;2;2;2]; informTime = [0;0;1;0;0;0] Output: 1 Explanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all. The tree structure of the employees in the company is shown. Constraints: 1 <= n <= 105 0 <= headID < n manager.length == n 0 <= manager[i] < n manager[headID] == -1 informTime.length == n 0 <= informTime[i] <= 1000 informTime[i] == 0 if employee i has no subordinates. It is guaranteed that all the employees can be informed.575Google,1942,The Number of the Smallest Unoccupied Chair,Med,Database,Table: Employee +---------------+---------+ | Column Name | Type | +---------------+---------+ | employee_id | int | | department_id | int | | primary_flag | varchar | +---------------+---------+ (employee_id; department_id) is the primary key (combination of columns with unique values) for this table. employee_id is the id of the employee. department_id is the id of the department to which the employee belongs. primary_flag is an ENUM (category) of type ('Y'; 'N'). If the flag is 'Y'; the department is the primary department for the employee. If the flag is 'N'; the department is not the primary. Employees can belong to multiple departments. When the employee joins other departments; they need to decide which department is their primary department. Note that when an employee belongs to only one department; their primary column is 'N'. Write a solution to report all the employees with their primary department. For employees who belong to one department; report their only department. Return the result table in any order. The result format is in the following example. Example 1: Input: Employee table: +-------------+---------------+--------------+ | employee_id | department_id | primary_flag | +-------------+---------------+--------------+ | 1 | 1 | N | | 2 | 1 | Y | | 2 | 2 | N | | 3 | 3 | N | | 4 | 2 | N | | 4 | 3 | Y | | 4 | 4 | N | +-------------+---------------+--------------+ Output: +-------------+---------------+ | employee_id | department_id | +-------------+---------------+ | 1 | 1 | | 2 | 1 | | 3 | 3 | | 4 | 3 | +-------------+---------------+ Explanation: - The Primary department for employee 1 is 1. - The Primary department for employee 2 is 1. - The Primary department for employee 3 is 3. - The Primary department for employee 4 is 3.576Google,2018,Check if Word Can Be Placed In Crossword,Med,"Array, Binary Search, Sorting, Prefix Sum",You have n packages that you are trying to place in boxes; one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box. The package sizes are given as an integer array packages; where packages[i] is the size of the ith package. The suppliers are given as a 2D integer array boxes; where boxes[j] is an array of box sizes that the jth supplier produces. You want to choose a single supplier and use boxes from them such that the total wasted space is minimized. For each package in a box; we define the space wasted to be size of the box - size of the package. The total wasted space is the sum of the space wasted in all the boxes. For example; if you have to fit packages with sizes [2;3;5] and the supplier offers boxes of sizes [4;8]; you can fit the packages of size-2 and size-3 into two boxes of size-4 and the package with size-5 into a box of size-8. This would result in a waste of (4-2) + (4-3) + (8-5) = 6. Return the minimum total wasted space by choosing the box supplier optimally; or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large; return it modulo 109 + 7. Example 1: Input: packages = [2;3;5]; boxes = [[4;8];[2;8]] Output: 6 Explanation: It is optimal to choose the first supplier; using two size-4 boxes and one size-8 box. The total waste is (4-2) + (4-3) + (8-5) = 6. Example 2: Input: packages = [2;3;5]; boxes = [[1;4];[2;3];[3;4]] Output: -1 Explanation: There is no box that the package of size 5 can fit in. Example 3: Input: packages = [3;5;8;10;11;12]; boxes = [[12];[11;9];[10;5;14]] Output: 9 Explanation: It is optimal to choose the third supplier; using two size-5 boxes; two size-10 boxes; and two size-14 boxes. The total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9. Constraints: n == packages.length m == boxes.length 1 <= n <= 105 1 <= m <= 105 1 <= packages[i] <= 105 1 <= boxes[j].length <= 105 1 <= boxes[j][k] <= 105 sum(boxes[j].length) <= 105 The elements in boxes[j] are distinct.577Google,2620,Counter,Easy,"Hash Table, Design, Queue, Counting, Data Stream","For a stream of integers; implement a data structure that checks if the last k integers parsed in the stream are equal to value. Implement the DataStream class: DataStream(int value; int k) Initializes the object with an empty integer stream and the two integers value and k. boolean consec(int num) Adds num to the stream of integers. Returns true if the last k integers are equal to value; and false otherwise. If there are less than k integers; the condition does not hold true; so returns false. Example 1: Input [""DataStream""; ""consec""; ""consec""; ""consec""; ""consec""] [[4; 3]; [4]; [4]; [4]; [3]] Output [null; false; false; true; false] Explanation DataStream dataStream = new DataStream(4; 3); //value = 4; k = 3 dataStream.consec(4); // Only 1 integer is parsed; so returns False. dataStream.consec(4); // Only 2 integers are parsed. // Since 2 is less than k; returns False. dataStream.consec(4); // The 3 integers parsed are all equal to value; so returns True. dataStream.consec(3); // The last k integers parsed in the stream are [4;4;3]. // Since 3 is not equal to value; it returns False. Constraints: 1 <= value; num <= 109 1 <= k <= 105 At most 105 calls will be made to consec."578Google,2703,Return Length of Arguments Passed,Easy,"Array, Segment Tree",You are given two 0-indexed arrays nums1 and nums2 and a 2D array queries of queries. There are three types of queries: For a query of type 1; queries[i] = [1; l; r]. Flip the values from 0 to 1 and from 1 to 0 in nums1 from index l to index r. Both l and r are 0-indexed. For a query of type 2; queries[i] = [2; p; 0]. For every index 0 <= i < n; set nums2[i] = nums2[i] + nums1[i] * p. For a query of type 3; queries[i] = [3; 0; 0]. Find the sum of the elements in nums2. Return an array containing all the answers to the third type queries. Example 1: Input: nums1 = [1;0;1]; nums2 = [0;0;0]; queries = [[1;1;1];[2;1;0];[3;0;0]] Output: [3] Explanation: After the first query nums1 becomes [1;1;1]. After the second query; nums2 becomes [1;1;1]; so the answer to the third query is 3. Thus; [3] is returned. Example 2: Input: nums1 = [1]; nums2 = [5]; queries = [[2;0;0];[3;0;0]] Output: [5] Explanation: After the first query; nums2 remains [5]; so the answer to the second query is 5. Thus; [5] is returned. Constraints: 1 <= nums1.length;nums2.length <= 105 nums1.length = nums2.length 1 <= queries.length <= 105 queries[i].length = 3 0 <= l <= r <= nums1.length - 1 0 <= p <= 106 0 <= nums1[i] <= 1 0 <= nums2[i] <= 109579Google,2812,Find the Safest Path in a Grid,Med,Math,Given two integers; num and t. A number is achievable if it can become equal to num after applying the following operation: Increase or decrease the number by 1; and simultaneously increase or decrease num by 1. Return the maximum achievable number after applying the operation at most t times. Example 1: Input: num = 4; t = 1 Output: 6 Explanation: Apply the following operation once to make the maximum achievable number equal to num: Decrease the maximum achievable number by 1; and increase num by 1. Example 2: Input: num = 3; t = 2 Output: 7 Explanation: Apply the following operation twice to make the maximum achievable number equal to num: Decrease the maximum achievable number by 1; and increase num by 1. Constraints: 1 <= num; t <= 50580Google,2914,Minimum Number of Changes to Make Binary String Beautiful,Med,"Array, Binary Search, Breadth-First Search, Union Find, Matrix",You are given a 0-indexed 2D matrix grid of size n x n; where (r; c) represents: A cell containing a thief if grid[r][c] = 1 An empty cell if grid[r][c] = 0 You are initially positioned at cell (0; 0). In one move; you can move to any adjacent cell in the grid; including cells containing thieves. The safeness factor of a path on the grid is defined as the minimum manhattan distance from any cell in the path to any thief in the grid. Return the maximum safeness factor of all paths leading to cell (n - 1; n - 1). An adjacent cell of cell (r; c); is one of the cells (r; c + 1); (r; c - 1); (r + 1; c) and (r - 1; c) if it exists. The Manhattan distance between two cells (a; b) and (x; y) is equal to |a - x| + |b - y|; where |val| denotes the absolute value of val. Example 1: Input: grid = [[1;0;0];[0;0;0];[0;0;1]] Output: 0 Explanation: All paths from (0; 0) to (n - 1; n - 1) go through the thieves in cells (0; 0) and (n - 1; n - 1). Example 2: Input: grid = [[0;0;1];[0;0;0];[0;0;0]] Output: 2 Explanation: The path depicted in the picture above has a safeness factor of 2 since: - The closest cell of the path to the thief at cell (0; 2) is cell (0; 0). The distance between them is | 0 - 0 | + | 0 - 2 | = 2. It can be shown that there are no other paths with a higher safeness factor. Example 3: Input: grid = [[0;0;0;1];[0;0;0;0];[0;0;0;0];[1;0;0;0]] Output: 2 Explanation: The path depicted in the picture above has a safeness factor of 2 since: - The closest cell of the path to the thief at cell (0; 3) is cell (1; 2). The distance between them is | 0 - 1 | + | 3 - 2 | = 2. - The closest cell of the path to the thief at cell (3; 0) is cell (3; 2). The distance between them is | 3 - 3 | + | 0 - 2 | = 2. It can be shown that there are no other paths with a higher safeness factor. Constraints: 1 <= grid.length == n <= 400 grid[i].length == n grid[i][j] is either 0 or 1. There is at least one thief in the grid.581Google,12,Integer to Roman,Med,"Hash Table, Math, String","Seven different symbols represent Roman numerals with the following values: Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 Roman numerals are formed by appending the conversions of decimal place values from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules: If the value does not start with 4 or 9; select the symbol of the maximal value that can be subtracted from the input; append that symbol to the result; subtract its value; and convert the remainder to a Roman numeral. If the value starts with 4 or 9 use the subtractive form representing one symbol subtracted from the following symbol; for example; 4 is 1 (I) less than 5 (V): IV and 9 is 1 (I) less than 10 (X): IX. Only the following subtractive forms are used: 4 (IV); 9 (IX); 40 (XL); 90 (XC); 400 (CD) and 900 (CM). Only powers of 10 (I; X; C; M) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5 (V); 50 (L); or 500 (D) multiple times. If you need to append a symbol 4 times use the subtractive form. Given an integer; convert it to a Roman numeral. Example 1: Input: num = 3749 Output: ""MMMDCCXLIX"" Explanation: 3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M) 700 = DCC as 500 (D) + 100 (C) + 100 (C) 40 = XL as 10 (X) less of 50 (L) 9 = IX as 1 (I) less of 10 (X) Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places Example 2: Input: num = 58 Output: ""LVIII"" Explanation: 50 = L 8 = VIII Example 3: Input: num = 1994 Output: ""MCMXCIV"" Explanation: 1000 = M 900 = CM 90 = XC 4 = IV Constraints: 1 <= num <= 3999"582Google,19,Remove Nth Node From End of List,Med,"Linked List, Two Pointers",Given the head of a linked list; remove the nth node from the end of the list and return its head. Example 1: Input: head = [1;2;3;4;5]; n = 2 Output: [1;2;3;5] Example 2: Input: head = [1]; n = 1 Output: [] Example 3: Input: head = [1;2]; n = 1 Output: [1] Constraints: The number of nodes in the list is sz. 1 <= sz <= 30 0 <= Node.val <= 100 1 <= n <= sz Follow up: Could you do this in one pass?583Google,24,Swap Nodes in Pairs,Med,"Linked List, Recursion",Given a linked list; swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e.; only nodes themselves may be changed.) Example 1: Input: head = [1;2;3;4] Output: [2;1;4;3] Explanation: Example 2: Input: head = [] Output: [] Example 3: Input: head = [1] Output: [1] Example 4: Input: head = [1;2;3] Output: [2;1;3] Constraints: The number of nodes in the list is in the range [0; 100]. 0 <= Node.val <= 100584Google,43,Multiply Strings,Med,"Math, String, Simulation","Given two non-negative integers num1 and num2 represented as strings; return the product of num1 and num2; also represented as a string. Note: You must not use any built-in BigInteger library or convert the inputs to integer directly. Example 1: Input: num1 = ""2""; num2 = ""3"" Output: ""6"" Example 2: Input: num1 = ""123""; num2 = ""456"" Output: ""56088"" Constraints: 1 <= num1.length; num2.length <= 200 num1 and num2 consist of digits only. Both num1 and num2 do not contain any leading zero; except the number 0 itself."585Google,75,Sort Colors,Med,"Array, Two Pointers, Sorting",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. Example 1: Input: nums = [2;0;2;1;1;0] Output: [0;0;1;1;2;2] Example 2: Input: nums = [2;0;1] Output: [0;1;2] Constraints: n == nums.length 1 <= n <= 300 nums[i] is either 0; 1; or 2. Follow up: Could you come up with a one-pass algorithm using only constant extra space?586Google,80,Remove Duplicates from Sorted Array II,Med,"Array, Two Pointers",Given an integer array nums sorted in non-decreasing order; remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages; you must instead have the result be placed in the first part of the array nums. More formally; if there are k elements after removing the duplicates; then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass; then your solution will be accepted. Example 1: Input: nums = [1;1;1;2;2;3] Output: 5; nums = [1;1;2;2;3;_] Explanation: Your function should return k = 5; with the first five elements of nums being 1; 1; 2; 2 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). Example 2: Input: nums = [0;0;1;1;1;1;2;3;3] Output: 7; nums = [0;0;1;1;2;3;3;_;_] Explanation: Your function should return k = 7; with the first seven elements of nums being 0; 0; 1; 1; 2; 3 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). Constraints: 1 <= nums.length <= 3 * 104 -104 <= nums[i] <= 104 nums is sorted in non-decreasing order.587Google,92,Reverse Linked List II,Med,Linked List,Given the head of a singly linked list and two integers left and right where left <= right; reverse the nodes of the list from position left to position right; and return the reversed list. Example 1: Input: head = [1;2;3;4;5]; left = 2; right = 4 Output: [1;4;3;2;5] Example 2: Input: head = [5]; left = 1; right = 1 Output: [5] Constraints: The number of nodes in the list is n. 1 <= n <= 500 -500 <= Node.val <= 500 1 <= left <= right <= n Follow up: Could you do it in one pass?588Google,93,Restore IP Addresses,Med,"String, Backtracking","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 ""192.168@1.1"" 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. Example 1: Input: s = ""25525511135"" Output: [""255.255.11.135"";""255.255.111.35""] Example 2: Input: s = ""0000"" Output: [""0.0.0.0""] Example 3: Input: s = ""101023"" Output: [""1.0.10.23"";""1.0.102.3"";""10.1.0.23"";""10.10.2.3"";""101.0.2.3""] Constraints: 1 <= s.length <= 20 s consists of digits only."589Google,94,Binary Tree Inorder Traversal,Easy,"Stack, Tree, Depth-First Search, Binary Tree",Given the root of a binary tree; return the inorder traversal of its nodes' values. Example 1: Input: root = [1;null;2;3] Output: [1;3;2] Explanation: Example 2: Input: root = [1;2;3;4;5;null;8;null;null;6;7;9] Output: [4;2;6;5;7;1;3;9;8] Explanation: Example 3: Input: root = [] Output: [] Example 4: Input: root = [1] Output: [1] Constraints: The number of nodes in the tree is in the range [0; 100]. -100 <= Node.val <= 100 Follow up: Recursive solution is trivial; could you do it iteratively?590Google,98,Validate Binary Search Tree,Med,"Tree, Depth-First Search, Binary Search Tree, Binary Tree",Given the root of a binary tree; determine if it is a valid binary search tree (BST). A valid BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: root = [2;1;3] Output: true Example 2: Input: root = [5;1;4;null;null;3;6] Output: false Explanation: The root node's value is 5 but its right child's value is 4. Constraints: The number of nodes in the tree is in the range [1; 104]. -231 <= Node.val <= 231 - 1591Google,102,Binary Tree Level Order Traversal,Med,"Tree, Breadth-First Search, Binary Tree",Given the root of a binary tree; return the level order traversal of its nodes' values. (i.e.; from left to right; level by level). Example 1: Input: root = [3;9;20;null;null;15;7] Output: [[3];[9;20];[15;7]] Example 2: Input: root = [1] Output: [[1]] Example 3: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0; 2000]. -1000 <= Node.val <= 1000592Google,130,Surrounded Regions,Med,"Array, Depth-First Search, Breadth-First Search, Union Find, Matrix","You are given an m x n matrix board containing letters 'X' and 'O'; capture regions that are surrounded: Connect: A cell is connected to adjacent cells horizontally or vertically. Region: To form a region connect every 'O' cell. Surround: The region is surrounded with 'X' cells if you can connect the region with 'X' cells and none of the region cells are on the edge of the board. A surrounded region is captured by replacing all 'O's with 'X's in the input matrix board. Example 1: Input: 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""]] Explanation: In the above diagram; the bottom region is not captured because it is on the edge of the board and cannot be surrounded. Example 2: Input: board = [[""X""]] Output: [[""X""]] Constraints: m == board.length n == board[i].length 1 <= m; n <= 200 board[i][j] is 'X' or 'O'."593Google,230,Kth Smallest Element in a BST,Med,"Tree, Depth-First Search, Binary Search Tree, Binary Tree",Given the root of a binary search tree; and an integer k; return the kth smallest value (1-indexed) of all the values of the nodes in the tree. Example 1: Input: root = [3;1;4;null;2]; k = 1 Output: 1 Example 2: Input: root = [5;3;6;2;4;null;null;1]; k = 3 Output: 3 Constraints: The number of nodes in the tree is n. 1 <= k <= n <= 104 0 <= Node.val <= 104 Follow up: If the BST is modified often (i.e.; we can do insert and delete operations) and you need to find the kth smallest frequently; how would you optimize?594Google,236,Lowest Common Ancestor of a Binary Tree,Med,"Tree, Depth-First Search, Binary Tree",Given a binary tree; find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Example 1: Input: root = [3;5;1;6;2;0;8;null;null;7;4]; p = 5; q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3. Example 2: Input: root = [3;5;1;6;2;0;8;null;null;7;4]; p = 5; q = 4 Output: 5 Explanation: The LCA of nodes 5 and 4 is 5; since a node can be a descendant of itself according to the LCA definition. Example 3: Input: root = [1;2]; p = 1; q = 2 Output: 1 Constraints: The number of nodes in the tree is in the range [2; 105]. -109 <= Node.val <= 109 All Node.val are unique. p != q p and q will exist in the tree.595Google,263,Ugly Number,Easy,Math,An ugly number is a positive integer which does not have a prime factor other than 2; 3; and 5. Given an integer n; return true if n is an ugly number. Example 1: Input: n = 6 Output: true Explanation: 6 = 2 × 3 Example 2: Input: n = 1 Output: true Explanation: 1 has no prime factors. Example 3: Input: n = 14 Output: false Explanation: 14 is not ugly since it includes the prime factor 7. Constraints: -231 <= n <= 231 - 1596Google,283,Move Zeroes,Easy,"Array, Two Pointers",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. Example 1: Input: nums = [0;1;0;3;12] Output: [1;3;12;0;0] Example 2: Input: nums = [0] Output: [0] Constraints: 1 <= nums.length <= 104 -231 <= nums[i] <= 231 - 1 Follow up: Could you minimize the total number of operations done?597Google,328,Odd Even Linked List,Med,Linked List,Given the head of a singly linked list; group all the nodes with odd indices together followed by the nodes with even indices; and return the reordered list. The first node is considered odd; and the second node is even; and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in O(1) extra space complexity and O(n) time complexity. Example 1: Input: head = [1;2;3;4;5] Output: [1;3;5;2;4] Example 2: Input: head = [2;1;3;5;6;4;7] Output: [2;3;6;7;1;5;4] Constraints: The number of nodes in the linked list is in the range [0; 104]. -106 <= Node.val <= 106598Google,332,Reconstruct Itinerary,Hard,"Depth-First Search, Graph, Eulerian Circuit","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. Example 1: Input: tickets = [[""MUC"";""LHR""];[""JFK"";""MUC""];[""SFO"";""SJC""];[""LHR"";""SFO""]] Output: [""JFK"";""MUC"";""LHR"";""SFO"";""SJC""] Example 2: 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. Constraints: 1 <= tickets.length <= 300 tickets[i].length == 2 fromi.length == 3 toi.length == 3 fromi and toi consist of uppercase English letters. fromi != toi"599Google,383,Ransom Note,Easy,"Hash Table, String, Counting","Given two strings ransomNote and magazine; return true if ransomNote can be constructed by using the letters from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote. Example 1: Input: ransomNote = ""a""; magazine = ""b"" Output: false Example 2: Input: ransomNote = ""aa""; magazine = ""ab"" Output: false Example 3: Input: ransomNote = ""aa""; magazine = ""aab"" Output: true Constraints: 1 <= ransomNote.length; magazine.length <= 105 ransomNote and magazine consist of lowercase English letters."600Google,387,First Unique Character in a String,Easy,"Hash Table, String, Queue, Counting","Given a string s; find the first non-repeating character in it and return its index. If it does not exist; return -1. Example 1: Input: s = ""leetcode"" Output: 0 Explanation: The character 'l' at index 0 is the first character that does not occur at any other index. Example 2: Input: s = ""loveleetcode"" Output: 2 Example 3: Input: s = ""aabb"" Output: -1 Constraints: 1 <= s.length <= 105 s consists of only lowercase English letters."601Google,389,Find the Difference,Easy,"Hash Table, String, Bit Manipulation, Sorting","You are given two strings s and t. String t is generated by random shuffling string s and then add one more letter at a random position. Return the letter that was added to t. Example 1: Input: s = ""abcd""; t = ""abcde"" Output: ""e"" Explanation: 'e' is the letter that was added. Example 2: Input: s = """"; t = ""y"" Output: ""y"" Constraints: 0 <= s.length <= 1000 t.length == s.length + 1 s and t consist of lowercase English letters."602Google,412,Fizz Buzz,Easy,"Math, String, Simulation","Given an integer n; return a string array answer (1-indexed) where: answer[i] == ""FizzBuzz"" if i is divisible by 3 and 5. answer[i] == ""Fizz"" if i is divisible by 3. answer[i] == ""Buzz"" if i is divisible by 5. answer[i] == i (as a string) if none of the above conditions are true. Example 1: Input: n = 3 Output: [""1"";""2"";""Fizz""] Example 2: Input: n = 5 Output: [""1"";""2"";""Fizz"";""4"";""Buzz""] Example 3: Input: n = 15 Output: [""1"";""2"";""Fizz"";""4"";""Buzz"";""Fizz"";""7"";""8"";""Fizz"";""Buzz"";""11"";""Fizz"";""13"";""14"";""FizzBuzz""] Constraints: 1 <= n <= 104"603Google,417,Pacific Atlantic Water Flow,Med,"Array, Depth-First Search, Breadth-First Search, Matrix",There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges; and the Atlantic Ocean touches the island's right and bottom edges. The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r; c). The island receives a lot of rain; and the rain water can flow to neighboring cells directly north; south; east; and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. Return a 2D list of grid coordinates result where result[i] = [ri; ci] denotes that rain water can flow from cell (ri; ci) to both the Pacific and Atlantic oceans. Example 1: Input: heights = [[1;2;2;3;5];[3;2;3;4;4];[2;4;5;3;1];[6;7;1;4;5];[5;1;1;2;4]] Output: [[0;4];[1;3];[1;4];[2;2];[3;0];[3;1];[4;0]] Explanation: The following cells can flow to the Pacific and Atlantic oceans; as shown below: [0;4]: [0;4] -> Pacific Ocean [0;4] -> Atlantic Ocean [1;3]: [1;3] -> [0;3] -> Pacific Ocean [1;3] -> [1;4] -> Atlantic Ocean [1;4]: [1;4] -> [1;3] -> [0;3] -> Pacific Ocean [1;4] -> Atlantic Ocean [2;2]: [2;2] -> [1;2] -> [0;2] -> Pacific Ocean [2;2] -> [2;3] -> [2;4] -> Atlantic Ocean [3;0]: [3;0] -> Pacific Ocean [3;0] -> [4;0] -> Atlantic Ocean [3;1]: [3;1] -> [3;0] -> Pacific Ocean [3;1] -> [4;1] -> Atlantic Ocean [4;0]: [4;0] -> Pacific Ocean [4;0] -> Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. Example 2: Input: heights = [[1]] Output: [[0;0]] Explanation: The water can flow from the only cell to the Pacific and Atlantic oceans. Constraints: m == heights.length n == heights[r].length 1 <= m; n <= 200 0 <= heights[r][c] <= 105604Google,440,K-th Smallest in Lexicographical Order,Hard,Trie,Given two integers n and k; return the kth lexicographically smallest integer in the range [1; n]. Example 1: Input: n = 13; k = 2 Output: 10 Explanation: The lexicographical order is [1; 10; 11; 12; 13; 2; 3; 4; 5; 6; 7; 8; 9]; so the second smallest number is 10. Example 2: Input: n = 1; k = 1 Output: 1 Constraints: 1 <= k <= n <= 109605Google,442,Find All Duplicates in an Array,Med,"Array, Hash Table",Given an integer array nums of length n where all the integers of nums are in the range [1; n] and each integer appears at most twice; return an array of all the integers that appears twice. You must write an algorithm that runs in O(n) time and uses only constant auxiliary space; excluding the space needed to store the output Example 1: Input: nums = [4;3;2;7;8;2;3;1] Output: [2;3] Example 2: Input: nums = [1;1;2] Output: [1] Example 3: Input: nums = [1] Output: [] Constraints: n == nums.length 1 <= n <= 105 1 <= nums[i] <= n Each element in nums appears once or twice.606Google,459,Repeated Substring Pattern,Easy,"String, String Matching","Given a string s; check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. Example 1: Input: s = ""abab"" Output: true Explanation: It is the substring ""ab"" twice. Example 2: Input: s = ""aba"" Output: false Example 3: Input: s = ""abcabcabcabc"" Output: true Explanation: It is the substring ""abc"" four times or the substring ""abcabc"" twice. Constraints: 1 <= s.length <= 104 s consists of lowercase English letters."607Google,543,Diameter of Binary Tree,Easy,"Tree, Depth-First Search, Binary Tree",Given the root of a binary tree; return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them. Example 1: Input: root = [1;2;3;4;5] Output: 3 Explanation: 3 is the length of the path [4;2;1;3] or [5;2;1;3]. Example 2: Input: root = [1;2] Output: 1 Constraints: The number of nodes in the tree is in the range [1; 104]. -100 <= Node.val <= 100608Google,592,Fraction Addition and Subtraction,Med,"Math, String, Simulation","Given a string expression representing an expression of fraction addition and subtraction; return the calculation result in string format. The final result should be an irreducible fraction. If your final result is an integer; change it to the format of a fraction that has a denominator 1. So in this case; 2 should be converted to 2/1. Example 1: Input: expression = ""-1/2+1/2"" Output: ""0/1"" Example 2: Input: expression = ""-1/2+1/2+1/3"" Output: ""1/3"" Example 3: Input: expression = ""1/3-1/2"" Output: ""-1/6"" Constraints: The input string only contains '0' to '9'; '/'; '+' and '-'. So does the output. Each fraction (input and output) has the format ±numerator/denominator. If the first input fraction or the output is positive; then '+' will be omitted. The input only contains valid irreducible fractions; where the numerator and denominator of each fraction will always be in the range [1; 10]. If the denominator is 1; it means this fraction is actually an integer in a fraction format defined above. The number of given fractions will be in the range [1; 10]. The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int."609Google,725,Split Linked List in Parts,Med,Linked List,Given the head of a singly linked list and an integer k; split the linked list into k consecutive linked list parts. The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null. The parts should be in the order of occurrence in the input list; and parts occurring earlier should always have a size greater than or equal to parts occurring later. Return an array of the k parts. Example 1: Input: head = [1;2;3]; k = 5 Output: [[1];[2];[3];[];[]] Explanation: The first element output[0] has output[0].val = 1; output[0].next = null. The last element output[4] is null; but its string representation as a ListNode is []. Example 2: Input: head = [1;2;3;4;5;6;7;8;9;10]; k = 3 Output: [[1;2;3;4];[5;6;7];[8;9;10]] Explanation: The input has been split into consecutive parts with size difference at most 1; and earlier parts are a larger size than the later parts. Constraints: The number of nodes in the list is in the range [0; 1000]. 0 <= Node.val <= 1000 1 <= k <= 50610Google,743,Network Delay Time,Med,"Tree, Depth-First Search, Breadth-First Search, Binary Tree",611Google,746,Min Cost Climbing Stairs,Easy,"Array, Hash Table, String, Design, Trie","Design a special dictionary that searches the words in it by a prefix and a suffix. Implement the WordFilter class: WordFilter(string[] words) Initializes the object with the words in the dictionary. f(string pref; string suff) Returns the index of the word in the dictionary; which has the prefix pref and the suffix suff. If there is more than one valid index; return the largest of them. If there is no such word in the dictionary; return -1. Example 1: Input [""WordFilter""; ""f""] [[[""apple""]]; [""a""; ""e""]] Output [null; 0] Explanation WordFilter wordFilter = new WordFilter([""apple""]); wordFilter.f(""a""; ""e""); // return 0; because the word at index 0 has prefix = ""a"" and suffix = ""e"". Constraints: 1 <= words.length <= 104 1 <= words[i].length <= 7 1 <= pref.length; suff.length <= 7 words[i]; pref and suff consist of lowercase English letters only. At most 104 calls will be made to the function f."612Google,921,Minimum Add to Make Parentheses Valid,Med,"Array, Matrix, Simulation",You start at the cell (rStart; cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid; and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary; we continue our walk outside the grid (but may return to the grid boundary later.). Eventually; we reach all rows * cols spaces of the grid. Return an array of coordinates representing the positions of the grid in the order you visited them. Example 1: Input: rows = 1; cols = 4; rStart = 0; cStart = 0 Output: [[0;0];[0;1];[0;2];[0;3]] Example 2: Input: rows = 5; cols = 6; rStart = 1; cStart = 4 Output: [[1;4];[1;5];[2;5];[2;4];[2;3];[1;3];[0;3];[0;4];[0;5];[3;5];[3;4];[3;3];[3;2];[2;2];[1;2];[0;2];[4;5];[4;4];[4;3];[4;2];[4;1];[3;1];[2;1];[1;1];[0;1];[4;0];[3;0];[2;0];[1;0];[0;0]] Constraints: 1 <= rows; cols <= 100 0 <= rStart < rows 0 <= cStart < cols613Google,509,Fibonacci Number,Easy,"Tree, Binary Search Tree, Binary Tree",614Google,973,K Closest Points to Origin,Med,"String, Stack, Greedy, Queue","You are given two strings stamp and target. Initially; there is a string s of length target.length with all s[i] == '?'. In one turn; you can place stamp over s and replace every letter in the s with the corresponding letter from stamp. For example; if stamp = ""abc"" and target = ""abcba""; then s is ""?????"" initially. In one turn you can: place stamp at index 0 of s to obtain ""abc??""; place stamp at index 1 of s to obtain ""?abc?""; or place stamp at index 2 of s to obtain ""??abc"". Note that stamp must be fully contained in the boundaries of s in order to stamp (i.e.; you cannot place stamp at index 3 of s). We want to convert s to target using at most 10 * target.length turns. Return an array of the index of the left-most letter being stamped at each turn. If we cannot obtain target from s within 10 * target.length turns; return an empty array. Example 1: Input: stamp = ""abc""; target = ""ababc"" Output: [0;2] Explanation: Initially s = ""?????"". - Place stamp at index 0 to get ""abc??"". - Place stamp at index 2 to get ""ababc"". [1;0;2] would also be accepted as an answer; as well as some other answers. Example 2: Input: stamp = ""abca""; target = ""aabcaca"" Output: [3;0;1] Explanation: Initially s = ""???????"". - Place stamp at index 3 to get ""???abca"". - Place stamp at index 0 to get ""abcabca"". - Place stamp at index 1 to get ""aabcaca"". Constraints: 1 <= stamp.length <= target.length <= 1000 stamp and target consist of lowercase English letters."615Google,986,Interval List Intersections,Med,"Array, String, Enumeration","Given an array arr of 4 digits; find the latest 24-hour time that can be made using each digit exactly once. 24-hour times are formatted as ""HH:MM""; where HH is between 00 and 23; and MM is between 00 and 59. The earliest 24-hour time is 00:00; and the latest is 23:59. Return the latest 24-hour time in ""HH:MM"" format. If no valid time can be made; return an empty string. Example 1: Input: arr = [1;2;3;4] Output: ""23:41"" Explanation: The valid 24-hour times are ""12:34""; ""12:43""; ""13:24""; ""13:42""; ""14:23""; ""14:32""; ""21:34""; ""21:43""; ""23:14""; and ""23:41"". Of these times; ""23:41"" is the latest. Example 2: Input: arr = [5;5;5;5] Output: """" Explanation: There are no valid 24-hour times as ""55:55"" is not valid. Constraints: arr.length == 4 0 <= arr[i] <= 9"616Google,992,Subarrays with K Different Integers,Hard,"Array, String, Greedy","You are given an array of n strings strs; all of the same length. We may choose any deletion indices; and we delete all the characters in those indices for each string. For example; if we have strs = [""abcdef"";""uvwxyz""] and deletion indices {0; 2; 3}; then the final array after deletions is [""bef""; ""vyz""]. Suppose we chose a set of deletion indices answer such that after deletions; the final array has its elements in lexicographic order (i.e.; strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]). Return the minimum possible value of answer.length. Example 1: Input: strs = [""ca"";""bb"";""ac""] Output: 1 Explanation: After deleting the first column; strs = [""a""; ""b""; ""c""]. Now strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]). We require at least 1 deletion since initially strs was not in lexicographic order; so the answer is 1. Example 2: Input: strs = [""xc"";""yb"";""za""] Output: 0 Explanation: strs is already in lexicographic order; so we do not need to delete anything. Note that the rows of strs are not necessarily in lexicographic order: i.e.; it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...) Example 3: Input: strs = [""zyx"";""wvu"";""tsr""] Output: 3 Explanation: We have to delete every column. Constraints: n == strs.length 1 <= n <= 100 1 <= strs[i].length <= 100 strs[i] consists of lowercase English letters."617Google,1007,Minimum Domino Rotations For Equal Row,Med,"Backtracking, Breadth-First Search",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. Example 1: 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. Example 2: Input: n = 2; k = 1 Output: [10;12;21;23;32;34;43;45;54;56;65;67;76;78;87;89;98] Constraints: 2 <= n <= 9 0 <= k <= 9618Google,1143,Longest Common Subsequence,Med,"Array, Hash Table, Binary Search, Matrix, Counting",619Google,1148,Article Views I,Easy,"Array, Math",Given two numbers arr1 and arr2 in base -2; return the result of adding them together. Each number is given in array format: as an array of 0s and 1s; from most significant bit to least significant bit. For example; arr = [1;1;0;1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3. A number arr in array; format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1. Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros. Example 1: Input: arr1 = [1;1;1;1;1]; arr2 = [1;0;1] Output: [1;0;0;0;0] Explanation: arr1 represents 11; arr2 represents 5; the output represents 16. Example 2: Input: arr1 = [0]; arr2 = [0] Output: [0] Example 3: Input: arr1 = [0]; arr2 = [1] Output: [1] Constraints: 1 <= arr1.length; arr2.length <= 1000 arr1[i] and arr2[i] are 0 or 1 arr1 and arr2 have no leading zeros620Google,1310,XOR Queries of a Subarray,Med,"Array, Simulation",You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. There is a river at x = -1 that you can refill your watering can at. Each plant needs a specific amount of water. You will water the plants in the following way: Water the plants in order from left to right. After watering the current plant; if you do not have enough water to completely water the next plant; return to the river to fully refill the watering can. You cannot refill the watering can early. You are initially at the river (i.e.; x = -1). It takes one step to move one unit on the x-axis. Given a 0-indexed integer array plants of n integers; where plants[i] is the amount of water the ith plant needs; and an integer capacity representing the watering can capacity; return the number of steps needed to water all the plants. Example 1: Input: plants = [2;2;3;3]; capacity = 5 Output: 14 Explanation: Start at the river with a full watering can: - Walk to plant 0 (1 step) and water it. Watering can has 3 units of water. - Walk to plant 1 (1 step) and water it. Watering can has 1 unit of water. - Since you cannot completely water plant 2; walk back to the river to refill (2 steps). - Walk to plant 2 (3 steps) and water it. Watering can has 2 units of water. - Since you cannot completely water plant 3; walk back to the river to refill (3 steps). - Walk to plant 3 (4 steps) and water it. Steps needed = 1 + 1 + 2 + 3 + 3 + 4 = 14. Example 2: Input: plants = [1;1;1;4;2;3]; capacity = 4 Output: 30 Explanation: Start at the river with a full watering can: - Water plants 0; 1; and 2 (3 steps). Return to river (3 steps). - Water plant 3 (4 steps). Return to river (4 steps). - Water plant 4 (5 steps). Return to river (5 steps). - Water plant 5 (6 steps). Steps needed = 3 + 3 + 4 + 4 + 5 + 5 + 6 = 30. Example 3: Input: plants = [7;7;7;7;7;7;7]; capacity = 8 Output: 49 Explanation: You have to refill before watering each plant. Steps needed = 1 + 1 + 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 + 7 = 49. Constraints: n == plants.length 1 <= n <= 1000 1 <= plants[i] <= 106 max(plants[i]) <= capacity <= 109621Google,1581,Customer Who Visited but Did Not Make Any Transactions,Easy,"Array, Two Pointers, Sorting",Given an array of integers arr and an integer k. A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array. If |arr[i] - m| == |arr[j] - m|; then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j]. Return a list of the strongest k values in the array. return the answer in any arbitrary order. Median is the middle value in an ordered integer list. More formally; if the length of the list is n; the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed). For arr = [6; -3; 7; 2; 11]; n = 5 and the median is obtained by sorting the array arr = [-3; 2; 6; 7; 11] and the median is arr[m] where m = ((5 - 1) / 2) = 2. The median is 6. For arr = [-7; 22; 17; 3]; n = 4 and the median is obtained by sorting the array arr = [-7; 3; 17; 22] and the median is arr[m] where m = ((4 - 1) / 2) = 1. The median is 3. Example 1: Input: arr = [1;2;3;4;5]; k = 2 Output: [5;1] Explanation: Median is 3; the elements of the array sorted by the strongest are [5;1;4;2;3]. The strongest 2 elements are [5; 1]. [1; 5] is also accepted answer. Please note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1. Example 2: Input: arr = [1;1;3;5;5]; k = 2 Output: [5;5] Explanation: Median is 3; the elements of the array sorted by the strongest are [5;5;1;1;3]. The strongest 2 elements are [5; 5]. Example 3: Input: arr = [6;7;11;7;6;8]; k = 5 Output: [11;8;6;6;7] Explanation: Median is 7; the elements of the array sorted by the strongest are [11;8;6;6;7;7]. Any permutation of [11;8;6;6;7] is accepted. Constraints: 1 <= arr.length <= 105 -105 <= arr[i] <= 105 1 <= k <= arr.length622Google,1684,Count the Number of Consistent Strings,Easy,"Array, Hash Table, Binary Search, Simulation","Given an array arr that represents a permutation of numbers from 1 to n. You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n; the bit at position arr[i] is set to 1. You are also given an integer m. Find the latest step at which there exists a group of ones of length m. A group of ones is a contiguous substring of 1's such that it cannot be extended in either direction. Return the latest step at which there exists a group of ones of length exactly m. If no such group exists; return -1. Example 1: Input: arr = [3;5;1;2;4]; m = 1 Output: 4 Explanation: Step 1: ""00100""; groups: [""1""] Step 2: ""00101""; groups: [""1""; ""1""] Step 3: ""10101""; groups: [""1""; ""1""; ""1""] Step 4: ""11101""; groups: [""111""; ""1""] Step 5: ""11111""; groups: [""11111""] The latest step at which there exists a group of size 1 is step 4. Example 2: Input: arr = [3;1;5;4;2]; m = 2 Output: -1 Explanation: Step 1: ""00100""; groups: [""1""] Step 2: ""10100""; groups: [""1""; ""1""] Step 3: ""10101""; groups: [""1""; ""1""; ""1""] Step 4: ""10111""; groups: [""1""; ""111""] Step 5: ""11111""; groups: [""11111""] No group of size 2 exists during any step. Constraints: n == arr.length 1 <= m <= n <= 105 1 <= arr[i] <= n All integers in arr are distinct."623Google,1752,Check if Array Is Sorted and Rotated,Easy,"Array, Hash Table, Sorting",A sequence of numbers is called arithmetic if it consists of at least two elements; and the difference between every two consecutive elements is the same. More formally; a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i. For example; these are arithmetic sequences: 1; 3; 5; 7; 9 7; 7; 7; 7 3; -1; -5; -9 The following sequence is not arithmetic: 1; 1; 2; 5; 7 You are given an array of n integers; nums; and two arrays of m integers each; l and r; representing the m range queries; where the ith query is the range [l[i]; r[i]]. All the arrays are 0-indexed. Return a list of boolean elements answer; where answer[i] is true if the subarray nums[l[i]]; nums[l[i]+1]; ... ; nums[r[i]] can be rearranged to form an arithmetic sequence; and false otherwise. Example 1: Input: nums = [4;6;5;9;3;7]; l = [0;0;2]; r = [2;3;5] Output: [true;false;true] Explanation: In the 0th query; the subarray is [4;6;5]. This can be rearranged as [6;5;4]; which is an arithmetic sequence. In the 1st query; the subarray is [4;6;5;9]. This cannot be rearranged as an arithmetic sequence. In the 2nd query; the subarray is [5;9;3;7]. This can be rearranged as [3;5;7;9]; which is an arithmetic sequence. Example 2: Input: nums = [-12;-9;-3;-12;-6;15;20;-25;-20;-15;-10]; l = [0;1;6;4;8;7]; r = [4;4;9;7;9;10] Output: [false;true;false;false;true;true] Constraints: n == nums.length m == l.length m == r.length 2 <= n <= 500 1 <= m <= 500 0 <= l[i] < r[i] < n -105 <= nums[i] <= 105624Google,1903,Largest Odd Number in String,Easy,"Array, Hash Table, Stack, Design, Binary Indexed Tree, Ordered Set",625Google,2035,Partition Array Into Two Arrays to Minimize Sum Difference,Hard,"Array, Depth-First Search, Breadth-First Search, Union Find, Matrix",You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2. Return the number of islands in grid2 that are considered sub-islands. Example 1: Input: grid1 = [[1;1;1;0;0];[0;1;1;1;1];[0;0;0;0;0];[1;0;0;0;0];[1;1;0;1;1]]; grid2 = [[1;1;1;0;0];[0;0;1;1;1];[0;1;0;0;0];[1;0;1;1;0];[0;1;0;1;0]] Output: 3 Explanation: In the picture above; the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands. Example 2: Input: grid1 = [[1;0;1;0;1];[1;1;1;1;1];[0;0;0;0;0];[1;1;1;1;1];[1;0;1;0;1]]; grid2 = [[0;0;0;0;0];[1;1;1;1;1];[0;1;0;1;0];[0;1;0;1;0];[1;0;0;0;1]] Output: 2 Explanation: In the picture above; the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands. Constraints: m == grid1.length == grid2.length n == grid1[i].length == grid2[i].length 1 <= m; n <= 500 grid1[i][j] and grid2[i][j] are either 0 or 1.626Google,2070,Most Beautiful Item for Each Query,Med,String,627Google,2064,Minimized Maximum of Products Distributed to Any Store,Med,Database,628Google,2641,Cousins in Binary Tree II,Med,"Array, Dynamic Programming, Depth-First Search, Breadth-First Search, Matrix",You are given a 0-indexed m x n binary matrix grid. You can move from a cell (row; col) to any of the cells (row + 1; col) or (row; col + 1) that has the value 1. The matrix is disconnected if there is no path from (0; 0) to (m - 1; n - 1). You can flip the value of at most one (possibly none) cell. You cannot flip the cells (0; 0) and (m - 1; n - 1). Return true if it is possible to make the matrix disconnect or false otherwise. Note that flipping a cell changes its value from 0 to 1 or from 1 to 0. Example 1: Input: grid = [[1;1;1];[1;0;0];[1;1;1]] Output: true Explanation: We can change the cell shown in the diagram above. There is no path from (0; 0) to (2; 2) in the resulting grid. Example 2: Input: grid = [[1;1;1];[1;0;1];[1;1;1]] Output: false Explanation: It is not possible to change at most one cell such that there is not path from (0; 0) to (2; 2). Constraints: m == grid.length n == grid[i].length 1 <= m; n <= 1000 1 <= m * n <= 105 grid[i][j] is either 0 or 1. grid[0][0] == grid[m - 1][n - 1] == 1629Google,2563,Count the Number of Fair Pairs,Med,"String, Binary Search","You are given a string; message; and a positive integer; limit. You must split message into one or more parts based on limit. Each resulting part should have the suffix ""<a/b>""; where ""b"" is to be replaced with the total number of parts and ""a"" is to be replaced with the index of the part; starting from 1 and going up to b. Additionally; the length of each resulting part (including its suffix) should be equal to limit; except for the last part whose length can be at most limit. The resulting parts should be formed such that when their suffixes are removed and they are all concatenated in order; they should be equal to message. Also; the result should contain as few parts as possible. Return the parts message would be split into as an array of strings. If it is impossible to split message as required; return an empty array. Example 1: Input: message = ""this is really a very awesome message""; limit = 9 Output: [""thi<1/14>"";""s i<2/14>"";""s r<3/14>"";""eal<4/14>"";""ly <5/14>"";""a v<6/14>"";""ery<7/14>"";"" aw<8/14>"";""eso<9/14>"";""me<10/14>"";"" m<11/14>"";""es<12/14>"";""sa<13/14>"";""ge<14/14>""] Explanation: The first 9 parts take 3 characters each from the beginning of message. The next 5 parts take 2 characters each to finish splitting message. In this example; each part; including the last; has length 9. It can be shown it is not possible to split message into less than 14 parts. Example 2: Input: message = ""short message""; limit = 15 Output: [""short mess<1/2>"";""age<2/2>""] Explanation: Under the given constraints; the string can be split into two parts: - The first part comprises of the first 10 characters; and has a length 15. - The next part comprises of the last 3 characters; and has a length 8. Constraints: 1 <= message.length <= 104 message consists only of lowercase English letters and ' '. 1 <= limit <= 104"630Google,2635,Apply Transform Over Each Element in Array,Easy,"Math, Number Theory",There exists an infinitely large grid. You are currently at point (1; 1); and you need to reach the point (targetX; targetY) using a finite number of steps. In one step; you can move from point (x; y) to any one of the following points: (x; y - x) (x - y; y) (2 * x; y) (x; 2 * y) Given two integers targetX and targetY representing the X-coordinate and Y-coordinate of your final position; return true if you can reach the point from (1; 1) using some number of steps; and false otherwise. Example 1: Input: targetX = 6; targetY = 9 Output: false Explanation: It is impossible to reach (6;9) from (1;1) using any sequence of moves; so false is returned. Example 2: Input: targetX = 4; targetY = 7 Output: true Explanation: You can follow the path (1;1) -> (1;2) -> (1;4) -> (1;8) -> (1;7) -> (2;7) -> (4;7). Constraints: 1 <= targetX; targetY <= 109631Google,2938,Separate Black and White Balls,Med,,632Google,3043,Find the Length of the Longest Common Prefix,Med,"Array, Breadth-First Search, Matrix",633Google,3163,String Compression III,Med,"Array, Hash Table",You are given a 0-indexed integer array nums. The distinct count of a subarray of nums is defined as: Let nums[i..j] be a subarray of nums consisting of all the indices from i to j such that 0 <= i <= j < nums.length. Then the number of distinct values in nums[i..j] is called the distinct count of nums[i..j]. Return the sum of the squares of distinct counts of all subarrays of nums. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: nums = [1;2;1] Output: 15 Explanation: Six possible subarrays are: [1]: 1 distinct value [2]: 1 distinct value [1]: 1 distinct value [1;2]: 2 distinct values [2;1]: 2 distinct values [1;2;1]: 2 distinct values The sum of the squares of the distinct counts in all subarrays is equal to 12 + 12 + 12 + 22 + 22 + 22 = 15. Example 2: Input: nums = [1;1] Output: 3 Explanation: Three possible subarrays are: [1]: 1 distinct value [1]: 1 distinct value [1;1]: 1 distinct value The sum of the squares of the distinct counts in all subarrays is equal to 12 + 12 + 12 = 3. Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 100634Google,3254,Find the Power of K-Size Subarrays I,Med,"Array, Hash Table",635Google,8,String to Integer (atoi),Med,String,"Implement the myAtoi(string s) function; which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: Whitespace: Ignore any leading whitespace ("" ""). Signedness: Determine the sign by checking if the next character is '-' or '+'; assuming positivity if neither present. Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read; then the result is 0. Rounding: If the integer is out of the 32-bit signed integer range [-231; 231 - 1]; then round the integer to remain in the range. Specifically; integers less than -231 should be rounded to -231; and integers greater than 231 - 1 should be rounded to 231 - 1. Return the integer as the final result. Example 1: Input: s = ""42"" Output: 42 Explanation: The underlined characters are what is read in and the caret is the current reader position. Step 1: ""42"" (no characters read because there is no leading whitespace) ^ Step 2: ""42"" (no characters read because there is neither a '-' nor '+') ^ Step 3: ""42"" (""42"" is read in) ^ Example 2: Input: s = "" -042"" Output: -42 Explanation: Step 1: "" -042"" (leading whitespace is read and ignored) ^ Step 2: "" -042"" ('-' is read; so the result should be negative) ^ Step 3: "" -042"" (""042"" is read in; leading zeros ignored in the result) ^ Example 3: Input: s = ""1337c0d3"" Output: 1337 Explanation: Step 1: ""1337c0d3"" (no characters read because there is no leading whitespace) ^ Step 2: ""1337c0d3"" (no characters read because there is neither a '-' nor '+') ^ Step 3: ""1337c0d3"" (""1337"" is read in; reading stops because the next character is a non-digit) ^ Example 4: Input: s = ""0-1"" Output: 0 Explanation: Step 1: ""0-1"" (no characters read because there is no leading whitespace) ^ Step 2: ""0-1"" (no characters read because there is neither a '-' nor '+') ^ Step 3: ""0-1"" (""0"" is read in; reading stops because the next character is a non-digit) ^ Example 5: Input: s = ""words and 987"" Output: 0 Explanation: Reading stops at the first non-digit character 'w'. Constraints: 0 <= s.length <= 200 s consists of English letters (lower-case and upper-case); digits (0-9); ' '; '+'; '-'; and '.'."636Google,25,Reverse Nodes in k-Group,Hard,"Linked List, Recursion",Given the head of a linked list; reverse the nodes of the list k at a time; and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes; in the end; should remain as it is. You may not alter the values in the list's nodes; only nodes themselves may be changed. Example 1: Input: head = [1;2;3;4;5]; k = 2 Output: [2;1;4;3;5] Example 2: Input: head = [1;2;3;4;5]; k = 3 Output: [3;2;1;4;5] Constraints: The number of nodes in the list is n. 1 <= k <= n <= 5000 0 <= Node.val <= 1000 Follow-up: Can you solve the problem in O(1) extra memory space?637Google,40,Combination Sum II,Med,"Array, Backtracking",Given a collection of candidate numbers (candidates) and a target number (target); find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations. Example 1: Input: candidates = [10;1;2;7;6;1;5]; target = 8 Output: [ [1;1;6]; [1;2;5]; [1;7]; [2;6] ] Example 2: Input: candidates = [2;5;2;1;2]; target = 5 Output: [ [1;2;2]; [5] ] Constraints: 1 <= candidates.length <= 100 1 <= candidates[i] <= 50 1 <= target <= 30638Google,46,Permutations,Med,"Array, Backtracking",Given an array nums of distinct integers; return all the possible permutations. You can return the answer in any order. Example 1: Input: nums = [1;2;3] Output: [[1;2;3];[1;3;2];[2;1;3];[2;3;1];[3;1;2];[3;2;1]] Example 2: Input: nums = [0;1] Output: [[0;1];[1;0]] Example 3: Input: nums = [1] Output: [[1]] Constraints: 1 <= nums.length <= 6 -10 <= nums[i] <= 10 All the integers of nums are unique.639Google,51,N-Queens,Hard,"Array, Backtracking","The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n; return all distinct solutions to the n-queens puzzle. You may return the answer in any order. Each solution contains a distinct board configuration of the n-queens' placement; where 'Q' and '.' both indicate a queen and an empty space; respectively. Example 1: Input: n = 4 Output: [["".Q.."";""...Q"";""Q..."";""..Q.""];[""..Q."";""Q..."";""...Q"";"".Q..""]] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above Example 2: Input: n = 1 Output: [[""Q""]] Constraints: 1 <= n <= 9"640Google,64,Minimum Path Sum,Med,"Array, Dynamic Programming, Matrix",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. Example 1: 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. Example 2: Input: grid = [[1;2;3];[4;5;6]] Output: 12 Constraints: m == grid.length n == grid[i].length 1 <= m; n <= 200 0 <= grid[i][j] <= 200641Google,68,Text Justification,Hard,"Array, String, Simulation","Given an array of strings words and a width maxWidth; format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is; pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words; the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text; it should be left-justified; and no extra space is inserted between words. Note: A word is defined as a character sequence consisting of non-space characters only. Each word's length is guaranteed to be greater than 0 and not exceed maxWidth. The input array words contains at least one word. Example 1: Input: words = [""This""; ""is""; ""an""; ""example""; ""of""; ""text""; ""justification.""]; maxWidth = 16 Output: [ ""This is an""; ""example of text""; ""justification. "" ] Example 2: Input: words = [""What"";""must"";""be"";""acknowledgment"";""shall"";""be""]; maxWidth = 16 Output: [ ""What must be""; ""acknowledgment ""; ""shall be "" ] Explanation: Note that the last line is ""shall be "" instead of ""shall be""; because the last line must be left-justified instead of fully-justified. Note that the second line is also left-justified because it contains only one word. Example 3: Input: words = [""Science"";""is"";""what"";""we"";""understand"";""well"";""enough"";""to"";""explain"";""to"";""a"";""computer."";""Art"";""is"";""everything"";""else"";""we"";""do""]; maxWidth = 20 Output: [ ""Science is what we""; ""understand well""; ""enough to explain to""; ""a computer. Art is""; ""everything else we""; ""do "" ] Constraints: 1 <= words.length <= 300 1 <= words[i].length <= 20 words[i] consists of only English letters and symbols. 1 <= maxWidth <= 100 words[i].length <= maxWidth"642Google,76,Minimum Window Substring,Hard,"Hash Table, String, Sliding Window","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. Example 1: Input: s = ""ADOBECODEBANC""; t = ""ABC"" Output: ""BANC"" Explanation: The minimum window substring ""BANC"" includes 'A'; 'B'; and 'C' from string t. Example 2: Input: s = ""a""; t = ""a"" Output: ""a"" Explanation: The entire string s is the minimum window. Example 3: Input: s = ""a""; t = ""aa"" Output: """" Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has one 'a'; return empty string. Constraints: m == s.length n == t.length 1 <= m; n <= 105 s and t consist of uppercase and lowercase English letters. Follow up: Could you find an algorithm that runs in O(m + n) time?"643Google,77,Combinations,Med,Backtracking,Given two integers n and k; return all possible combinations of k numbers chosen from the range [1; n]. You may return the answer in any order. Example 1: Input: n = 4; k = 2 Output: [[1;2];[1;3];[1;4];[2;3];[2;4];[3;4]] Explanation: There are 4 choose 2 = 6 total combinations. Note that combinations are unordered; i.e.; [1;2] and [2;1] are considered to be the same combination. Example 2: Input: n = 1; k = 1 Output: [[1]] Explanation: There is 1 choose 1 = 1 total combination. Constraints: 1 <= n <= 20 1 <= k <= n644Google,79,Word Search,Med,"Array, String, Backtracking, Matrix","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. Example 1: Input: board = [[""A"";""B"";""C"";""E""];[""S"";""F"";""C"";""S""];[""A"";""D"";""E"";""E""]]; word = ""ABCCED"" Output: true Example 2: Input: board = [[""A"";""B"";""C"";""E""];[""S"";""F"";""C"";""S""];[""A"";""D"";""E"";""E""]]; word = ""SEE"" Output: true Example 3: Input: board = [[""A"";""B"";""C"";""E""];[""S"";""F"";""C"";""S""];[""A"";""D"";""E"";""E""]]; word = ""ABCB"" Output: false Constraints: m == board.length n = board[i].length 1 <= m; n <= 6 1 <= word.length <= 15 board and word consists of only lowercase and uppercase English letters. Follow up: Could you use search pruning to make your solution faster with a larger board?"645Google,82,Remove Duplicates from Sorted List II,Med,"Linked List, Two Pointers",Given the head of a sorted linked list; delete all nodes that have duplicate numbers; leaving only distinct numbers from the original list. Return the linked list sorted as well. Example 1: Input: head = [1;2;3;3;4;4;5] Output: [1;2;5] Example 2: Input: head = [1;1;1;2;3] Output: [2;3] Constraints: The number of nodes in the list is in the range [0; 300]. -100 <= Node.val <= 100 The list is guaranteed to be sorted in ascending order.646Google,96,Unique Binary Search Trees,Med,"Math, Dynamic Programming, Tree, Binary Search Tree, Binary Tree",Given an integer n; return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n. Example 1: Input: n = 3 Output: 5 Example 2: Input: n = 1 Output: 1 Constraints: 1 <= n <= 19647Google,103,Binary Tree Zigzag Level Order Traversal,Med,"Tree, Breadth-First Search, Binary Tree",Given the root of a binary tree; return the zigzag level order traversal of its nodes' values. (i.e.; from left to right; then right to left for the next level and alternate between). Example 1: Input: root = [3;9;20;null;null;15;7] Output: [[3];[20;9];[15;7]] Example 2: Input: root = [1] Output: [[1]] Example 3: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0; 2000]. -100 <= Node.val <= 100648Google,104,Maximum Depth of Binary Tree,Easy,"Tree, Depth-First Search, Breadth-First Search, Binary Tree",Given the root of a binary tree; return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Example 1: Input: root = [3;9;20;null;null;15;7] Output: 3 Example 2: Input: root = [1;null;2] Output: 2 Constraints: The number of nodes in the tree is in the range [0; 104]. -100 <= Node.val <= 100649Google,119,Pascal's Triangle II,Easy,"Array, Dynamic Programming",Given an integer rowIndex; return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle; each number is the sum of the two numbers directly above it as shown: Example 1: Input: rowIndex = 3 Output: [1;3;3;1] Example 2: Input: rowIndex = 0 Output: [1] Example 3: Input: rowIndex = 1 Output: [1;1] Constraints: 0 <= rowIndex <= 33 Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space?650Google,145,Binary Tree Postorder Traversal,Easy,"Stack, Tree, Depth-First Search, Binary Tree",Given the root of a binary tree; return the postorder traversal of its nodes' values. Example 1: Input: root = [1;null;2;3] Output: [3;2;1] Explanation: Example 2: Input: root = [1;2;3;4;5;null;8;null;null;6;7;9] Output: [4;6;7;5;2;9;8;3;1] Explanation: Example 3: Input: root = [] Output: [] Example 4: Input: root = [1] Output: [1] Constraints: The number of the nodes in the tree is in the range [0; 100]. -100 <= Node.val <= 100 Follow up: Recursive solution is trivial; could you do it iteratively?651Google,151,Reverse Words in a String,Med,"Two Pointers, 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. Example 1: Input: s = ""the sky is blue"" Output: ""blue is sky the"" Example 2: Input: s = "" hello world "" Output: ""world hello"" Explanation: Your reversed string should not contain leading or trailing spaces. Example 3: 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. Constraints: 1 <= s.length <= 104 s contains English letters (upper-case and lower-case); digits; and spaces ' '. There is at least one word in s. Follow-up: If the string data type is mutable in your language; can you solve it in-place with O(1) extra space?"652Google,160,Intersection of Two Linked Lists,Easy,"Hash Table, Linked List, Two Pointers",Given the heads of two singly linked-lists headA and headB; return the node at which the two lists intersect. If the two linked lists have no intersection at all; return null. For example; the following two linked lists begin to intersect at node c1: The test cases are generated such that there are no cycles anywhere in the entire linked structure. Note that the linked lists must retain their original structure after the function returns. Custom Judge: The inputs to the judge are given as follows (your program is not given these inputs): intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node. listA - The first linked list. listB - The second linked list. skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node. skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node. The judge will then create the linked structure based on these inputs and pass the two heads; headA and headB to your program. If you correctly return the intersected node; then your solution will be accepted. Example 1: Input: intersectVal = 8; listA = [4;1;8;4;5]; listB = [5;6;1;8;4;5]; skipA = 2; skipB = 3 Output: Intersected at '8' Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A; it reads as [4;1;8;4;5]. From the head of B; it reads as [5;6;1;8;4;5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words; they point to two different locations in memory; while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory. Example 2: Input: intersectVal = 2; listA = [1;9;1;2;4]; listB = [3;2;4]; skipA = 3; skipB = 1 Output: Intersected at '2' Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A; it reads as [1;9;1;2;4]. From the head of B; it reads as [3;2;4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. Example 3: Input: intersectVal = 0; listA = [2;6;4]; listB = [1;5]; skipA = 3; skipB = 2 Output: No intersection Explanation: From the head of A; it reads as [2;6;4]. From the head of B; it reads as [1;5]. Since the two lists do not intersect; intersectVal must be 0; while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect; so return null. Constraints: The number of nodes of listA is in the m. The number of nodes of listB is in the n. 1 <= m; n <= 3 * 104 1 <= Node.val <= 105 0 <= skipA <= m 0 <= skipB <= n intersectVal is 0 if listA and listB do not intersect. intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect. Follow up: Could you write a solution that runs in O(m + n) time and use only O(1) memory?653Google,166,Fraction to Recurring Decimal,Med,"Hash Table, Math, String","Given two integers representing the numerator and denominator of a fraction; return the fraction in string format. If the fractional part is repeating; enclose the repeating part in parentheses. If multiple answers are possible; return any of them. It is guaranteed that the length of the answer string is less than 104 for all the given inputs. Example 1: Input: numerator = 1; denominator = 2 Output: ""0.5"" Example 2: Input: numerator = 2; denominator = 1 Output: ""2"" Example 3: Input: numerator = 4; denominator = 333 Output: ""0.(012)"" Constraints: -231 <= numerator; denominator <= 231 - 1 denominator != 0"654Google,168,Excel Sheet Column Title,Easy,"Math, String","Given an integer columnNumber; return its corresponding column title as it appears in an Excel sheet. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... Example 1: Input: columnNumber = 1 Output: ""A"" Example 2: Input: columnNumber = 28 Output: ""AB"" Example 3: Input: columnNumber = 701 Output: ""ZY"" Constraints: 1 <= columnNumber <= 231 - 1"655Google,175,Combine Two Tables,Easy,Database,Table: Person +-------------+---------+ | Column Name | Type | +-------------+---------+ | personId | int | | lastName | varchar | | firstName | varchar | +-------------+---------+ personId is the primary key (column with unique values) for this table. This table contains information about the ID of some persons and their first and last names. Table: Address +-------------+---------+ | Column Name | Type | +-------------+---------+ | addressId | int | | personId | int | | city | varchar | | state | varchar | +-------------+---------+ addressId is the primary key (column with unique values) for this table. Each row of this table contains information about the city and state of one person with ID = PersonId. Write a solution to report the first name; last name; city; and state of each person in the Person table. If the address of a personId is not present in the Address table; report null instead. Return the result table in any order. The result format is in the following example. Example 1: Input: Person table: +----------+----------+-----------+ | personId | lastName | firstName | +----------+----------+-----------+ | 1 | Wang | Allen | | 2 | Alice | Bob | +----------+----------+-----------+ Address table: +-----------+----------+---------------+------------+ | addressId | personId | city | state | +-----------+----------+---------------+------------+ | 1 | 2 | New York City | New York | | 2 | 3 | Leetcode | California | +-----------+----------+---------------+------------+ Output: +-----------+----------+---------------+----------+ | firstName | lastName | city | state | +-----------+----------+---------------+----------+ | Allen | Wang | Null | Null | | Bob | Alice | New York City | New York | +-----------+----------+---------------+----------+ Explanation: There is no address in the address table for the personId = 1 so we return null in their city and state. addressId = 1 contains information about the address of personId = 2.656Google,176,Second Highest Salary,Med,Database,Table: Employee +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | salary | int | +-------------+------+ id is the primary key (column with unique values) for this table. Each row of this table contains information about the salary of an employee. Write a solution to find the second highest distinct salary from the Employee table. If there is no second highest salary; return null (return None in Pandas). The result format is in the following example. Example 1: Input: Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+ Output: +---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+ Example 2: Input: Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | +----+--------+ Output: +---------------------+ | SecondHighestSalary | +---------------------+ | null | +---------------------+657Google,191,Number of 1 Bits,Easy,"Divide and Conquer, Bit Manipulation",Given a positive integer n; write a function that returns the number of set bits in its binary representation (also known as the Hamming weight). Example 1: Input: n = 11 Output: 3 Explanation: The input binary string 1011 has a total of three set bits. Example 2: Input: n = 128 Output: 1 Explanation: The input binary string 10000000 has a total of one set bit. Example 3: Input: n = 2147483645 Output: 30 Explanation: The input binary string 1111111111111111111111111111101 has a total of thirty set bits. Constraints: 1 <= n <= 231 - 1 Follow up: If this function is called many times; how would you optimize it?658Google,211,Design Add and Search Words Data Structure,Med,"String, Depth-First Search, Design, Trie","Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class: WordDictionary() Initializes the object. void addWord(word) Adds word to the data structure; it can be matched later. bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter. Example: Input [""WordDictionary"";""addWord"";""addWord"";""addWord"";""search"";""search"";""search"";""search""] [[];[""bad""];[""dad""];[""mad""];[""pad""];[""bad""];["".ad""];[""b..""]] Output [null;null;null;null;false;true;true;true] Explanation WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord(""bad""); wordDictionary.addWord(""dad""); wordDictionary.addWord(""mad""); wordDictionary.search(""pad""); // return False wordDictionary.search(""bad""); // return True wordDictionary.search("".ad""); // return True wordDictionary.search(""b..""); // return True Constraints: 1 <= word.length <= 25 word in addWord consists of lowercase English letters. word in search consist of '.' or lowercase English letters. There will be at most 2 dots in word for search queries. At most 104 calls will be made to addWord and search."659Google,213,House Robber II,Med,"Array, Dynamic Programming",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. Example 1: Input: nums = [2;3;2] Output: 3 Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2); because they are adjacent houses. Example 2: 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. Example 3: Input: nums = [1;2;3] Output: 3 Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 1000660Google,219,Contains Duplicate II,Easy,"Array, Hash Table, Sliding Window",Given an integer array nums and an integer k; return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k. Example 1: Input: nums = [1;2;3;1]; k = 3 Output: true Example 2: Input: nums = [1;0;1;1]; k = 1 Output: true Example 3: Input: nums = [1;2;3;1;2;3]; k = 2 Output: false Constraints: 1 <= nums.length <= 105 -109 <= nums[i] <= 109 0 <= k <= 105661Google,229,Majority Element II,Med,"Array, Hash Table, Sorting, Counting",Given an integer array of size n; find all elements that appear more than ⌊ n/3 ⌋ times. Example 1: Input: nums = [3;2;3] Output: [3] Example 2: Input: nums = [1] Output: [1] Example 3: Input: nums = [1;2] Output: [1;2] Constraints: 1 <= nums.length <= 5 * 104 -109 <= nums[i] <= 109 Follow up: Could you solve the problem in linear time and in O(1) space?662Google,235,Lowest Common Ancestor of a Binary Search Tree,Med,"Tree, Depth-First Search, Binary Search Tree, Binary Tree",Given a binary search tree (BST); find the lowest common ancestor (LCA) node of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Example 1: Input: root = [6;2;8;0;4;7;9;null;null;3;5]; p = 2; q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6. Example 2: Input: root = [6;2;8;0;4;7;9;null;null;3;5]; p = 2; q = 4 Output: 2 Explanation: The LCA of nodes 2 and 4 is 2; since a node can be a descendant of itself according to the LCA definition. Example 3: Input: root = [2;1]; p = 2; q = 1 Output: 2 Constraints: The number of nodes in the tree is in the range [2; 105]. -109 <= Node.val <= 109 All Node.val are unique. p != q p and q will exist in the BST.663Google,237,Delete Node in a Linked List,Med,Linked List,There is a singly-linked list head and we want to delete a node node in it. You are given the node to be deleted node. You will not be given access to the first node of head. All the values of the linked list are unique; and it is guaranteed that the given node node is not the last node in the linked list. Delete the given node. Note that by deleting the node; we do not mean removing it from memory. We mean: The value of the given node should not exist in the linked list. The number of nodes in the linked list should decrease by one. All the values before node should be in the same order. All the values after node should be in the same order. Custom testing: For the input; you should provide the entire linked list head and the node to be given node. node should not be the last node of the list and should be an actual node in the list. We will build the linked list and pass the node to your function. The output will be the entire list after calling your function. Example 1: Input: head = [4;5;1;9]; node = 5 Output: [4;1;9] Explanation: You are given the second node with value 5; the linked list should become 4 -> 1 -> 9 after calling your function. Example 2: Input: head = [4;5;1;9]; node = 1 Output: [4;5;9] Explanation: You are given the third node with value 1; the linked list should become 4 -> 5 -> 9 after calling your function. Constraints: The number of the nodes in the given list is in the range [2; 1000]. -1000 <= Node.val <= 1000 The value of each node in the list is unique. The node to be deleted is in the list and is not a tail node.664Google,241,Different Ways to Add Parentheses,Med,"Math, String, Dynamic Programming, Recursion, Memoization","Given a string expression of numbers and operators; return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order. The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 104. Example 1: Input: expression = ""2-1-1"" Output: [0;2] Explanation: ((2-1)-1) = 0 (2-(1-1)) = 2 Example 2: Input: expression = ""2*3-4*5"" Output: [-34;-14;-10;-10;10] Explanation: (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 Constraints: 1 <= expression.length <= 20 expression consists of digits and the operator '+'; '-'; and '*'. All the integer values in the input expression are in the range [0; 99]. The integer values in the input expression do not have a leading '-' or '+' denoting the sign."665Google,268,Missing Number,Easy,"Array, Hash Table, Math, Binary Search, Bit Manipulation, Sorting",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. Example 1: 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. Example 2: Input: nums = [0;1] Output: 2 Explanation: n = 2 since there are 2 numbers; so all numbers are in the range [0;2]. 2 is the missing number in the range since it does not appear in nums. Example 3: Input: nums = [9;6;4;2;3;5;7;0;1] Output: 8 Explanation: n = 9 since there are 9 numbers; so all numbers are in the range [0;9]. 8 is the missing number in the range since it does not appear in nums. Constraints: n == nums.length 1 <= n <= 104 0 <= nums[i] <= n All the numbers of nums are unique. Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?666Google,269,Alien Dictionary,Hard,"Array, String, Depth-First Search, Breadth-First Search, Graph, Topological Sort",667Google,301,Remove Invalid Parentheses,Hard,"String, Backtracking, Breadth-First Search","Given a string s that contains parentheses and letters; remove the minimum number of invalid parentheses to make the input string valid. Return a list of unique strings that are valid with the minimum number of removals. You may return the answer in any order. Example 1: Input: s = ""()())()"" Output: [""(())()"";""()()()""] Example 2: Input: s = ""(a)())()"" Output: [""(a())()"";""(a)()()""] Example 3: Input: s = "")("" Output: [""""] Constraints: 1 <= s.length <= 25 s consists of lowercase English letters and parentheses '(' and ')'. There will be at most 20 parentheses in s."668Google,303,Range Sum Query - Immutable,Easy,"Array, Design, Prefix Sum","Given an integer array nums; handle multiple queries of the following type: Calculate the sum of the elements of nums between indices left and right inclusive where left <= right. Implement the NumArray class: NumArray(int[] nums) Initializes the object with the integer array nums. int sumRange(int left; int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]). Example 1: Input [""NumArray""; ""sumRange""; ""sumRange""; ""sumRange""] [[[-2; 0; 3; -5; 2; -1]]; [0; 2]; [2; 5]; [0; 5]] Output [null; 1; -1; -3] Explanation NumArray numArray = new NumArray([-2; 0; 3; -5; 2; -1]); numArray.sumRange(0; 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2; 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0; 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 Constraints: 1 <= nums.length <= 104 -105 <= nums[i] <= 105 0 <= left <= right < nums.length At most 104 calls will be made to sumRange."669Google,312,Burst Balloons,Hard,"Array, Dynamic Programming",You are given n balloons; indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons. If you burst the ith balloon; you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array; then treat it as if there is a balloon with a 1 painted on it. Return the maximum coins you can collect by bursting the balloons wisely. Example 1: Input: nums = [3;1;5;8] Output: 167 Explanation: nums = [3;1;5;8] --> [3;5;8] --> [3;8] --> [8] --> [] coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 Example 2: Input: nums = [1;5] Output: 10 Constraints: n == nums.length 1 <= n <= 300 0 <= nums[i] <= 100670Google,314,Binary Tree Vertical Order Traversal,Med,"Hash Table, Tree, Depth-First Search, Breadth-First Search, Sorting, Binary Tree",671Google,318,Maximum Product of Word Lengths,Med,"Array, String, Bit Manipulation","Given a string array words; return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist; return 0. Example 1: Input: words = [""abcw"";""baz"";""foo"";""bar"";""xtfn"";""abcdef""] Output: 16 Explanation: The two words can be ""abcw""; ""xtfn"". Example 2: Input: words = [""a"";""ab"";""abc"";""d"";""cd"";""bcd"";""abcd""] Output: 4 Explanation: The two words can be ""ab""; ""cd"". Example 3: Input: words = [""a"";""aa"";""aaa"";""aaaa""] Output: 0 Explanation: No such pair of words. Constraints: 2 <= words.length <= 1000 1 <= words[i].length <= 1000 words[i] consists only of lowercase English letters."672Google,322,Coin Change,Med,"Array, Dynamic Programming, Breadth-First Search",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. Example 1: Input: coins = [1;2;5]; amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1 Example 2: Input: coins = [2]; amount = 3 Output: -1 Example 3: Input: coins = [1]; amount = 0 Output: 0 Constraints: 1 <= coins.length <= 12 1 <= coins[i] <= 231 - 1 0 <= amount <= 104673Google,341,Flatten Nested List Iterator,Med,"Stack, Tree, Depth-First Search, Design, Queue, Iterator",You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. Implement the NestedIterator class: NestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested list nestedList. int next() Returns the next integer in the nested list. boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise. Your code will be tested with the following pseudocode: initialize iterator with nestedList res = [] while iterator.hasNext() append iterator.next() to the end of res return res If res matches the expected flattened list; then your code will be judged as correct. Example 1: Input: nestedList = [[1;1];2;[1;1]] Output: [1;1;2;1;1] Explanation: By calling next repeatedly until hasNext returns false; the order of elements returned by next should be: [1;1;2;1;1]. Example 2: Input: nestedList = [1;[4;[6]]] Output: [1;4;6] Explanation: By calling next repeatedly until hasNext returns false; the order of elements returned by next should be: [1;4;6]. Constraints: 1 <= nestedList.length <= 500 The values of the integers in the nested list is in the range [-106; 106].674Google,350,Intersection of Two Arrays II,Easy,"Array, Hash Table, Two Pointers, Binary Search, Sorting",Given two integer arrays nums1 and nums2; return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order. Example 1: Input: nums1 = [1;2;2;1]; nums2 = [2;2] Output: [2;2] Example 2: Input: nums1 = [4;9;5]; nums2 = [9;4;9;8;4] Output: [4;9] Explanation: [9;4] is also accepted. Constraints: 1 <= nums1.length; nums2.length <= 1000 0 <= nums1[i]; nums2[i] <= 1000 Follow up: What if the given array is already sorted? How would you optimize your algorithm? What if nums1's size is small compared to nums2's size? Which algorithm is better? What if elements of nums2 are stored on disk; and the memory is limited such that you cannot load all elements into the memory at once?675Google,351,Android Unlock Patterns,Med,"Dynamic Programming, Backtracking, Bit Manipulation, Bitmask",676Google,362,Design Hit Counter,Med,"Array, Binary Search, Design, Queue, Data Stream",677Google,366,Find Leaves of Binary Tree,Med,"Tree, Depth-First Search, Binary Tree",678Google,377,Combination Sum IV,Med,"Array, Dynamic Programming",Given an array of distinct integers nums and a target integer target; return the number of possible combinations that add up to target. The test cases are generated so that the answer can fit in a 32-bit integer. Example 1: Input: nums = [1;2;3]; target = 4 Output: 7 Explanation: The possible combination ways are: (1; 1; 1; 1) (1; 1; 2) (1; 2; 1) (1; 3) (2; 1; 1) (2; 2) (3; 1) Note that different sequences are counted as different combinations. Example 2: Input: nums = [9]; target = 3 Output: 0 Constraints: 1 <= nums.length <= 200 1 <= nums[i] <= 1000 All the elements of nums are unique. 1 <= target <= 1000 Follow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?679Google,382,Linked List Random Node,Med,"Linked List, Math, Reservoir Sampling, Randomized","Given a singly linked list; return a random node's value from the linked list. Each node must have the same probability of being chosen. Implement the Solution class: Solution(ListNode head) Initializes the object with the head of the singly-linked list head. int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen. Example 1: Input [""Solution""; ""getRandom""; ""getRandom""; ""getRandom""; ""getRandom""; ""getRandom""] [[[1; 2; 3]]; []; []; []; []; []] Output [null; 1; 3; 2; 2; 3] Explanation Solution solution = new Solution([1; 2; 3]); solution.getRandom(); // return 1 solution.getRandom(); // return 3 solution.getRandom(); // return 2 solution.getRandom(); // return 2 solution.getRandom(); // return 3 // getRandom() should return either 1; 2; or 3 randomly. Each element should have equal probability of returning. Constraints: The number of nodes in the linked list will be in the range [1; 104]. -104 <= Node.val <= 104 At most 104 calls will be made to getRandom. Follow up: What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?"680Google,409,Longest Palindrome,Easy,"Hash Table, String, Greedy","Given a string s which consists of lowercase or uppercase letters; return the length of the longest palindrome that can be built with those letters. Letters are case sensitive; for example; ""Aa"" is not considered a palindrome. Example 1: Input: s = ""abccccdd"" Output: 7 Explanation: One longest palindrome that can be built is ""dccaccd""; whose length is 7. Example 2: Input: s = ""a"" Output: 1 Explanation: The longest palindrome that can be built is ""a""; whose length is 1. Constraints: 1 <= s.length <= 2000 s consists of lowercase and/or uppercase English letters only."681Google,451,Sort Characters By Frequency,Med,"Hash Table, String, Sorting, Heap (Priority Queue), Bucket Sort, Counting","Given a string s; sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. Return the sorted string. If there are multiple answers; return any of them. Example 1: Input: s = ""tree"" Output: ""eert"" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore ""eetr"" is also a valid answer. Example 2: Input: s = ""cccaaa"" Output: ""aaaccc"" Explanation: Both 'c' and 'a' appear three times; so both ""cccaaa"" and ""aaaccc"" are valid answers. Note that ""cacaca"" is incorrect; as the same characters must be together. Example 3: Input: s = ""Aabb"" Output: ""bbAa"" Explanation: ""bbaA"" is also a valid answer; but ""Aabb"" is incorrect. Note that 'A' and 'a' are treated as two different characters. Constraints: 1 <= s.length <= 5 * 105 s consists of uppercase and lowercase English letters and digits."682Google,453,Minimum Moves to Equal Array Elements,Med,"Array, Math",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. Example 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] Example 2: Input: nums = [1;1;1] Output: 0 Constraints: n == nums.length 1 <= nums.length <= 105 -109 <= nums[i] <= 109 The answer is guaranteed to fit in a 32-bit integer.683Google,493,Reverse Pairs,Hard,"Array, Binary Search, Divide and Conquer, Binary Indexed Tree, Segment Tree, Merge Sort, Ordered Set",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]. Example 1: 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 Example 2: Input: nums = [2;4;3;5;1] Output: 3 Explanation: The reverse pairs are: (1; 4) --> nums[1] = 4; nums[4] = 1; 4 > 2 * 1 (2; 4) --> nums[2] = 3; nums[4] = 1; 3 > 2 * 1 (3; 4) --> nums[3] = 5; nums[4] = 1; 5 > 2 * 1 Constraints: 1 <= nums.length <= 5 * 104 -231 <= nums[i] <= 231 - 1684Google,506,Relative Ranks,Easy,"Array, Sorting, Heap (Priority Queue)","You are given an integer array score of size n; where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique. The athletes are placed based on their scores; where the 1st place athlete has the highest score; the 2nd place athlete has the 2nd highest score; and so on. The placement of each athlete determines their rank: The 1st place athlete's rank is ""Gold Medal"". The 2nd place athlete's rank is ""Silver Medal"". The 3rd place athlete's rank is ""Bronze Medal"". For the 4th place to the nth place athlete; their rank is their placement number (i.e.; the xth place athlete's rank is ""x""). Return an array answer of size n where answer[i] is the rank of the ith athlete. Example 1: Input: score = [5;4;3;2;1] Output: [""Gold Medal"";""Silver Medal"";""Bronze Medal"";""4"";""5""] Explanation: The placements are [1st; 2nd; 3rd; 4th; 5th]. Example 2: Input: score = [10;3;8;9;4] Output: [""Gold Medal"";""5"";""Bronze Medal"";""Silver Medal"";""4""] Explanation: The placements are [1st; 5th; 3rd; 2nd; 4th]. Constraints: n == score.length 1 <= n <= 104 0 <= score[i] <= 106 All the values in score are unique."685Google,523,Continuous Subarray Sum,Med,"Array, Hash Table, Math, Prefix Sum",Given an integer array nums and an integer k; return true if nums has a good subarray or false otherwise. A good subarray is a subarray where: its length is at least two; and the sum of the elements of the subarray is a multiple of k. Note that: A subarray is a contiguous part of the array. 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. Example 1: 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. Example 2: Input: nums = [23;2;6;4;7]; k = 6 Output: true Explanation: [23; 2; 6; 4; 7] is an continuous subarray of size 5 whose elements sum up to 42. 42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer. Example 3: Input: nums = [23;2;6;4;7]; k = 13 Output: false Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 109 0 <= sum(nums[i]) <= 231 - 1 1 <= k <= 231 - 1686Google,577,Employee Bonus,Easy,Database,Table: Employee +-------------+---------+ | Column Name | Type | +-------------+---------+ | empId | int | | name | varchar | | supervisor | int | | salary | int | +-------------+---------+ empId is the column with unique values for this table. Each row of this table indicates the name and the ID of an employee in addition to their salary and the id of their manager. Table: Bonus +-------------+------+ | Column Name | Type | +-------------+------+ | empId | int | | bonus | int | +-------------+------+ empId is the column of unique values for this table. empId is a foreign key (reference column) to empId from the Employee table. Each row of this table contains the id of an employee and their respective bonus. Write a solution to report the name and bonus amount of each employee with a bonus less than 1000. Return the result table in any order. The result format is in the following example. Example 1: Input: Employee table: +-------+--------+------------+--------+ | empId | name | supervisor | salary | +-------+--------+------------+--------+ | 3 | Brad | null | 4000 | | 1 | John | 3 | 1000 | | 2 | Dan | 3 | 2000 | | 4 | Thomas | 3 | 4000 | +-------+--------+------------+--------+ Bonus table: +-------+-------+ | empId | bonus | +-------+-------+ | 2 | 500 | | 4 | 2000 | +-------+-------+ Output: +------+-------+ | name | bonus | +------+-------+ | Brad | null | | John | null | | Dan | 500 | +------+-------+687Google,605,Can Place Flowers,Easy,"Array, Greedy",You have a long flowerbed in which some of the plots are planted; and some are not. However; flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0's and 1's; where 0 means empty and 1 means not empty; and an integer n; return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise. Example 1: Input: flowerbed = [1;0;0;0;1]; n = 1 Output: true Example 2: Input: flowerbed = [1;0;0;0;1]; n = 2 Output: false Constraints: 1 <= flowerbed.length <= 2 * 104 flowerbed[i] is 0 or 1. There are no two adjacent flowers in flowerbed. 0 <= n <= flowerbed.length688Google,642,Design Search Autocomplete System,Hard,"String, Depth-First Search, Design, Trie, Sorting, Heap (Priority Queue), Data Stream",689Google,643,Maximum Average Subarray I,Easy,"Array, Sliding Window",You are given an integer array nums consisting of n elements; and an integer k. Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted. Example 1: Input: nums = [1;12;-5;-6;50;3]; k = 4 Output: 12.75000 Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 Example 2: Input: nums = [5]; k = 1 Output: 5.00000 Constraints: n == nums.length 1 <= k <= n <= 105 -104 <= nums[i] <= 104690Google,680,Valid Palindrome II,Easy,"Two Pointers, String, Greedy","Given a string s; return true if the s can be palindrome after deleting at most one character from it. Example 1: Input: s = ""aba"" Output: true Example 2: Input: s = ""abca"" Output: true Explanation: You could delete the character 'c'. Example 3: Input: s = ""abc"" Output: false Constraints: 1 <= s.length <= 105 s consists of lowercase English letters."691Google,681,Next Closest Time,Med,"Hash Table, String, Backtracking, Enumeration",692Google,713,Subarray Product Less Than K,Med,"Array, Binary Search, Sliding Window, Prefix Sum",Given an array of integers nums and an integer k; return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k. Example 1: Input: nums = [10;5;2;6]; k = 100 Output: 8 Explanation: The 8 subarrays that have product less than 100 are: [10]; [5]; [2]; [6]; [10; 5]; [5; 2]; [2; 6]; [5; 2; 6] Note that [10; 5; 2] is not included as the product of 100 is not strictly less than k. Example 2: Input: nums = [1;2;3]; k = 0 Output: 0 Constraints: 1 <= nums.length <= 3 * 104 1 <= nums[i] <= 1000 0 <= k <= 106693Google,590,N-ary Tree Postorder Traversal,Easy,,694Google,767,Reorganize String,Med,"Math, Bit Manipulation",Given two integers left and right; return the count of numbers in the inclusive range [left; right] having a prime number of set bits in their binary representation. Recall that the number of set bits an integer has is the number of 1's present when written in binary. For example; 21 written in binary is 10101; which has 3 set bits. Example 1: Input: left = 6; right = 10 Output: 4 Explanation: 6 -> 110 (2 set bits; 2 is prime) 7 -> 111 (3 set bits; 3 is prime) 8 -> 1000 (1 set bit; 1 is not prime) 9 -> 1001 (2 set bits; 2 is prime) 10 -> 1010 (2 set bits; 2 is prime) 4 numbers have a prime number of set bits. Example 2: Input: left = 10; right = 15 Output: 5 Explanation: 10 -> 1010 (2 set bits; 2 is prime) 11 -> 1011 (3 set bits; 3 is prime) 12 -> 1100 (2 set bits; 2 is prime) 13 -> 1101 (3 set bits; 3 is prime) 14 -> 1110 (3 set bits; 3 is prime) 15 -> 1111 (4 set bits; 4 is not prime) 5 numbers have a prime number of set bits. Constraints: 1 <= left <= right <= 106 0 <= right - left <= 104695Google,772,Basic Calculator III,Hard,"Array, Divide and Conquer, Tree, Matrix",Given a n * n matrix grid of 0's and 1's only. We want to represent grid with a Quad-Tree. Return the root of the Quad-Tree representing grid. A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides; each node has two attributes: val: True if the node represents a grid of 1's or False if the node represents a grid of 0's. Notice that you can assign the val to True or False when isLeaf is False; and both are accepted in the answer. isLeaf: True if the node is a leaf node on the tree or False if the node has four children. class Node { public boolean val; public boolean isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; } We can construct a Quad-Tree from a two-dimensional area using the following steps: If the current grid has the same value (i.e all 1's or all 0's) set isLeaf True and set val to the value of the grid and set the four children to Null and stop. If the current grid has different values; set isLeaf to False and set val to any value and divide the current grid into four sub-grids as shown in the photo. Recurse for each of the children with the proper sub-grid. If you want to know more about the Quad-Tree; you can refer to the wiki. Quad-Tree format: You don't need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal; where null signifies a path terminator where no node exists below. It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf; val]. If the value of isLeaf or val is True we represent it as 1 in the list [isLeaf; val] and if the value of isLeaf or val is False we represent it as 0. Example 1: Input: grid = [[0;1];[1;0]] Output: [[0;1];[1;0];[1;1];[1;1];[1;0]] Explanation: The explanation of this example is shown below: Notice that 0 represents False and 1 represents True in the photo representing the Quad-Tree. Example 2: Input: grid = [[1;1;1;1;0;0;0;0];[1;1;1;1;0;0;0;0];[1;1;1;1;1;1;1;1];[1;1;1;1;1;1;1;1];[1;1;1;1;0;0;0;0];[1;1;1;1;0;0;0;0];[1;1;1;1;0;0;0;0];[1;1;1;1;0;0;0;0]] Output: [[0;1];[1;1];[0;1];[1;1];[1;0];null;null;null;null;[1;0];[1;0];[1;1];[1;1]] Explanation: All values in the grid are not the same. We divide the grid into four sub-grids. The topLeft; bottomLeft and bottomRight each has the same value. The topRight have different values so we divide it into 4 sub-grids where each has the same value. Explanation is shown in the photo below: Constraints: n == grid.length == grid[i].length n == 2x where 0 <= x <= 6696Google,833,Find And Replace in String,Med,"Array, Hash Table, Breadth-First Search",You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever. For example; if routes[0] = [1; 5; 7]; this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever. You will start at the bus stop source (You are not on any bus initially); and you want to go to the bus stop target. You can travel between bus stops by buses only. Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible. Example 1: Input: routes = [[1;2;7];[3;6;7]]; source = 1; target = 6 Output: 2 Explanation: The best strategy is take the first bus to the bus stop 7; then take the second bus to the bus stop 6. Example 2: Input: routes = [[7;12];[4;5;15];[6];[15;19];[9;12;13]]; source = 15; target = 12 Output: -1 Constraints: 1 <= routes.length <= 500. 1 <= routes[i].length <= 105 All the values of routes[i] are unique. sum(routes[i].length) <= 105 0 <= routes[i][j] < 106 0 <= source; target < 106697Google,844,Backspace String Compare,Easy,,698Google,846,Hand of Straights,Med,,699Google,863,All Nodes Distance K in Binary Tree,Med,"Dynamic Programming, Tree, Depth-First Search, Graph",There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [ai; bi] indicates that there is an edge between nodes ai and bi in the tree. Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes. Example 1: Input: n = 6; edges = [[0;1];[0;2];[2;3];[2;4];[2;5]] Output: [8;12;6;10;10;10] Explanation: The tree is shown above. We can see that dist(0;1) + dist(0;2) + dist(0;3) + dist(0;4) + dist(0;5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence; answer[0] = 8; and so on. Example 2: Input: n = 1; edges = [] Output: [0] Example 3: Input: n = 2; edges = [[1;0]] Output: [1;1] Constraints: 1 <= n <= 3 * 104 edges.length == n - 1 edges[i].length == 2 0 <= ai; bi < n ai != bi The given input represents a valid tree.700Google,867,Transpose Matrix,Easy,"Math, Dynamic Programming, Sliding Window, Probability and Statistics","Alice plays the following game; loosely based on the card game ""21"". Alice starts with 0 points and draws numbers while she has less than k points. During each draw; she gains an integer number of points randomly from the range [1; maxPts]; where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities. Alice stops drawing numbers when she gets k or more points. Return the probability that Alice has n or fewer points. Answers within 10-5 of the actual answer are considered accepted. Example 1: Input: n = 10; k = 1; maxPts = 10 Output: 1.00000 Explanation: Alice gets a single card; then stops. Example 2: Input: n = 6; k = 1; maxPts = 10 Output: 0.60000 Explanation: Alice gets a single card; then stops. In 6 out of 10 possibilities; she is at or below 6 points. Example 3: Input: n = 21; k = 17; maxPts = 10 Output: 0.73278 Constraints: 0 <= k <= n <= 104 1 <= maxPts <= 104"701Google,876,Middle of the Linked List,Easy,"Array, Hash Table, Greedy, Sorting",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. Example 1: 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] Example 2: Input: hand = [1;2;3;4;5]; groupSize = 4 Output: false Explanation: Alice's hand can not be rearranged into groups of 4. Constraints: 1 <= hand.length <= 104 0 <= hand[i] <= 109 1 <= groupSize <= hand.length Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/702Google,904,Fruit Into Baskets,Med,"Tree, Depth-First Search, Binary Tree",Consider all the leaves of a binary tree; from left to right order; the values of those leaves form a leaf value sequence. For example; in the given tree above; the leaf value sequence is (6; 7; 4; 9; 8). Two binary trees are considered leaf-similar if their leaf value sequence is the same. Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar. Example 1: Input: root1 = [3;5;1;6;2;9;8;null;null;7;4]; root2 = [3;5;1;6;7;4;2;null;null;null;null;null;null;9;8] Output: true Example 2: Input: root1 = [1;2;3]; root2 = [1;3;2] Output: false Constraints: The number of nodes in each tree will be in the range [1; 200]. Both of the given trees will have values in the range [0; 200].703Google,905,Sort Array By Parity,Easy,"Array, Hash Table, Dynamic Programming",A sequence x1; x2; ...; xn is Fibonacci-like if: n >= 3 xi + xi+1 == xi+2 for all i + 2 <= n Given a strictly increasing array arr of positive integers forming a sequence; return the length of the longest Fibonacci-like subsequence of arr. If one does not exist; return 0. A subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr; without changing the order of the remaining elements. For example; [3; 5; 8] is a subsequence of [3; 4; 5; 6; 7; 8]. Example 1: Input: arr = [1;2;3;4;5;6;7;8] Output: 5 Explanation: The longest subsequence that is fibonacci-like: [1;2;3;5;8]. Example 2: Input: arr = [1;3;7;11;12;14;18] Output: 3 Explanation: The longest subsequence that is fibonacci-like: [1;11;12]; [3;11;14] or [7;11;18]. Constraints: 3 <= arr.length <= 1000 1 <= arr[i] < arr[i + 1] <= 109704Google,938,Range Sum of BST,Easy,"Array, Math, String, Binary Search, Dynamic Programming","Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example; if digits = ['1';'3';'5']; we may write numbers such as '13'; '551'; and '1351315'. Return the number of positive integers that can be generated that are less than or equal to a given integer n. Example 1: Input: digits = [""1"";""3"";""5"";""7""]; n = 100 Output: 20 Explanation: The 20 numbers that can be written are: 1; 3; 5; 7; 11; 13; 15; 17; 31; 33; 35; 37; 51; 53; 55; 57; 71; 73; 75; 77. Example 2: Input: digits = [""1"";""4"";""9""]; n = 1000000000 Output: 29523 Explanation: We can write 3 one digit numbers; 9 two digit numbers; 27 three digit numbers; 81 four digit numbers; 243 five digit numbers; 729 six digit numbers; 2187 seven digit numbers; 6561 eight digit numbers; and 19683 nine digit numbers. In total; this is 29523 integers that can be written using the digits array. Example 3: Input: digits = [""7""]; n = 8 Output: 1 Constraints: 1 <= digits.length <= 9 digits[i].length == 1 digits[i] is a digit from '1' to '9'. All the values in digits are unique. digits is sorted in non-decreasing order. 1 <= n <= 109"705Google,947,Most Stones Removed with Same Row or Column,Med,"Array, Hash Table, Binary Search, Design","You are given two integer arrays persons and times. In an election; the ith vote was cast for persons[i] at time times[i]. For each query at a time t; find the person that was leading the election at time t. Votes cast at time t will count towards our query. In the case of a tie; the most recent vote (among tied candidates) wins. Implement the TopVotedCandidate class: TopVotedCandidate(int[] persons; int[] times) Initializes the object with the persons and times arrays. int q(int t) Returns the number of the person that was leading the election at time t according to the mentioned rules. Example 1: Input [""TopVotedCandidate""; ""q""; ""q""; ""q""; ""q""; ""q""; ""q""] [[[0; 1; 1; 0; 0; 1; 0]; [0; 5; 10; 15; 20; 25; 30]]; [3]; [12]; [25]; [15]; [24]; [8]] Output [null; 0; 1; 1; 0; 0; 1] Explanation TopVotedCandidate topVotedCandidate = new TopVotedCandidate([0; 1; 1; 0; 0; 1; 0]; [0; 5; 10; 15; 20; 25; 30]); topVotedCandidate.q(3); // return 0; At time 3; the votes are [0]; and 0 is leading. topVotedCandidate.q(12); // return 1; At time 12; the votes are [0;1;1]; and 1 is leading. topVotedCandidate.q(25); // return 1; At time 25; the votes are [0;1;1;0;0;1]; and 1 is leading (as ties go to the most recent vote.) topVotedCandidate.q(15); // return 0 topVotedCandidate.q(24); // return 0 topVotedCandidate.q(8); // return 1 Constraints: 1 <= persons.length <= 5000 times.length == persons.length 0 <= persons[i] < persons.length 0 <= times[i] <= 109 times is sorted in a strictly increasing order. times[0] <= t <= 109 At most 104 calls will be made to q."706Google,977,Squares of a Sorted Array,Easy,"String, Dynamic Programming","Given a string s; return the number of distinct non-empty subsequences of s. Since the answer may be very large; return it modulo 109 + 7. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e.; ""ace"" is a subsequence of ""abcde"" while ""aec"" is not. Example 1: Input: s = ""abc"" Output: 7 Explanation: The 7 distinct subsequences are ""a""; ""b""; ""c""; ""ab""; ""ac""; ""bc""; and ""abc"". Example 2: Input: s = ""aba"" Output: 6 Explanation: The 6 distinct subsequences are ""a""; ""b""; ""ab""; ""aa""; ""ba""; and ""aba"". Example 3: Input: s = ""aaa"" Output: 3 Explanation: The 3 distinct subsequences are ""a""; ""aa"" and ""aaa"". Constraints: 1 <= s.length <= 2000 s consists of lowercase English letters."707Google,983,Minimum Cost For Tickets,Med,"Array, Stack, Simulation",Given two integer arrays pushed and popped each with distinct values; return true if this could have been the result of a sequence of push and pop operations on an initially empty stack; or false otherwise. Example 1: Input: pushed = [1;2;3;4;5]; popped = [4;5;3;2;1] Output: true Explanation: We might do the following sequence: push(1); push(2); push(3); push(4); pop() -> 4; push(5); pop() -> 5; pop() -> 3; pop() -> 2; pop() -> 1 Example 2: Input: pushed = [1;2;3;4;5]; popped = [4;3;5;1;2] Output: false Explanation: 1 cannot be popped before 2. Constraints: 1 <= pushed.length <= 1000 0 <= pushed[i] <= 1000 All the elements of pushed are unique. popped.length == pushed.length popped is a permutation of pushed.708Google,1004,Max Consecutive Ones III,Med,"Math, Dynamic Programming, Memoization","Given a single positive integer x; we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1; op2; etc. is either addition; subtraction; multiplication; or division (+; -; *; or /). For example; with x = 3; we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression; we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happen before addition and subtraction. It is not allowed to use the unary negation operator (-). For example; ""x - x"" is a valid expression as it only uses subtraction; but ""-x + x"" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used. Example 1: Input: x = 3; target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5; target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100; target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations. Constraints: 2 <= x <= 100 1 <= target <= 2 * 108"709Google,1057,Campus Bikes,Med,"Math, Dynamic Programming",Given an integer n; return the number of positive integers in the range [1; n] that have at least one repeated digit. Example 1: Input: n = 20 Output: 1 Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11. Example 2: Input: n = 100 Output: 10 Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11; 22; 33; 44; 55; 66; 77; 88; 99; and 100. Example 3: Input: n = 1000 Output: 262 Constraints: 1 <= n <= 109710Google,1046,Last Stone Weight,Easy,"Array, Binary Search, Sliding Window, Prefix Sum",Given a binary array nums and an integer k; return the maximum number of consecutive 1's in the array if you can flip at most k 0's. Example 1: Input: nums = [1;1;1;0;0;0;1;1;1;1;0]; k = 2 Output: 6 Explanation: [1;1;1;0;0;1;1;1;1;1;1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. Example 2: Input: nums = [0;0;1;1;0;0;1;1;1;0;1;1;0;0;0;1;1;1;1]; k = 3 Output: 10 Explanation: [0;0;1;1;1;1;1;1;1;1;1;1;0;0;0;1;1;1;1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. Constraints: 1 <= nums.length <= 105 nums[i] is either 0 or 1. 0 <= k <= nums.length711Google,1047,Remove All Adjacent Duplicates In String,Easy,"Array, Greedy, Sorting",Given an integer array nums and an integer k; modify the array in the following way: choose an index i and replace nums[i] with -nums[i]. You should apply this process exactly k times. You may choose the same index i multiple times. Return the largest possible sum of the array after modifying it in this way. Example 1: Input: nums = [4;2;3]; k = 1 Output: 5 Explanation: Choose index 1 and nums becomes [4;-2;3]. Example 2: Input: nums = [3;-1;0;2]; k = 3 Output: 6 Explanation: Choose indices (1; 2; 2) and nums becomes [3;1;0;2]. Example 3: Input: nums = [2;-3;-1;5;-4]; k = 2 Output: 13 Explanation: Choose indices (1; 4) and nums becomes [2;3;-1;5;4]. Constraints: 1 <= nums.length <= 104 -100 <= nums[i] <= 100 1 <= k <= 104712Google,1106,Parsing A Boolean Expression,Hard,"Array, Hash Table, Depth-First Search, Breadth-First Search",There is a 1 million by 1 million grid on an XY-plane; and the coordinates of each grid square are (x; y). We start at the source = [sx; sy] square and want to reach the target = [tx; ty] square. There is also an array of blocked squares; where each blocked[i] = [xi; yi] represents a blocked square with coordinates (xi; yi). Each move; we can walk one square north; east; south; or west if the square is not in the array of blocked squares. We are also not allowed to walk outside of the grid. Return true if and only if it is possible to reach the target square from the source square through a sequence of valid moves. Example 1: Input: blocked = [[0;1];[1;0]]; source = [0;0]; target = [0;2] Output: false Explanation: The target square is inaccessible starting from the source square because we cannot move. We cannot move north or east because those squares are blocked. We cannot move south or west because we cannot go outside of the grid. Example 2: Input: blocked = []; source = [0;0]; target = [999999;999999] Output: true Explanation: Because there are no blocked cells; it is possible to reach the target square. Constraints: 0 <= blocked.length <= 200 blocked[i].length == 2 0 <= xi; yi < 106 source.length == target.length == 2 0 <= sx; sy; tx; ty < 106 source != target It is guaranteed that source and target are not blocked.713Google,1146,Snapshot Array,Med,"Math, String","For two strings s and t; we say ""t divides s"" if and only if s = t + t + t + ... + t + t (i.e.; t is concatenated with itself one or more times). Given two strings str1 and str2; return the largest string x such that x divides both str1 and str2. Example 1: Input: str1 = ""ABCABC""; str2 = ""ABC"" Output: ""ABC"" Example 2: Input: str1 = ""ABABAB""; str2 = ""ABAB"" Output: ""AB"" Example 3: Input: str1 = ""LEET""; str2 = ""CODE"" Output: """" Constraints: 1 <= str1.length; str2.length <= 1000 str1 and str2 consist of English uppercase letters."714Google,1192,Critical Connections in a Network,Hard,"Array, Binary Search",715Google,1233,Remove Sub-Folders from the Filesystem,Med,"Array, Divide and Conquer, Interactive",716Google,2263,Make Array Non-decreasing or Non-increasing,Hard,"Array, Binary Search, Greedy, Sorting",You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Initially; you can insert at most one battery into each computer. After that and at any integer time moment; you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. Note that the batteries cannot be recharged. Return the maximum number of minutes you can run all the n computers simultaneously. Example 1: Input: n = 2; batteries = [3;3;3] Output: 4 Explanation: Initially; insert battery 0 into the first computer and battery 1 into the second computer. After two minutes; remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute. At the end of the third minute; battery 0 is drained; and you need to remove it from the first computer and insert battery 1 instead. By the end of the fourth minute; battery 1 is also drained; and the first computer is no longer running. We can run the two computers simultaneously for at most 4 minutes; so we return 4. Example 2: Input: n = 2; batteries = [1;1;1;1] Output: 2 Explanation: Initially; insert battery 0 into the first computer and battery 2 into the second computer. After one minute; battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer. After another minute; battery 1 and battery 3 are also drained so the first and second computers are no longer running. We can run the two computers simultaneously for at most 2 minutes; so we return 2. Constraints: 1 <= n <= batteries.length <= 105 1 <= batteries[i] <= 109717Google,1348,Tweet Counts Per Frequency,Med,"Array, Dynamic Programming",You are given two 0-indexed integer arrays nums1 and nums2; both of length n. You can choose two integers left and right where 0 <= left <= right < n and swap the subarray nums1[left...right] with the subarray nums2[left...right]. For example; if nums1 = [1;2;3;4;5] and nums2 = [11;12;13;14;15] and you choose left = 1 and right = 2; nums1 becomes [1;12;13;4;5] and nums2 becomes [11;2;3;14;15]. You may choose to apply the mentioned operation once or not do anything. The score of the arrays is the maximum of sum(nums1) and sum(nums2); where sum(arr) is the sum of all the elements in the array arr. Return the maximum possible score. A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right (inclusive). Example 1: Input: nums1 = [60;60;60]; nums2 = [10;90;10] Output: 210 Explanation: Choosing left = 1 and right = 1; we have nums1 = [60;90;60] and nums2 = [10;60;10]. The score is max(sum(nums1); sum(nums2)) = max(210; 80) = 210. Example 2: Input: nums1 = [20;40;20;70;30]; nums2 = [50;20;50;40;20] Output: 220 Explanation: Choosing left = 3; right = 4; we have nums1 = [20;40;20;40;20] and nums2 = [50;20;50;70;30]. The score is max(sum(nums1); sum(nums2)) = max(140; 220) = 220. Example 3: Input: nums1 = [7;11;13]; nums2 = [1;1;1] Output: 31 Explanation: We choose not to swap any subarray. The score is max(sum(nums1); sum(nums2)) = max(31; 3) = 31. Constraints: n == nums1.length == nums2.length 1 <= n <= 105 1 <= nums1[i]; nums2[i] <= 104718Google,1367,Linked List in Binary Tree,Med,"Array, Dynamic Programming, Sorting",Given n cuboids where the dimensions of the ith cuboid is cuboids[i] = [widthi; lengthi; heighti] (0-indexed). Choose a subset of cuboids and place them on each other. You can place cuboid i on cuboid j if widthi <= widthj and lengthi <= lengthj and heighti <= heightj. You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid. Return the maximum height of the stacked cuboids. Example 1: Input: cuboids = [[50;45;20];[95;37;53];[45;23;12]] Output: 190 Explanation: Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95. Cuboid 0 is placed next with the 45x20 side facing down with height 50. Cuboid 2 is placed next with the 23x12 side facing down with height 45. The total height is 95 + 50 + 45 = 190. Example 2: Input: cuboids = [[38;25;45];[76;35;3]] Output: 76 Explanation: You can't place any of the cuboids on the other. We choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76. Example 3: Input: cuboids = [[7;11;17];[7;17;11];[11;7;17];[11;17;7];[17;7;11];[17;11;7]] Output: 102 Explanation: After rearranging the cuboids; you can see that all cuboids have the same dimension. You can place the 11x7 side down on all cuboids so their heights are 17. The maximum height of stacked cuboids is 6 * 17 = 102. Constraints: n == cuboids.length 1 <= n <= 100 1 <= widthi; lengthi; heighti <= 100719Google,1438,Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit,Med,Database,720Google,1480,Running Sum of 1d Array,Easy,Database,"Table: Movies +---------------+---------+ | Column Name | Type | +---------------+---------+ | movie_id | int | | title | varchar | +---------------+---------+ movie_id is the primary key (column with unique values) for this table. title is the name of the movie. Table: Users +---------------+---------+ | Column Name | Type | +---------------+---------+ | user_id | int | | name | varchar | +---------------+---------+ user_id is the primary key (column with unique values) for this table. The column 'name' has unique values. Table: MovieRating +---------------+---------+ | Column Name | Type | +---------------+---------+ | movie_id | int | | user_id | int | | rating | int | | created_at | date | +---------------+---------+ (movie_id; user_id) is the primary key (column with unique values) for this table. This table contains the rating of a movie by a user in their review. created_at is the user's review date. Write a solution to: Find the name of the user who has rated the greatest number of movies. In case of a tie; return the lexicographically smaller user name. Find the movie name with the highest average rating in February 2020. In case of a tie; return the lexicographically smaller movie name. The result format is in the following example. Example 1: Input: Movies table: +-------------+--------------+ | movie_id | title | +-------------+--------------+ | 1 | Avengers | | 2 | Frozen 2 | | 3 | Joker | +-------------+--------------+ Users table: +-------------+--------------+ | user_id | name | +-------------+--------------+ | 1 | Daniel | | 2 | Monica | | 3 | Maria | | 4 | James | +-------------+--------------+ MovieRating table: +-------------+--------------+--------------+-------------+ | movie_id | user_id | rating | created_at | +-------------+--------------+--------------+-------------+ | 1 | 1 | 3 | 2020-01-12 | | 1 | 2 | 4 | 2020-02-11 | | 1 | 3 | 2 | 2020-02-12 | | 1 | 4 | 1 | 2020-01-01 | | 2 | 1 | 5 | 2020-02-17 | | 2 | 2 | 2 | 2020-02-01 | | 2 | 3 | 2 | 2020-03-01 | | 3 | 1 | 3 | 2020-02-22 | | 3 | 2 | 4 | 2020-02-25 | +-------------+--------------+--------------+-------------+ Output: +--------------+ | results | +--------------+ | Daniel | | Frozen 2 | +--------------+ Explanation: Daniel and Monica have rated 3 movies (""Avengers""; ""Frozen 2"" and ""Joker"") but Daniel is smaller lexicographically. Frozen 2 and Joker have a rating average of 3.5 in February but Frozen 2 is smaller lexicographically."721Google,1512,Number of Good Pairs,Easy,"Hash Table, String, Design","An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another. Implement the UndergroundSystem class: void checkIn(int id; string stationName; int t) A customer with a card ID equal to id; checks in at the station stationName at time t. A customer can only be checked into one place at a time. void checkOut(int id; string stationName; int t) A customer with a card ID equal to id; checks out from the station stationName at time t. double getAverageTime(string startStation; string endStation) Returns the average time it takes to travel from startStation to endStation. The average time is computed from all the previous traveling times from startStation to endStation that happened directly; meaning a check in at startStation followed by a check out from endStation. The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation. There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called. You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t1 then checks out at time t2; then t1 < t2. All events happen in chronological order. Example 1: Input [""UndergroundSystem"";""checkIn"";""checkIn"";""checkIn"";""checkOut"";""checkOut"";""checkOut"";""getAverageTime"";""getAverageTime"";""checkIn"";""getAverageTime"";""checkOut"";""getAverageTime""] [[];[45;""Leyton"";3];[32;""Paradise"";8];[27;""Leyton"";10];[45;""Waterloo"";15];[27;""Waterloo"";20];[32;""Cambridge"";22];[""Paradise"";""Cambridge""];[""Leyton"";""Waterloo""];[10;""Leyton"";24];[""Leyton"";""Waterloo""];[10;""Waterloo"";38];[""Leyton"";""Waterloo""]] Output [null;null;null;null;null;null;null;14.00000;11.00000;null;11.00000;null;12.00000] Explanation UndergroundSystem undergroundSystem = new UndergroundSystem(); undergroundSystem.checkIn(45; ""Leyton""; 3); undergroundSystem.checkIn(32; ""Paradise""; 8); undergroundSystem.checkIn(27; ""Leyton""; 10); undergroundSystem.checkOut(45; ""Waterloo""; 15); // Customer 45 ""Leyton"" -> ""Waterloo"" in 15-3 = 12 undergroundSystem.checkOut(27; ""Waterloo""; 20); // Customer 27 ""Leyton"" -> ""Waterloo"" in 20-10 = 10 undergroundSystem.checkOut(32; ""Cambridge""; 22); // Customer 32 ""Paradise"" -> ""Cambridge"" in 22-8 = 14 undergroundSystem.getAverageTime(""Paradise""; ""Cambridge""); // return 14.00000. One trip ""Paradise"" -> ""Cambridge""; (14) / 1 = 14 undergroundSystem.getAverageTime(""Leyton""; ""Waterloo""); // return 11.00000. Two trips ""Leyton"" -> ""Waterloo""; (10 + 12) / 2 = 11 undergroundSystem.checkIn(10; ""Leyton""; 24); undergroundSystem.getAverageTime(""Leyton""; ""Waterloo""); // return 11.00000 undergroundSystem.checkOut(10; ""Waterloo""; 38); // Customer 10 ""Leyton"" -> ""Waterloo"" in 38-24 = 14 undergroundSystem.getAverageTime(""Leyton""; ""Waterloo""); // return 12.00000. Three trips ""Leyton"" -> ""Waterloo""; (10 + 12 + 14) / 3 = 12 Example 2: Input [""UndergroundSystem"";""checkIn"";""checkOut"";""getAverageTime"";""checkIn"";""checkOut"";""getAverageTime"";""checkIn"";""checkOut"";""getAverageTime""] [[];[10;""Leyton"";3];[10;""Paradise"";8];[""Leyton"";""Paradise""];[5;""Leyton"";10];[5;""Paradise"";16];[""Leyton"";""Paradise""];[2;""Leyton"";21];[2;""Paradise"";30];[""Leyton"";""Paradise""]] Output [null;null;null;5.00000;null;null;5.50000;null;null;6.66667] Explanation UndergroundSystem undergroundSystem = new UndergroundSystem(); undergroundSystem.checkIn(10; ""Leyton""; 3); undergroundSystem.checkOut(10; ""Paradise""; 8); // Customer 10 ""Leyton"" -> ""Paradise"" in 8-3 = 5 undergroundSystem.getAverageTime(""Leyton""; ""Paradise""); // return 5.00000; (5) / 1 = 5 undergroundSystem.checkIn(5; ""Leyton""; 10); undergroundSystem.checkOut(5; ""Paradise""; 16); // Customer 5 ""Leyton"" -> ""Paradise"" in 16-10 = 6 undergroundSystem.getAverageTime(""Leyton""; ""Paradise""); // return 5.50000; (5 + 6) / 2 = 5.5 undergroundSystem.checkIn(2; ""Leyton""; 21); undergroundSystem.checkOut(2; ""Paradise""; 30); // Customer 2 ""Leyton"" -> ""Paradise"" in 30-21 = 9 undergroundSystem.getAverageTime(""Leyton""; ""Paradise""); // return 6.66667; (5 + 6 + 9) / 3 = 6.66667 Constraints: 1 <= id; t <= 106 1 <= stationName.length; startStation.length; endStation.length <= 10 All strings consist of uppercase and lowercase English letters and digits. There will be at most 2 * 104 calls in total to checkIn; checkOut; and getAverageTime. Answers within 10-5 of the actual value will be accepted."722Google,1593,Split a String Into the Max Number of Unique Substrings,Med,,723Google,1672,Richest Customer Wealth,Easy,"Array, Binary Search, Interactive",724Google,1661,Average Time of Process per Machine,Easy,Graph,Given a directed acyclic graph; with n vertices numbered from 0 to n-1; and an array edges where edges[i] = [fromi; toi] represents a directed edge from node fromi to node toi. Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists. Notice that you can return the vertices in any order. Example 1: Input: n = 6; edges = [[0;1];[0;2];[2;5];[3;4];[4;2]] Output: [0;3] Explanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0;1;2;5]. From 3 we can reach [3;4;2;5]. So we output [0;3]. Example 2: Input: n = 5; edges = [[0;1];[2;1];[3;1];[1;4];[2;4]] Output: [0;2;3] Explanation: Notice that vertices 0; 3 and 2 are not reachable from any other node; so we must include them. Also any of these vertices can reach nodes 1 and 4. Constraints: 2 <= n <= 10^5 1 <= edges.length <= min(10^5; n * (n - 1) / 2) edges[i].length == 2 0 <= fromi; toi < n All pairs (fromi; toi) are distinct.725Google,1696,Jump Game VI,Med,"Array, Graph, Topological Sort, Matrix",There is a strange printer with the following two special requirements: On each turn; the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle. Once the printer has used a color for the above operation; the same color cannot be used again. You are given a m x n matrix targetGrid; where targetGrid[row][col] is the color in the position (row; col) of the grid. Return true if it is possible to print the matrix targetGrid; otherwise; return false. Example 1: Input: targetGrid = [[1;1;1;1];[1;2;2;1];[1;2;2;1];[1;1;1;1]] Output: true Example 2: Input: targetGrid = [[1;1;1;1];[1;1;3;3];[1;1;3;4];[5;5;1;4]] Output: true Example 3: Input: targetGrid = [[1;2;1];[2;1;2];[1;2;1]] Output: false Explanation: It is impossible to form targetGrid because it is not allowed to print the same color in different turns. Constraints: m == targetGrid.length n == targetGrid[i].length 1 <= m; n <= 60 1 <= targetGrid[row][col] <= 60726Google,1743,Restore the Array From Adjacent Pairs,Med,"Hash Table, String, Dynamic Programming, Enumeration","Given two strings s and t; find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words; find the number of substrings in s that differ from some substring in t by exactly one character. For example; the underlined substrings in ""computer"" and ""computation"" only differ by the 'e'/'a'; so this is a valid way. Return the number of substrings that satisfy the condition above. A substring is a contiguous sequence of characters within a string. Example 1: Input: s = ""aba""; t = ""baba"" Output: 6 Explanation: The following are the pairs of substrings from s and t that differ by exactly 1 character: (""aba""; ""baba"") (""aba""; ""baba"") (""aba""; ""baba"") (""aba""; ""baba"") (""aba""; ""baba"") (""aba""; ""baba"") The underlined portions are the substrings that are chosen from s and t. ​​Example 2: Input: s = ""ab""; t = ""bb"" Output: 3 Explanation: The following are the pairs of substrings from s and t that differ by 1 character: (""ab""; ""bb"") (""ab""; ""bb"") (""ab""; ""bb"") ​​​​The underlined portions are the substrings that are chosen from s and t. Constraints: 1 <= s.length; t.length <= 100 s and t consist of lowercase English letters only."727Google,1834,Single-Threaded CPU,Med,"Array, Hash Table, Greedy",On a social network consisting of m users and some friendships between users; two users can communicate with each other if they know a common language. You are given an integer n; an array languages; and an array friendships where: There are n languages numbered 1 through n; languages[i] is the set of languages the i​​​​​​th​​​​ user knows; and friendships[i] = [u​​​​​​i​​​; v​​​​​​i] denotes a friendship between the users u​​​​​​​​​​​i​​​​​ and vi. You can choose one language and teach it to some users so that all friends can communicate with each other. Return the minimum number of users you need to teach. Note that friendships are not transitive; meaning if x is a friend of y and y is a friend of z; this doesn't guarantee that x is a friend of z. Example 1: Input: n = 2; languages = [[1];[2];[1;2]]; friendships = [[1;2];[1;3];[2;3]] Output: 1 Explanation: You can either teach user 1 the second language or user 2 the first language. Example 2: Input: n = 3; languages = [[2];[1;3];[1;2];[3]]; friendships = [[1;4];[1;2];[3;4];[2;3]] Output: 2 Explanation: Teach the third language to users 1 and 3; yielding two users to teach. Constraints: 2 <= n <= 500 languages.length == m 1 <= m <= 500 1 <= languages[i].length <= n 1 <= languages[i][j] <= n 1 <= u​​​​​​i < v​​​​​​i <= languages.length 1 <= friendships.length <= 500 All tuples (u​​​​​i; v​​​​​​i) are unique languages[i] contains only unique values728Google,1851,Minimum Interval to Include Each Query,Hard,"Array, Binary Search, Dynamic Programming, Sorting",You are given an array of events where events[i] = [startDayi; endDayi; valuei]. The ith event starts at startDayi and ends at endDayi; and if you attend this event; you will receive a value of valuei. You are also given an integer k which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event; you must attend the entire event. Note that the end day is inclusive: that is; you cannot attend two events where one of them starts and the other ends on the same day. Return the maximum sum of values that you can receive by attending events. Example 1: Input: events = [[1;2;4];[3;4;3];[2;3;1]]; k = 2 Output: 7 Explanation: Choose the green events; 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. Example 2: Input: events = [[1;2;4];[3;4;3];[2;3;10]]; k = 2 Output: 10 Explanation: Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap; and that you do not have to attend k events. Example 3: Input: events = [[1;1;1];[2;2;2];[3;3;3];[4;4;4]]; k = 3 Output: 9 Explanation: Although the events do not overlap; you can only attend 3 events. Pick the highest valued three. Constraints: 1 <= k <= events.length 1 <= k * events.length <= 106 1 <= startDayi <= endDayi <= 109 1 <= valuei <= 106729Google,1978,Employees Whose Manager Left the Company,Easy,"Two Pointers, String, Greedy","You are given a string num; representing a large integer; and an integer k. We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. There can be many wonderful integers. However; we only care about the smallest-valued ones. For example; when num = ""5489355142"": The 1st smallest wonderful integer is ""5489355214"". The 2nd smallest wonderful integer is ""5489355241"". The 3rd smallest wonderful integer is ""5489355412"". The 4th smallest wonderful integer is ""5489355421"". Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer. The tests are generated in such a way that kth smallest wonderful integer exists. Example 1: Input: num = ""5489355142""; k = 4 Output: 2 Explanation: The 4th smallest wonderful number is ""5489355421"". To get this number: - Swap index 7 with index 8: ""5489355142"" -> ""5489355412"" - Swap index 8 with index 9: ""5489355412"" -> ""5489355421"" Example 2: Input: num = ""11112""; k = 4 Output: 4 Explanation: The 4th smallest wonderful number is ""21111"". To get this number: - Swap index 3 with index 4: ""11112"" -> ""11121"" - Swap index 2 with index 3: ""11121"" -> ""11211"" - Swap index 1 with index 2: ""11211"" -> ""12111"" - Swap index 0 with index 1: ""12111"" -> ""21111"" Example 3: Input: num = ""00123""; k = 1 Output: 1 Explanation: The 1st smallest wonderful number is ""00132"". To get this number: - Swap index 3 with index 4: ""00123"" -> ""00132"" Constraints: 2 <= num.length <= 1000 1 <= k <= 1000 num only consists of digits."730Google,2022,Convert 1D Array Into 2D Array,Easy,"Array, Dynamic Programming",The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices. For example; the alternating sum of [4;2;5;3] is (4 + 5) - (2 + 3) = 4. Given an array nums; return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence). A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example; [2;7;4] is a subsequence of [4;2;3;7;2;1;4] (the underlined elements); while [2;4;2] is not. Example 1: Input: nums = [4;2;5;3] Output: 7 Explanation: It is optimal to choose the subsequence [4;2;5] with alternating sum (4 + 5) - 2 = 7. Example 2: Input: nums = [5;6;7;8] Output: 8 Explanation: It is optimal to choose the subsequence [8] with alternating sum 8. Example 3: Input: nums = [6;2;1;2;4;5] Output: 10 Explanation: It is optimal to choose the subsequence [6;1;5] with alternating sum (6 + 5) - 1 = 10. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 105731Google,2044,Count Number of Maximum Bitwise-OR Subsets,Med,"Hash Table, String, Bit Manipulation, Prefix Sum","A wonderful string is a string where at most one letter appears an odd number of times. For example; ""ccjjc"" and ""abab"" are wonderful; but ""ab"" is not. Given a string word that consists of the first ten lowercase English letters ('a' through 'j'); return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word; then count each occurrence separately. A substring is a contiguous sequence of characters in a string. Example 1: Input: word = ""aba"" Output: 4 Explanation: The four wonderful substrings are underlined below: - ""aba"" -> ""a"" - ""aba"" -> ""b"" - ""aba"" -> ""a"" - ""aba"" -> ""aba"" Example 2: Input: word = ""aabb"" Output: 9 Explanation: The nine wonderful substrings are underlined below: - ""aabb"" -> ""a"" - ""aabb"" -> ""aa"" - ""aabb"" -> ""aab"" - ""aabb"" -> ""aabb"" - ""aabb"" -> ""a"" - ""aabb"" -> ""abb"" - ""aabb"" -> ""b"" - ""aabb"" -> ""bb"" - ""aabb"" -> ""b"" Example 3: Input: word = ""he"" Output: 2 Explanation: The two wonderful substrings are underlined below: - ""he"" -> ""h"" - ""he"" -> ""e"" Constraints: 1 <= word.length <= 105 word consists of lowercase English letters from 'a' to 'j'."732Google,2115,Find All Possible Recipes from Given Supplies,Med,"String, Dynamic Programming","You are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of ""0""). Find the number of unique good subsequences of binary. For example; if binary = ""001""; then all the good subsequences are [""0""; ""0""; ""1""]; so the unique good subsequences are ""0"" and ""1"". Note that subsequences ""00""; ""01""; and ""001"" are not good because they have leading zeros. Return the number of unique good subsequences of binary. Since the answer may be very large; return it modulo 109 + 7. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. Example 1: Input: binary = ""001"" Output: 2 Explanation: The good subsequences of binary are [""0""; ""0""; ""1""]. The unique good subsequences are ""0"" and ""1"". Example 2: Input: binary = ""11"" Output: 2 Explanation: The good subsequences of binary are [""1""; ""1""; ""11""]. The unique good subsequences are ""1"" and ""11"". Example 3: Input: binary = ""101"" Output: 5 Explanation: The good subsequences of binary are [""1""; ""0""; ""1""; ""10""; ""11""; ""101""]. The unique good subsequences are ""0""; ""1""; ""10""; ""11""; and ""101"". Constraints: 1 <= binary.length <= 105 binary consists of only '0's and '1's."733Google,2220,Minimum Bit Flips to Convert Number,Easy,"Array, Hash Table, String, Graph, Topological Sort","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. Example 1: Input: recipes = [""bread""]; ingredients = [[""yeast"";""flour""]]; supplies = [""yeast"";""flour"";""corn""] Output: [""bread""] Explanation: We can create ""bread"" since we have the ingredients ""yeast"" and ""flour"". Example 2: Input: recipes = [""bread"";""sandwich""]; ingredients = [[""yeast"";""flour""];[""bread"";""meat""]]; supplies = [""yeast"";""flour"";""meat""] Output: [""bread"";""sandwich""] 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"". Example 3: 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"". Constraints: n == recipes.length == ingredients.length 1 <= n <= 100 1 <= ingredients[i].length; supplies.length <= 100 1 <= recipes[i].length; ingredients[i][j].length; supplies[k].length <= 10 recipes[i]; ingredients[i][j]; and supplies[k] consist only of lowercase English letters. All the values of recipes and supplies combined are unique. Each ingredients[i] does not contain any duplicate values."734Google,2275,Largest Combination With Bitwise AND Greater Than Zero,Med,"String, Sliding Window, Rolling Hash, Hash Function","The hash of a 0-indexed string s of length k; given integers p and m; is computed using the following function: hash(s; p; m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m. Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26. You are given a string s and the integers power; modulo; k; and hashValue. Return sub; the first substring of s of length k such that hash(sub; power; modulo) == hashValue. The test cases will be generated such that an answer always exists. A substring is a contiguous non-empty sequence of characters within a string. Example 1: Input: s = ""leetcode""; power = 7; modulo = 20; k = 2; hashValue = 0 Output: ""ee"" Explanation: The hash of ""ee"" can be computed to be hash(""ee""; 7; 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0. ""ee"" is the first substring of length 2 with hashValue 0. Hence; we return ""ee"". Example 2: Input: s = ""fbxzaad""; power = 31; modulo = 100; k = 3; hashValue = 32 Output: ""fbx"" Explanation: The hash of ""fbx"" can be computed to be hash(""fbx""; 31; 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32. The hash of ""bxz"" can be computed to be hash(""bxz""; 31; 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32. ""fbx"" is the first substring of length 3 with hashValue 32. Hence; we return ""fbx"". Note that ""bxz"" also has a hash of 32 but it appears later than ""fbx"". Constraints: 1 <= k <= s.length <= 2 * 104 1 <= power; modulo <= 109 0 <= hashValue < modulo s consists of lowercase English letters only. The test cases are generated such that an answer always exists."735Google,2284,Sender With Largest Word Count,Med,"Math, Sorting",You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros. Return the rearranged number with minimal value. Note that the sign of the number does not change after rearranging the digits. Example 1: Input: num = 310 Output: 103 Explanation: The possible arrangements for the digits of 310 are 013; 031; 103; 130; 301; 310. The arrangement with the smallest value that does not contain any leading zeros is 103. Example 2: Input: num = -7605 Output: -7650 Explanation: Some possible arrangements for the digits of -7605 are -7650; -6705; -5076; -0567. The arrangement with the smallest value that does not contain any leading zeros is -7650. Constraints: -1015 <= num <= 1015736Google,2326,Spiral Matrix IV,Med,"String, Binary Search, Rolling Hash, Suffix Array, String Matching, Hash Function","You are building a string s of length n one character at a time; prepending each new character to the front of the string. The strings are labeled from 1 to n; where the string with length i is labeled si. For example; for s = ""abaca""; s1 == ""a""; s2 == ""ca""; s3 == ""aca""; etc. The score of si is the length of the longest common prefix between si and sn (Note that s == sn). Given the final string s; return the sum of the score of every si. Example 1: Input: s = ""babab"" Output: 9 Explanation: For s1 == ""b""; the longest common prefix is ""b"" which has a score of 1. For s2 == ""ab""; there is no common prefix so the score is 0. For s3 == ""bab""; the longest common prefix is ""bab"" which has a score of 3. For s4 == ""abab""; there is no common prefix so the score is 0. For s5 == ""babab""; the longest common prefix is ""babab"" which has a score of 5. The sum of the scores is 1 + 0 + 3 + 0 + 5 = 9; so we return 9. Example 2: Input: s = ""azbazbzaz"" Output: 14 Explanation: For s2 == ""az""; the longest common prefix is ""az"" which has a score of 2. For s6 == ""azbzaz""; the longest common prefix is ""azb"" which has a score of 3. For s9 == ""azbazbzaz""; the longest common prefix is ""azbazbzaz"" which has a score of 9. For all other si; the score is 0. The sum of the scores is 2 + 3 + 9 = 14; so we return 14. Constraints: 1 <= s.length <= 105 s consists of lowercase English letters."737Google,2336,Smallest Number in Infinite Set,Med,Database,738Google,2402,Meeting Rooms III,Hard,"Array, Math, Bit Manipulation",You are given a 0-indexed integer array nums. In one operation; select any non-negative integer x and an index i; then update nums[i] to be equal to nums[i] AND (nums[i] XOR x). Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation. Return the maximum possible bitwise XOR of all elements of nums after applying the operation any number of times. Example 1: Input: nums = [3;2;4;6] Output: 7 Explanation: Apply the operation with x = 4 and i = 3; num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2. Now; nums = [3; 2; 4; 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7. It can be shown that 7 is the maximum possible bitwise XOR. Note that other operations may be used to achieve a bitwise XOR of 7. Example 2: Input: nums = [1;2;3;9;2] Output: 11 Explanation: Apply the operation zero times. The bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11. It can be shown that 11 is the maximum possible bitwise XOR. Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 108739Google,2406,Divide Intervals Into Minimum Number of Groups,Med,"Hash Table, String","You are given the strings key and message; which represent a cipher key and a secret message; respectively. The steps to decode message are as follows: Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table. Align the substitution table with the regular English alphabet. Each letter in message is then substituted using the table. Spaces ' ' are transformed to themselves. For example; given key = ""happy boy"" (actual key would have at least one instance of each letter in the alphabet); we have the partial substitution table of ('h' -> 'a'; 'a' -> 'b'; 'p' -> 'c'; 'y' -> 'd'; 'b' -> 'e'; 'o' -> 'f'). Return the decoded message. Example 1: Input: key = ""the quick brown fox jumps over the lazy dog""; message = ""vkbs bs t suepuv"" Output: ""this is a secret"" Explanation: The diagram above shows the substitution table. It is obtained by taking the first appearance of each letter in ""the quick brown fox jumps over the lazy dog"". Example 2: Input: key = ""eljuxhpwnyrdgtqkviszcfmabo""; message = ""zwx hnfx lqantp mnoeius ycgk vcnjrdb"" Output: ""the five boxing wizards jump quickly"" Explanation: The diagram above shows the substitution table. It is obtained by taking the first appearance of each letter in ""eljuxhpwnyrdgtqkviszcfmabo"". Constraints: 26 <= key.length <= 2000 key consists of lowercase English letters and ' '. key contains every letter in the English alphabet ('a' to 'z') at least once. 1 <= message.length <= 2000 message consists of lowercase English letters and ' '."740Google,2419,Longest Subarray With Maximum Bitwise AND,Med,"Array, Stack, Union Find, Monotonic Stack",You are given an integer array nums and an integer threshold. Find any subarray of nums of length k such that every element in the subarray is greater than threshold / k. Return the size of any such subarray. If there is no such subarray; return -1. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: nums = [1;3;4;3;1]; threshold = 6 Output: 3 Explanation: The subarray [3;4;3] has a size of 3; and every element is greater than 6 / 3 = 2. Note that this is the only valid subarray. Example 2: Input: nums = [6;5;6;5;8]; threshold = 7 Output: 1 Explanation: The subarray [8] has a size of 1; and 8 > 7 / 1 = 7. So 1 is returned. Note that the subarray [6;5] has a size of 2; and every element is greater than 7 / 2 = 3.5. Similarly; the subarrays [6;5;6]; [6;5;6;5]; [6;5;6;5;8] also satisfy the given conditions. Therefore; 2; 3; 4; or 5 may also be returned. Constraints: 1 <= nums.length <= 105 1 <= nums[i]; threshold <= 109741Google,2707,Extra Characters in a String,Med,"Array, Hash Table, Two Pointers",You are given two 2D integer arrays nums1 and nums2. nums1[i] = [idi; vali] indicate that the number with the id idi has a value equal to vali. nums2[i] = [idi; vali] indicate that the number with the id idi has a value equal to vali. Each array contains unique ids and is sorted in ascending order by id. Merge the two arrays into one array that is sorted in ascending order by id; respecting the following conditions: Only ids that appear in at least one of the two arrays should be included in the resulting array. Each id should be included only once and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays then its value in that array is considered to be 0. Return the resulting array. The returned array must be sorted in ascending order by id. Example 1: Input: nums1 = [[1;2];[2;3];[4;5]]; nums2 = [[1;4];[3;2];[4;1]] Output: [[1;6];[2;3];[3;2];[4;6]] Explanation: The resulting array contains the following: - id = 1; the value of this id is 2 + 4 = 6. - id = 2; the value of this id is 3. - id = 3; the value of this id is 2. - id = 4; the value of this id is 5 + 1 = 6. Example 2: Input: nums1 = [[2;4];[3;6];[5;5]]; nums2 = [[1;3];[4;3]] Output: [[1;3];[2;4];[3;6];[4;3];[5;5]] Explanation: There are no common ids; so we just include each id with its value in the resulting list. Constraints: 1 <= nums1.length; nums2.length <= 200 nums1[i].length == nums2[j].length == 2 1 <= idi; vali <= 1000 Both arrays contain unique ids. Both arrays are in strictly ascending order by id.742Google,2704,To Be Or Not To Be,Easy,"Math, Greedy",You are given an integer num. You know that Bob will sneakily remap one of the 10 possible digits (0 to 9) to another digit. Return the difference between the maximum and minimum values Bob can make by remapping exactly one digit in num. Notes: When Bob remaps a digit d1 to another digit d2; Bob replaces all occurrences of d1 in num with d2. Bob can remap a digit to itself; in which case num does not change. Bob can remap different digits for obtaining minimum and maximum values respectively. The resulting number after remapping can contain leading zeroes. Example 1: Input: num = 11891 Output: 99009 Explanation: To achieve the maximum value; Bob can remap the digit 1 to the digit 9 to yield 99899. To achieve the minimum value; Bob can remap the digit 1 to the digit 0; yielding 890. The difference between these two numbers is 99009. Example 2: Input: num = 90 Output: 99 Explanation: The maximum value that can be returned by the function is 99 (if 0 is replaced by 9) and the minimum value that can be returned by the function is 0 (if 9 is replaced by 0). Thus; we return 99. Constraints: 1 <= num <= 108743Google,3110,Score of a String,Easy,,744Google,3097,Shortest Subarray With OR at Least K II,Med,Database,745Google,3319,K-th Largest Perfect Subtree Size in Binary Tree,Med,,746Google,3286,Find a Safe Walk Through a Grid,Med,Database,747Google,30,Substring with Concatenation of All Words,Hard,"Hash Table, String, Sliding Window","You are given a string s and an array of strings words. All the strings of words are of the same length. A concatenated string is a string that exactly contains all the strings of any permutation of words concatenated. For example; if words = [""ab"";""cd"";""ef""]; then ""abcdef""; ""abefcd""; ""cdabef""; ""cdefab""; ""efabcd""; and ""efcdab"" are all concatenated strings. ""acdbef"" is not a concatenated string because it is not the concatenation of any permutation of words. Return an array of the starting indices of all the concatenated substrings in s. You can return the answer in any order. Example 1: Input: s = ""barfoothefoobarman""; words = [""foo"";""bar""] Output: [0;9] Explanation: The substring starting at 0 is ""barfoo"". It is the concatenation of [""bar"";""foo""] which is a permutation of words. The substring starting at 9 is ""foobar"". It is the concatenation of [""foo"";""bar""] which is a permutation of words. Example 2: Input: s = ""wordgoodgoodgoodbestword""; words = [""word"";""good"";""best"";""word""] Output: [] Explanation: There is no concatenated substring. Example 3: Input: s = ""barfoofoobarthefoobarman""; words = [""bar"";""foo"";""the""] Output: [6;9;12] Explanation: The substring starting at 6 is ""foobarthe"". It is the concatenation of [""foo"";""bar"";""the""]. The substring starting at 9 is ""barthefoo"". It is the concatenation of [""bar"";""the"";""foo""]. The substring starting at 12 is ""thefoobar"". It is the concatenation of [""the"";""foo"";""bar""]. Constraints: 1 <= s.length <= 104 1 <= words.length <= 5000 1 <= words[i].length <= 30 s and words[i] consist of lowercase English letters."748Google,44,Wildcard Matching,Hard,"String, Dynamic Programming, Greedy, Recursion","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). Example 1: Input: s = ""aa""; p = ""a"" Output: false Explanation: ""a"" does not match the entire string ""aa"". Example 2: Input: s = ""aa""; p = ""*"" Output: true Explanation: '*' matches any sequence. Example 3: Input: s = ""cb""; p = ""?a"" Output: false Explanation: '?' matches 'c'; but the second letter is 'a'; which does not match 'b'. Constraints: 0 <= s.length; p.length <= 2000 s contains only lowercase English letters. p contains only lowercase English letters; '?' or '*'."749Google,47,Permutations II,Med,"Array, Backtracking",Given a collection of numbers; nums; that might contain duplicates; return all possible unique permutations in any order. Example 1: Input: nums = [1;1;2] Output: [[1;1;2]; [1;2;1]; [2;1;1]] Example 2: Input: nums = [1;2;3] Output: [[1;2;3];[1;3;2];[2;1;3];[2;3;1];[3;1;2];[3;2;1]] Constraints: 1 <= nums.length <= 8 -10 <= nums[i] <= 10750Google,58,Length of Last Word,Easy,String,"Given a string s consisting of words and spaces; return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. Example 1: Input: s = ""Hello World"" Output: 5 Explanation: The last word is ""World"" with length 5. Example 2: Input: s = "" fly me to the moon "" Output: 4 Explanation: The last word is ""moon"" with length 4. Example 3: Input: s = ""luffy is still joyboy"" Output: 6 Explanation: The last word is ""joyboy"" with length 6. Constraints: 1 <= s.length <= 104 s consists of only English letters and spaces ' '. There will be at least one word in s."751Google,63,Unique Paths II,Med,"Array, Dynamic Programming, Matrix",You are given an m x n integer array grid. There is a robot 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. An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner. The testcases are generated so that the answer will be less than or equal to 2 * 109. Example 1: Input: obstacleGrid = [[0;0;0];[0;1;0];[0;0;0]] Output: 2 Explanation: There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right Example 2: Input: obstacleGrid = [[0;1];[0;0]] Output: 1 Constraints: m == obstacleGrid.length n == obstacleGrid[i].length 1 <= m; n <= 100 obstacleGrid[i][j] is 0 or 1.752Google,81,Search in Rotated Sorted Array II,Med,"Array, Binary Search",There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function; nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k]; nums[k+1]; ...; nums[n-1]; nums[0]; nums[1]; ...; nums[k-1]] (0-indexed). For example; [0;1;2;4;4;4;5;6;6;7] might be rotated at pivot index 5 and become [4;5;6;6;7;0;1;2;4;4]. Given the array nums after the rotation and an integer target; return true if target is in nums; or false if it is not in nums. You must decrease the overall operation steps as much as possible. Example 1: Input: nums = [2;5;6;0;0;1;2]; target = 0 Output: true Example 2: Input: nums = [2;5;6;0;0;1;2]; target = 3 Output: false Constraints: 1 <= nums.length <= 5000 -104 <= nums[i] <= 104 nums is guaranteed to be rotated at some pivot. -104 <= target <= 104 Follow up: This problem is similar to Search in Rotated Sorted Array; but nums may contain duplicates. Would this affect the runtime complexity? How and why?753Google,86,Partition List,Med,"Linked List, Two Pointers",Given the head of a linked list and a value x; partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. Example 1: Input: head = [1;4;3;2;5;2]; x = 3 Output: [1;2;2;4;3;5] Example 2: Input: head = [2;1]; x = 2 Output: [1;2] Constraints: The number of nodes in the list is in the range [0; 200]. -100 <= Node.val <= 100 -200 <= x <= 200754Google,90,Subsets II,Med,"Array, Backtracking, Bit Manipulation",Given an integer array nums that may contain duplicates; return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. Example 1: Input: nums = [1;2;2] Output: [[];[1];[1;2];[1;2;2];[2];[2;2]] Example 2: Input: nums = [0] Output: [[];[0]] Constraints: 1 <= nums.length <= 10 -10 <= nums[i] <= 10755Google,91,Decode Ways,Med,"String, Dynamic Programming","You have intercepted a secret message encoded as a string of numbers. The message is decoded via the following mapping: ""1"" -> 'A' ""2"" -> 'B' ... ""25"" -> 'Y' ""26"" -> 'Z' However; while decoding the message; you realize that there are many different ways you can decode the message because some codes are contained in other codes (""2"" and ""5"" vs ""25""). For example; ""11106"" can be decoded into: ""AAJF"" with the grouping (1; 1; 10; 6) ""KJF"" with the grouping (11; 10; 6) The grouping (1; 11; 06) is invalid because ""06"" is not a valid code (only ""6"" is valid). Note: there may be strings that are impossible to decode. Given a string s containing only digits; return the number of ways to decode it. If the entire string cannot be decoded in any valid way; return 0. The test cases are generated so that the answer fits in a 32-bit integer. Example 1: Input: s = ""12"" Output: 2 Explanation: ""12"" could be decoded as ""AB"" (1 2) or ""L"" (12). Example 2: Input: s = ""226"" Output: 3 Explanation: ""226"" could be decoded as ""BZ"" (2 26); ""VF"" (22 6); or ""BBF"" (2 2 6). Example 3: Input: s = ""06"" Output: 0 Explanation: ""06"" cannot be mapped to ""F"" because of the leading zero (""6"" is different from ""06""). In this case; the string is not a valid encoding; so return 0. Constraints: 1 <= s.length <= 100 s contains only digits and may contain leading zero(s)."756Google,106,Construct Binary Tree from Inorder and Postorder Traversal,Med,"Array, Hash Table, Divide and Conquer, Tree, Binary Tree",Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree; construct and return the binary tree. Example 1: Input: inorder = [9;3;15;20;7]; postorder = [9;15;7;20;3] Output: [3;9;20;null;null;15;7] Example 2: Input: inorder = [-1]; postorder = [-1] Output: [-1] Constraints: 1 <= inorder.length <= 3000 postorder.length == inorder.length -3000 <= inorder[i]; postorder[i] <= 3000 inorder and postorder consist of unique values. Each value of postorder also appears in inorder. inorder is guaranteed to be the inorder traversal of the tree. postorder is guaranteed to be the postorder traversal of the tree.757Google,110,Balanced Binary Tree,Easy,"Tree, Depth-First Search, Binary Tree",Given a binary tree; determine if it is height-balanced. Example 1: Input: root = [3;9;20;null;null;15;7] Output: true Example 2: Input: root = [1;2;2;3;3;null;null;4;4] Output: false Example 3: Input: root = [] Output: true Constraints: The number of nodes in the tree is in the range [0; 5000]. -104 <= Node.val <= 104758Google,113,Path Sum II,Med,"Backtracking, Tree, Depth-First Search, Binary Tree",Given the root of a binary tree and an integer targetSum; return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values; not node references. A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children. Example 1: Input: root = [5;4;8;11;null;13;4;7;2;null;null;5;1]; targetSum = 22 Output: [[5;4;11;2];[5;8;4;5]] Explanation: There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 Example 2: Input: root = [1;2;3]; targetSum = 5 Output: [] Example 3: Input: root = [1;2]; targetSum = 0 Output: [] Constraints: The number of nodes in the tree is in the range [0; 5000]. -1000 <= Node.val <= 1000 -1000 <= targetSum <= 1000759Google,114,Flatten Binary Tree to Linked List,Med,"Linked List, Stack, Tree, Depth-First Search, Binary Tree","Given the root of a binary tree; flatten the tree into a ""linked list"": The ""linked list"" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. The ""linked list"" should be in the same order as a pre-order traversal of the binary tree. Example 1: Input: root = [1;2;5;3;4;null;6] Output: [1;null;2;null;3;null;4;null;5;null;6] Example 2: Input: root = [] Output: [] Example 3: Input: root = [0] Output: [0] Constraints: The number of nodes in the tree is in the range [0; 2000]. -100 <= Node.val <= 100 Follow up: Can you flatten the tree in-place (with O(1) extra space)?"760Google,123,Best Time to Buy and Sell Stock III,Hard,"Array, Dynamic Programming",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 at most two transactions. Note: You may not engage in multiple transactions simultaneously (i.e.; you must sell the stock before you buy again). Example 1: Input: prices = [3;3;5;0;0;3;1;4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3); profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4); profit = 4-1 = 3. Example 2: Input: prices = [1;2;3;4;5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5); profit = 5-1 = 4. Note that you cannot buy on day 1; buy on day 2 and sell them later; as you are engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: prices = [7;6;4;3;1] Output: 0 Explanation: In this case; no transaction is done; i.e. max profit = 0. Constraints: 1 <= prices.length <= 105 0 <= prices[i] <= 105761Google,126,Word Ladder II,Hard,"Hash Table, String, Backtracking, Breadth-First Search","A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Every adjacent pair of words differs by a single letter. Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. sk == endWord Given two words; beginWord and endWord; and a dictionary wordList; return all the shortest transformation sequences from beginWord to endWord; or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord; s1; s2; ...; sk]. Example 1: Input: beginWord = ""hit""; endWord = ""cog""; wordList = [""hot"";""dot"";""dog"";""lot"";""log"";""cog""] Output: [[""hit"";""hot"";""dot"";""dog"";""cog""];[""hit"";""hot"";""lot"";""log"";""cog""]] Explanation: There are 2 shortest transformation sequences: ""hit"" -> ""hot"" -> ""dot"" -> ""dog"" -> ""cog"" ""hit"" -> ""hot"" -> ""lot"" -> ""log"" -> ""cog"" Example 2: Input: beginWord = ""hit""; endWord = ""cog""; wordList = [""hot"";""dot"";""dog"";""lot"";""log""] Output: [] Explanation: The endWord ""cog"" is not in wordList; therefore there is no valid transformation sequence. Constraints: 1 <= beginWord.length <= 5 endWord.length == beginWord.length 1 <= wordList.length <= 500 wordList[i].length == beginWord.length beginWord; endWord; and wordList[i] consist of lowercase English letters. beginWord != endWord All the words in wordList are unique. The sum of all shortest transformation sequences does not exceed 105."762Google,131,Palindrome Partitioning,Med,"String, Dynamic Programming, Backtracking","Given a string s; partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. Example 1: Input: s = ""aab"" Output: [[""a"";""a"";""b""];[""aa"";""b""]] Example 2: Input: s = ""a"" Output: [[""a""]] Constraints: 1 <= s.length <= 16 s contains only lowercase English letters."763Google,133,Clone Graph,Med,"Hash Table, Depth-First Search, Breadth-First Search, Graph",Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. class Node { public int val; public List<Node> neighbors; } Test case format: For simplicity; each node's value is the same as the node's index (1-indexed). For example; the first node with val == 1; the second node with val == 2; and so on. The graph is represented in the test case using an adjacency list. An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph. Example 1: Input: adjList = [[2;4];[1;3];[2;4];[1;3]] Output: [[2;4];[1;3];[2;4];[1;3]] Explanation: There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). Example 2: Input: adjList = [[]] Output: [[]] Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. Example 3: Input: adjList = [] Output: [] Explanation: This an empty graph; it does not have any nodes. Constraints: The number of nodes in the graph is in the range [0; 100]. 1 <= Node.val <= 100 Node.val is unique for each node. There are no repeated edges and no self-loops in the graph. The Graph is connected and all nodes can be visited starting from the given node.764Google,135,Candy,Hard,"Array, Greedy",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. Example 1: Input: ratings = [1;0;2] Output: 5 Explanation: You can allocate to the first; second and third child with 2; 1; 2 candies respectively. Example 2: 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. Constraints: n == ratings.length 1 <= n <= 2 * 104 0 <= ratings[i] <= 2 * 104765Google,148,Sort List,Med,"Linked List, Two Pointers, Divide and Conquer, Sorting, Merge Sort",Given the head of a linked list; return the list after sorting it in ascending order. Example 1: Input: head = [4;2;1;3] Output: [1;2;3;4] Example 2: Input: head = [-1;5;3;4;0] Output: [-1;0;3;4;5] Example 3: Input: head = [] Output: [] Constraints: The number of nodes in the list is in the range [0; 5 * 104]. -105 <= Node.val <= 105 Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?766Google,149,Max Points on a Line,Hard,"Array, Hash Table, Math, Geometry",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. Example 1: Input: points = [[1;1];[2;2];[3;3]] Output: 3 Example 2: Input: points = [[1;1];[3;2];[5;3];[4;1];[2;3];[1;4]] Output: 4 Constraints: 1 <= points.length <= 300 points[i].length == 2 -104 <= xi; yi <= 104 All the points are unique.767Google,153,Find Minimum in Rotated Sorted Array,Med,"Array, Binary Search",Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example; the array nums = [0;1;2;4;5;6;7] might become: [4;5;6;7;0;1;2] if it was rotated 4 times. [0;1;2;4;5;6;7] if it was rotated 7 times. Notice that rotating an array [a[0]; a[1]; a[2]; ...; a[n-1]] 1 time results in the array [a[n-1]; a[0]; a[1]; a[2]; ...; a[n-2]]. Given the sorted rotated array nums of unique elements; return the minimum element of this array. You must write an algorithm that runs in O(log n) time. Example 1: Input: nums = [3;4;5;1;2] Output: 1 Explanation: The original array was [1;2;3;4;5] rotated 3 times. Example 2: Input: nums = [4;5;6;7;0;1;2] Output: 0 Explanation: The original array was [0;1;2;4;5;6;7] and it was rotated 4 times. Example 3: Input: nums = [11;13;15;17] Output: 11 Explanation: The original array was [11;13;15;17] and it was rotated 4 times. Constraints: n == nums.length 1 <= n <= 5000 -5000 <= nums[i] <= 5000 All the integers of nums are unique. nums is sorted and rotated between 1 and n times.768Google,155,Min Stack,Med,"Stack, Design","Design a stack that supports push; pop; top; and retrieving the minimum element in constant time. Implement the MinStack class: MinStack() initializes the stack object. void push(int val) pushes the element val onto the stack. void pop() removes the element on the top of the stack. int top() gets the top element of the stack. int getMin() retrieves the minimum element in the stack. You must implement a solution with O(1) time complexity for each function. Example 1: Input [""MinStack"";""push"";""push"";""push"";""getMin"";""pop"";""top"";""getMin""] [[];[-2];[0];[-3];[];[];[];[]] Output [null;null;null;null;-3;null;0;-2] Explanation MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2 Constraints: -231 <= val <= 231 - 1 Methods pop; top and getMin operations will always be called on non-empty stacks. At most 3 * 104 calls will be made to push; pop; top; and getMin."769Google,167,Two Sum II - Input Array Is Sorted,Med,"Array, Two Pointers, Binary Search",Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order; find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. Return the indices of the two numbers; index1 and index2; added by one as an integer array [index1; index2] of length 2. The tests are generated such that there is exactly one solution. You may not use the same element twice. Your solution must use only constant extra space. Example 1: Input: numbers = [2;7;11;15]; target = 9 Output: [1;2] Explanation: The sum of 2 and 7 is 9. Therefore; index1 = 1; index2 = 2. We return [1; 2]. Example 2: Input: numbers = [2;3;4]; target = 6 Output: [1;3] Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1; index2 = 3. We return [1; 3]. Example 3: Input: numbers = [-1;0]; target = -1 Output: [1;2] Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1; index2 = 2. We return [1; 2]. Constraints: 2 <= numbers.length <= 3 * 104 -1000 <= numbers[i] <= 1000 numbers is sorted in non-decreasing order. -1000 <= target <= 1000 The tests are generated such that there is exactly one solution.770Google,197,Rising Temperature,Easy,Database,Table: Weather +---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | recordDate | date | | temperature | int | +---------------+---------+ id is the column with unique values for this table. There are no different rows with the same recordDate. This table contains information about the temperature on a certain day. Write a solution to find all dates' id with higher temperatures compared to its previous dates (yesterday). Return the result table in any order. The result format is in the following example. Example 1: Input: Weather table: +----+------------+-------------+ | id | recordDate | temperature | +----+------------+-------------+ | 1 | 2015-01-01 | 10 | | 2 | 2015-01-02 | 25 | | 3 | 2015-01-03 | 20 | | 4 | 2015-01-04 | 30 | +----+------------+-------------+ Output: +----+ | id | +----+ | 2 | | 4 | +----+ Explanation: In 2015-01-02; the temperature was higher than the previous day (10 -> 25). In 2015-01-04; the temperature was higher than the previous day (20 -> 30).771Google,209,Minimum Size Subarray Sum,Med,"Array, Binary Search, Sliding Window, Prefix Sum",Given an array of positive integers nums and a positive integer target; return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray; return 0 instead. Example 1: Input: target = 7; nums = [2;3;1;2;4;3] Output: 2 Explanation: The subarray [4;3] has the minimal length under the problem constraint. Example 2: Input: target = 4; nums = [1;4;4] Output: 1 Example 3: Input: target = 11; nums = [1;1;1;1;1;1;1;1] Output: 0 Constraints: 1 <= target <= 109 1 <= nums.length <= 105 1 <= nums[i] <= 104 Follow up: If you have figured out the O(n) solution; try coding another solution of which the time complexity is O(n log(n)).772Google,210,Course Schedule II,Med,"Depth-First Search, Breadth-First Search, Graph, Topological Sort",There are a total of numCourses courses you have to take; labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai; bi] indicates that you must take course bi first if you want to take course ai. For example; the pair [0; 1]; indicates that to take course 0 you have to first take course 1. Return the ordering of courses you should take to finish all courses. If there are many valid answers; return any of them. If it is impossible to finish all courses; return an empty array. Example 1: Input: numCourses = 2; prerequisites = [[1;0]] Output: [0;1] Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0;1]. Example 2: Input: numCourses = 4; prerequisites = [[1;0];[2;0];[3;1];[3;2]] Output: [0;2;1;3] Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0;1;2;3]. Another correct ordering is [0;2;1;3]. Example 3: Input: numCourses = 1; prerequisites = [] Output: [0] Constraints: 1 <= numCourses <= 2000 0 <= prerequisites.length <= numCourses * (numCourses - 1) prerequisites[i].length == 2 0 <= ai; bi < numCourses ai != bi All the pairs [ai; bi] are distinct.773Google,218,The Skyline Problem,Hard,"Array, Divide and Conquer, Binary Indexed Tree, Segment Tree, Line Sweep, Heap (Priority Queue), Ordered Set","A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings; return the skyline formed by these buildings collectively. The geometric information of each building is given in the array buildings where buildings[i] = [lefti; righti; heighti]: lefti is the x coordinate of the left edge of the ith building. righti is the x coordinate of the right edge of the ith building. heighti is the height of the ith building. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0. The skyline should be represented as a list of ""key points"" sorted by their x-coordinate in the form [[x1;y1];[x2;y2];...]. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list; which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour. Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance; [...;[2 3];[4 5];[7 5];[11 5];[12 7];...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...;[2 3];[4 5];[12 7];...] Example 1: Input: buildings = [[2;9;10];[3;7;15];[5;12;12];[15;20;10];[19;24;8]] Output: [[2;10];[3;15];[7;12];[12;0];[15;10];[20;8];[24;0]] Explanation: Figure A shows the buildings of the input. Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list. Example 2: Input: buildings = [[0;2;3];[2;5;3]] Output: [[0;3];[5;0]] Constraints: 1 <= buildings.length <= 104 0 <= lefti < righti <= 231 - 1 1 <= heighti <= 231 - 1 buildings is sorted by lefti in non-decreasing order."774Google,222,Count Complete Tree Nodes,Easy,"Binary Search, Bit Manipulation, Tree, Binary Tree",Given the root of a complete binary tree; return the number of the nodes in the tree. According to Wikipedia; every level; except possibly the last; is completely filled in a complete binary tree; and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Design an algorithm that runs in less than O(n) time complexity. Example 1: Input: root = [1;2;3;4;5;6] Output: 6 Example 2: Input: root = [] Output: 0 Example 3: Input: root = [1] Output: 1 Constraints: The number of nodes in the tree is in the range [0; 5 * 104]. 0 <= Node.val <= 5 * 104 The tree is guaranteed to be complete.775Google,232,Implement Queue using Stacks,Easy,"Stack, Design, Queue","Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push; peek; pop; and empty). Implement the MyQueue class: void push(int x) Pushes element x to the back of the queue. int pop() Removes the element from the front of the queue and returns it. int peek() Returns the element at the front of the queue. boolean empty() Returns true if the queue is empty; false otherwise. Notes: You must use only standard operations of a stack; which means only push to top; peek/pop from top; size; and is empty operations are valid. Depending on your language; the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations. Example 1: Input [""MyQueue""; ""push""; ""push""; ""peek""; ""pop""; ""empty""] [[]; [1]; [2]; []; []; []] Output [null; null; null; 1; 1; false] Explanation MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1; 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1; queue is [2] myQueue.empty(); // return false Constraints: 1 <= x <= 9 At most 100 calls will be made to push; pop; peek; and empty. All the calls to pop and peek are valid. Follow-up: Can you implement the queue such that each operation is amortized O(1) time complexity? In other words; performing n operations will take overall O(n) time even if one of those operations may take longer."776Google,233,Number of Digit One,Hard,"Math, Dynamic Programming, Recursion",Given an integer n; count the total number of digit 1 appearing in all non-negative integers less than or equal to n. Example 1: Input: n = 13 Output: 6 Example 2: Input: n = 0 Output: 0 Constraints: 0 <= n <= 109777Google,257,Binary Tree Paths,Easy,"String, Backtracking, Tree, Depth-First Search, Binary Tree","Given the root of a binary tree; return all root-to-leaf paths in any order. A leaf is a node with no children. Example 1: Input: root = [1;2;3;null;5] Output: [""1->2->5"";""1->3""] Example 2: Input: root = [1] Output: [""1""] Constraints: The number of nodes in the tree is in the range [1; 100]. -100 <= Node.val <= 100"778Google,261,Graph Valid Tree,Med,"Depth-First Search, Breadth-First Search, Union Find, Graph",779Google,271,Encode and Decode Strings,Med,"Array, String, Design",780Google,273,Integer to English Words,Hard,"Math, String, Recursion","Convert a non-negative integer num to its English words representation. Example 1: Input: num = 123 Output: ""One Hundred Twenty Three"" Example 2: Input: num = 12345 Output: ""Twelve Thousand Three Hundred Forty Five"" Example 3: Input: num = 1234567 Output: ""One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"" Constraints: 0 <= num <= 231 - 1"781Google,280,Wiggle Sort,Med,"Array, Greedy, Sorting",782Google,282,Expression Add Operators,Hard,"Math, String, Backtracking","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. Example 1: Input: num = ""123""; target = 6 Output: [""1*2*3"";""1+2+3""] Explanation: Both ""1*2*3"" and ""1+2+3"" evaluate to 6. Example 2: Input: num = ""232""; target = 8 Output: [""2*3+2"";""2+3*2""] Explanation: Both ""2*3+2"" and ""2+3*2"" evaluate to 8. Example 3: Input: num = ""3456237490""; target = 9191 Output: [] Explanation: There are no expressions that can be created from ""3456237490"" to evaluate to 9191. Constraints: 1 <= num.length <= 10 num consists of only digits. -231 <= target <= 231 - 1"783Google,292,Nim Game,Easy,"Math, Brainteaser, Game Theory",You are playing the following Nim Game with your friend: Initially; there is a heap of stones on the table. You and your friend will alternate taking turns; and you go first. On each turn; the person whose turn it is will remove 1 to 3 stones from the heap. The one who removes the last stone is the winner. Given n; the number of stones in the heap; return true if you can win the game assuming both you and your friend play optimally; otherwise return false. Example 1: Input: n = 4 Output: false Explanation: These are the possible outcomes: 1. You remove 1 stone. Your friend removes 3 stones; including the last stone. Your friend wins. 2. You remove 2 stones. Your friend removes 2 stones; including the last stone. Your friend wins. 3. You remove 3 stones. Your friend removes the last stone. Your friend wins. In all outcomes; your friend wins. Example 2: Input: n = 1 Output: true Example 3: Input: n = 2 Output: true Constraints: 1 <= n <= 231 - 1784Google,308,Range Sum Query 2D - Mutable,Hard,"Array, Design, Binary Indexed Tree, Segment Tree, Matrix",785Google,309,Best Time to Buy and Sell Stock with Cooldown,Med,"Array, Dynamic Programming",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). Example 1: Input: prices = [1;2;3;0;2] Output: 3 Explanation: transactions = [buy; sell; cooldown; buy; sell] Example 2: Input: prices = [1] Output: 0 Constraints: 1 <= prices.length <= 5000 0 <= prices[i] <= 1000786Google,310,Minimum Height Trees,Med,"Depth-First Search, Breadth-First Search, Graph, Topological Sort",A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words; any connected graph without simple cycles is a tree. Given a tree of n nodes labelled from 0 to n - 1; and an array of n - 1 edges where edges[i] = [ai; bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree; you can choose any node of the tree as the root. When you select a node x as the root; the result tree has height h. Among all possible rooted trees; those with minimum height (i.e. min(h)) are called minimum height trees (MHTs). Return a list of all MHTs' root labels. You can return the answer in any order. The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf. Example 1: Input: n = 4; edges = [[1;0];[1;2];[1;3]] Output: [1] Explanation: As shown; the height of the tree is 1 when the root is the node with label 1 which is the only MHT. Example 2: Input: n = 6; edges = [[3;0];[3;1];[3;2];[3;4];[5;4]] Output: [3;4] Constraints: 1 <= n <= 2 * 104 edges.length == n - 1 0 <= ai; bi < n ai != bi All the pairs (ai; bi) are distinct. The given input is guaranteed to be a tree and there will be no repeated edges.787Google,315,Count of Smaller Numbers After Self,Hard,"Array, Binary Search, Divide and Conquer, Binary Indexed Tree, Segment Tree, Merge Sort, Ordered Set",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]. Example 1: 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. Example 2: Input: nums = [-1] Output: [0] Example 3: Input: nums = [-1;-1] Output: [0;0] Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104788Google,321,Create Maximum Number,Hard,"Array, Two Pointers, Stack, Greedy, Monotonic Stack",You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers. You are also given an integer k. Create the maximum number of length k <= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserved. Return an array of the k digits representing the answer. Example 1: Input: nums1 = [3;4;6;5]; nums2 = [9;1;2;5;8;3]; k = 5 Output: [9;8;6;5;3] Example 2: Input: nums1 = [6;7]; nums2 = [6;0;4]; k = 5 Output: [6;7;6;0;4] Example 3: Input: nums1 = [3;9]; nums2 = [8;9]; k = 3 Output: [9;8;9] Constraints: m == nums1.length n == nums2.length 1 <= m; n <= 500 0 <= nums1[i]; nums2[i] <= 9 1 <= k <= m + n789Google,334,Increasing Triplet Subsequence,Med,"Array, Greedy",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. Example 1: Input: nums = [1;2;3;4;5] Output: true Explanation: Any triplet where i < j < k is valid. Example 2: Input: nums = [5;4;3;2;1] Output: false Explanation: No triplet exists. Example 3: 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. Constraints: 1 <= nums.length <= 5 * 105 -231 <= nums[i] <= 231 - 1 Follow up: Could you implement a solution that runs in O(n) time complexity and O(1) space complexity?790Google,337,House Robber III,Med,"Dynamic Programming, Tree, Depth-First Search, Binary Tree",The thief has found himself a new place for his thievery again. There is only one entrance to this area; called root. Besides the root; each house has one and only one parent house. After a tour; the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night. Given the root of the binary tree; return the maximum amount of money the thief can rob without alerting the police. Example 1: Input: root = [3;2;3;null;3;null;1] Output: 7 Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. Example 2: Input: root = [3;4;5;1;3;null;1] Output: 9 Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9. Constraints: The number of nodes in the tree is in the range [1; 104]. 0 <= Node.val <= 104791Google,342,Power of Four,Easy,"Math, Bit Manipulation, Recursion",Given an integer n; return true if it is a power of four. Otherwise; return false. An integer n is a power of four; if there exists an integer x such that n == 4x. Example 1: Input: n = 16 Output: true Example 2: Input: n = 5 Output: false Example 3: Input: n = 1 Output: true Constraints: -231 <= n <= 231 - 1 Follow up: Could you solve it without loops/recursion?792Google,344,Reverse String,Easy,"Two Pointers, String","Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory. Example 1: Input: s = [""h"";""e"";""l"";""l"";""o""] Output: [""o"";""l"";""l"";""e"";""h""] Example 2: Input: s = [""H"";""a"";""n"";""n"";""a"";""h""] Output: [""h"";""a"";""n"";""n"";""a"";""H""] Constraints: 1 <= s.length <= 105 s[i] is a printable ascii character."793Google,345,Reverse Vowels of a String,Easy,"Two Pointers, String","Given a string s; reverse only all the vowels in the string and return it. The vowels are 'a'; 'e'; 'i'; 'o'; and 'u'; and they can appear in both lower and upper cases; more than once. Example 1: Input: s = ""IceCreAm"" Output: ""AceCreIm"" Explanation: The vowels in s are ['I'; 'e'; 'e'; 'A']. On reversing the vowels; s becomes ""AceCreIm"". Example 2: Input: s = ""leetcode"" Output: ""leotcede"" Constraints: 1 <= s.length <= 3 * 105 s consist of printable ASCII characters."794Google,367,Valid Perfect Square,Easy,"Math, Binary Search",Given a positive integer num; return true if num is a perfect square or false otherwise. A perfect square is an integer that is the square of an integer. In other words; it is the product of some integer with itself. You must not use any built-in library function; such as sqrt. Example 1: Input: num = 16 Output: true Explanation: We return true because 4 * 4 = 16 and 4 is an integer. Example 2: Input: num = 14 Output: false Explanation: We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer. Constraints: 1 <= num <= 231 - 1795Google,390,Elimination Game,Med,"Math, Recursion",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. Example 1: 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] Example 2: Input: n = 1 Output: 1 Constraints: 1 <= n <= 109796Google,399,Evaluate Division,Med,"Array, String, Depth-First Search, Breadth-First Search, Union Find, Graph, Shortest Path","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. Note: The variables that do not occur in the list of equations are undefined; so the answer cannot be determined for them. Example 1: 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 ] note: x is undefined => -1.0 Example 2: Input: equations = [[""a"";""b""];[""b"";""c""];[""bc"";""cd""]]; values = [1.5;2.5;5.0]; queries = [[""a"";""c""];[""c"";""b""];[""bc"";""cd""];[""cd"";""bc""]] Output: [3.75000;0.40000;5.00000;0.20000] Example 3: Input: equations = [[""a"";""b""]]; values = [0.5]; queries = [[""a"";""b""];[""b"";""a""];[""a"";""c""];[""x"";""y""]] Output: [0.50000;2.00000;-1.00000;-1.00000] Constraints: 1 <= equations.length <= 20 equations[i].length == 2 1 <= Ai.length; Bi.length <= 5 values.length == equations.length 0.0 < values[i] <= 20.0 1 <= queries.length <= 20 queries[i].length == 2 1 <= Cj.length; Dj.length <= 5 Ai; Bi; Cj; Dj consist of lower case English letters and digits."797Google,402,Remove K Digits,Med,"String, Stack, Greedy, Monotonic Stack","Given string num representing a non-negative integer num; and an integer k; return the smallest possible integer after removing k digits from num. Example 1: Input: num = ""1432219""; k = 3 Output: ""1219"" Explanation: Remove the three digits 4; 3; and 2 to form the new number 1219 which is the smallest. Example 2: Input: num = ""10200""; k = 1 Output: ""200"" Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. Example 3: Input: num = ""10""; k = 2 Output: ""0"" Explanation: Remove all the digits from the number and it is left with nothing which is 0. Constraints: 1 <= k <= num.length <= 105 num consists of only digits. num does not have any leading zeros except for the zero itself."798Google,414,Third Maximum Number,Easy,"Array, Sorting",Given an integer array nums; return the third distinct maximum number in this array. If the third maximum does not exist; return the maximum number. Example 1: Input: nums = [3;2;1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum is 1. Example 2: Input: nums = [1;2] Output: 2 Explanation: The first distinct maximum is 2. The second distinct maximum is 1. The third distinct maximum does not exist; so the maximum (2) is returned instead. Example 3: Input: nums = [2;2;3;1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2 (both 2's are counted together since they have the same value). The third distinct maximum is 1. Constraints: 1 <= nums.length <= 104 -231 <= nums[i] <= 231 - 1 Follow up: Can you find an O(n) solution?799Google,433,Minimum Genetic Mutation,Med,"Hash Table, String, Breadth-First Search","A gene string can be represented by an 8-character long string; with choices from 'A'; 'C'; 'G'; and 'T'. Suppose we need to investigate a mutation from a gene string startGene to a gene string endGene where one mutation is defined as one single character changed in the gene string. For example; ""AACCGGTT"" --> ""AACCGGTA"" is one mutation. There is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string. Given the two gene strings startGene and endGene and the gene bank bank; return the minimum number of mutations needed to mutate from startGene to endGene. If there is no such a mutation; return -1. Note that the starting point is assumed to be valid; so it might not be included in the bank. Example 1: Input: startGene = ""AACCGGTT""; endGene = ""AACCGGTA""; bank = [""AACCGGTA""] Output: 1 Example 2: Input: startGene = ""AACCGGTT""; endGene = ""AAACGGTA""; bank = [""AACCGGTA"";""AACCGCTA"";""AAACGGTA""] Output: 2 Constraints: 0 <= bank.length <= 10 startGene.length == endGene.length == bank[i].length == 8 startGene; endGene; and bank[i] consist of only the characters ['A'; 'C'; 'G'; 'T']."800Google,435,Non-overlapping Intervals,Med,"Array, Dynamic Programming, Greedy, Sorting",Given an array of intervals intervals where intervals[i] = [starti; endi]; return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. Note that intervals which only touch at a point are non-overlapping. For example; [1; 2] and [2; 3] are non-overlapping. Example 1: Input: intervals = [[1;2];[2;3];[3;4];[1;3]] Output: 1 Explanation: [1;3] can be removed and the rest of the intervals are non-overlapping. Example 2: Input: intervals = [[1;2];[1;2];[1;2]] Output: 2 Explanation: You need to remove two [1;2] to make the rest of the intervals non-overlapping. Example 3: Input: intervals = [[1;2];[2;3]] Output: 0 Explanation: You don't need to remove any of the intervals since they're already non-overlapping. Constraints: 1 <= intervals.length <= 105 intervals[i].length == 2 -5 * 104 <= starti < endi <= 5 * 104801Google,438,Find All Anagrams in a String,Med,"Hash Table, String, Sliding Window","Given two strings s and p; return an array of all the start indices of p's anagrams in s. You may return the answer in any order. Example 1: Input: s = ""cbaebabacd""; p = ""abc"" Output: [0;6] Explanation: The substring with start index = 0 is ""cba""; which is an anagram of ""abc"". The substring with start index = 6 is ""bac""; which is an anagram of ""abc"". Example 2: Input: s = ""abab""; p = ""ab"" Output: [0;1;2] Explanation: The substring with start index = 0 is ""ab""; which is an anagram of ""ab"". The substring with start index = 1 is ""ba""; which is an anagram of ""ab"". The substring with start index = 2 is ""ab""; which is an anagram of ""ab"". Constraints: 1 <= s.length; p.length <= 3 * 104 s and p consist of lowercase English letters."802Google,446,Arithmetic Slices II - Subsequence,Hard,"Array, Dynamic Programming",Given an integer array nums; return the number of all the arithmetic subsequences of nums. A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For example; [1; 3; 5; 7; 9]; [7; 7; 7; 7]; and [3; -1; -5; -9] are arithmetic sequences. For example; [1; 1; 2; 5; 7] is not an arithmetic sequence. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. For example; [2;5;10] is a subsequence of [1;2;1;2;4;1;5;10]. The test cases are generated so that the answer fits in 32-bit integer. Example 1: Input: nums = [2;4;6;8;10] Output: 7 Explanation: All arithmetic subsequence slices are: [2;4;6] [4;6;8] [6;8;10] [2;4;6;8] [4;6;8;10] [2;4;6;8;10] [2;6;10] Example 2: Input: nums = [7;7;7;7;7] Output: 16 Explanation: Any subsequence of this array is arithmetic. Constraints: 1 <= nums.length <= 1000 -231 <= nums[i] <= 231 - 1803Google,448,Find All Numbers Disappeared in an Array,Easy,"Array, Hash Table",Given an array nums of n integers where nums[i] is in the range [1; n]; return an array of all the integers in the range [1; n] that do not appear in nums. Example 1: Input: nums = [4;3;2;7;8;2;3;1] Output: [5;6] Example 2: Input: nums = [1;1] Output: [2] Constraints: n == nums.length 1 <= n <= 105 1 <= nums[i] <= n Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.804Google,476,Number Complement,Easy,Bit Manipulation,"The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. For example; The integer 5 is ""101"" in binary and its complement is ""010"" which is the integer 2. Given an integer num; return its complement. Example 1: Input: num = 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits); and its complement is 010. So you need to output 2. Example 2: Input: num = 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits); and its complement is 0. So you need to output 0. Constraints: 1 <= num < 231 Note: This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/"805Google,486,Predict the Winner,Med,"Array, Math, Dynamic Programming, Recursion, Game Theory",You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns; with player 1 starting first. Both players start the game with a score of 0. At each turn; the player takes one of the numbers from either end of the array (i.e.; nums[0] or nums[nums.length - 1]) which reduces the size of the array by 1. The player adds the chosen number to their score. The game ends when there are no more elements in the array. Return true if Player 1 can win the game. If the scores of both players are equal; then player 1 is still the winner; and you should also return true. You may assume that both players are playing optimally. Example 1: Input: nums = [1;5;2] Output: false Explanation: Initially; player 1 can choose between 1 and 2. If he chooses 2 (or 1); then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5; then player 1 will be left with 1 (or 2). So; final score of player 1 is 1 + 2 = 3; and player 2 is 5. Hence; player 1 will never be the winner and you need to return false. Example 2: Input: nums = [1;5;233;7] Output: true Explanation: Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose; player 1 can choose 233. Finally; player 1 has more score (234) than player 2 (12); so you need to return True representing player1 can win. Constraints: 1 <= nums.length <= 20 0 <= nums[i] <= 107806Google,518,Coin Change II,Med,"Array, Dynamic Programming",You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins; return 0. You may assume that you have an infinite number of each kind of coin. The answer is guaranteed to fit into a signed 32-bit integer. Example 1: Input: amount = 5; coins = [1;2;5] Output: 4 Explanation: there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1 Example 2: Input: amount = 3; coins = [2] Output: 0 Explanation: the amount of 3 cannot be made up just with coins of 2. Example 3: Input: amount = 10; coins = [10] Output: 1 Constraints: 1 <= coins.length <= 300 1 <= coins[i] <= 5000 All the values of coins are unique. 0 <= amount <= 5000807Google,546,Remove Boxes,Hard,"Array, Dynamic Programming, Memoization",You are given several boxes with different colors represented by different positive numbers. You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e.; composed of k boxes; k >= 1); remove them and get k * k points. Return the maximum points you can get. Example 1: Input: boxes = [1;3;2;2;2;3;4;3;1] Output: 23 Explanation: [1; 3; 2; 2; 2; 3; 4; 3; 1] ----> [1; 3; 3; 4; 3; 1] (3*3=9 points) ----> [1; 3; 3; 3; 1] (1*1=1 points) ----> [1; 1] (3*3=9 points) ----> [] (2*2=4 points) Example 2: Input: boxes = [1;1;1] Output: 9 Example 3: Input: boxes = [1] Output: 1 Constraints: 1 <= boxes.length <= 100 1 <= boxes[i] <= 100808Google,552,Student Attendance Record II,Hard,Dynamic Programming,"An attendance record for a student can be represented as a string where each character signifies whether the student was absent; late; or present on that day. The record only contains the following three characters: 'A': Absent. 'L': Late. 'P': Present. Any student is eligible for an attendance award if they meet both of the following criteria: The student was absent ('A') for strictly fewer than 2 days total. The student was never late ('L') for 3 or more consecutive days. Given an integer n; return the number of possible attendance records of length n that make a student eligible for an attendance award. The answer may be very large; so return it modulo 109 + 7. Example 1: Input: n = 2 Output: 8 Explanation: There are 8 records with length 2 that are eligible for an award: ""PP""; ""AP""; ""PA""; ""LP""; ""PL""; ""AL""; ""LA""; ""LL"" Only ""AA"" is not eligible because there are 2 absences (there need to be fewer than 2). Example 2: Input: n = 1 Output: 3 Example 3: Input: n = 10101 Output: 183236316 Constraints: 1 <= n <= 105"809Google,564,Find the Closest Palindrome,Hard,"Math, String","Given a string n representing an integer; return the closest integer (not including itself); which is a palindrome. If there is a tie; return the smaller one. The closest is defined as the absolute difference minimized between two integers. Example 1: Input: n = ""123"" Output: ""121"" Example 2: Input: n = ""1"" Output: ""0"" Explanation: 0 and 2 are the closest palindromes but we return the smallest which is 0. Constraints: 1 <= n.length <= 18 n consists of only digits. n does not have leading zeros. n is representing an integer in the range [1; 1018 - 1]."810Google,572,Subtree of Another Tree,Easy,"Tree, Depth-First Search, String Matching, Binary Tree, Hash Function",Given the roots of two binary trees root and subRoot; return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise. A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself. Example 1: Input: root = [3;4;5;1;2]; subRoot = [4;1;2] Output: true Example 2: Input: root = [3;4;5;1;2;null;null;null;null;0]; subRoot = [4;1;2] Output: false Constraints: The number of nodes in the root tree is in the range [1; 2000]. The number of nodes in the subRoot tree is in the range [1; 1000]. -104 <= root.val <= 104 -104 <= subRoot.val <= 104811Google,581,Shortest Unsorted Continuous Subarray,Med,"Array, Two Pointers, Stack, Greedy, Sorting, Monotonic Stack",Given an integer array nums; you need to find one continuous subarray such that if you only sort this subarray in non-decreasing order; then the whole array will be sorted in non-decreasing order. Return the shortest such subarray and output its length. Example 1: Input: nums = [2;6;4;8;10;9;15] Output: 5 Explanation: You need to sort [6; 4; 8; 10; 9] in ascending order to make the whole array sorted in ascending order. Example 2: Input: nums = [1;2;3;4] Output: 0 Example 3: Input: nums = [1] Output: 0 Constraints: 1 <= nums.length <= 104 -105 <= nums[i] <= 105 Follow up: Can you solve it in O(n) time complexity?812Google,586,Customer Placing the Largest Number of Orders,Easy,Database,Table: Orders +-----------------+----------+ | Column Name | Type | +-----------------+----------+ | order_number | int | | customer_number | int | +-----------------+----------+ order_number is the primary key (column with unique values) for this table. This table contains information about the order ID and the customer ID. Write a solution to find the customer_number for the customer who has placed the largest number of orders. The test cases are generated so that exactly one customer will have placed more orders than any other customer. The result format is in the following example. Example 1: Input: Orders table: +--------------+-----------------+ | order_number | customer_number | +--------------+-----------------+ | 1 | 1 | | 2 | 2 | | 3 | 3 | | 4 | 3 | +--------------+-----------------+ Output: +-----------------+ | customer_number | +-----------------+ | 3 | +-----------------+ Explanation: The customer with number 3 has two orders; which is greater than either customer 1 or 2 because each of them only has one order. So the result is customer_number 3. Follow up: What if more than one customer has the largest number of orders; can you find all the customer_number in this case?813Google,617,Merge Two Binary Trees,Easy,"Tree, Depth-First Search, Breadth-First Search, Binary Tree",You are given two binary trees root1 and root2. Imagine that when you put one of them to cover the other; some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap; then sum node values up as the new value of the merged node. Otherwise; the NOT null node will be used as the node of the new tree. Return the merged tree. Note: The merging process must start from the root nodes of both trees. Example 1: Input: root1 = [1;3;2;5]; root2 = [2;1;3;null;4;null;7] Output: [3;4;5;5;4;null;7] Example 2: Input: root1 = [1]; root2 = [1;2] Output: [2;2] Constraints: The number of nodes in both trees is in the range [0; 2000]. -104 <= Node.val <= 104814Google,620,Not Boring Movies,Easy,Database,"Table: Cinema +----------------+----------+ | Column Name | Type | +----------------+----------+ | id | int | | movie | varchar | | description | varchar | | rating | float | +----------------+----------+ id is the primary key (column with unique values) for this table. Each row contains information about the name of a movie; its genre; and its rating. rating is a 2 decimal places float in the range [0; 10] Write a solution to report the movies with an odd-numbered ID and a description that is not ""boring"". Return the result table ordered by rating in descending order. The result format is in the following example. Example 1: Input: Cinema table: +----+------------+-------------+--------+ | id | movie | description | rating | +----+------------+-------------+--------+ | 1 | War | great 3D | 8.9 | | 2 | Science | fiction | 8.5 | | 3 | irish | boring | 6.2 | | 4 | Ice song | Fantacy | 8.6 | | 5 | House card | Interesting | 9.1 | +----+------------+-------------+--------+ Output: +----+------------+-------------+--------+ | id | movie | description | rating | +----+------------+-------------+--------+ | 5 | House card | Interesting | 9.1 | | 1 | War | great 3D | 8.9 | +----+------------+-------------+--------+ Explanation: We have three movies with odd-numbered IDs: 1; 3; and 5. The movie with ID = 3 is boring so we do not include it in the answer."815Google,636,Exclusive Time of Functions,Med,"Array, Stack","On a single-threaded CPU; we execute a program containing n functions. Each function has a unique ID between 0 and n-1. Function calls are stored in a call stack: when a function call starts; its ID is pushed onto the stack; and when a function call ends; its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed. Each time a function starts or ends; we write a log with the ID; whether it started or ended; and the timestamp. You are given a list logs; where logs[i] represents the ith log message formatted as a string ""{function_id}:{""start"" | ""end""}:{timestamp}"". For example; ""0:start:3"" means a function call with function ID 0 started at the beginning of timestamp 3; and ""1:end:2"" means a function call with function ID 1 ended at the end of timestamp 2. Note that a function can be called multiple times; possibly recursively. A function's exclusive time is the sum of execution times for all function calls in the program. For example; if a function is called twice; one call executing for 2 time units and another call executing for 1 time unit; the exclusive time is 2 + 1 = 3. Return the exclusive time of each function in an array; where the value at the ith index represents the exclusive time for the function with ID i. Example 1: Input: n = 2; logs = [""0:start:0"";""1:start:2"";""1:end:5"";""0:end:6""] Output: [3;4] Explanation: Function 0 starts at the beginning of time 0; then it executes 2 for units of time and reaches the end of time 1. Function 1 starts at the beginning of time 2; executes for 4 units of time; and ends at the end of time 5. Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time. So function 0 spends 2 + 1 = 3 units of total time executing; and function 1 spends 4 units of total time executing. Example 2: Input: n = 1; logs = [""0:start:0"";""0:start:2"";""0:end:5"";""0:start:6"";""0:end:6"";""0:end:7""] Output: [8] Explanation: Function 0 starts at the beginning of time 0; executes for 2 units of time; and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls itself again. Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time. Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time. So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing. Example 3: Input: n = 2; logs = [""0:start:0"";""0:start:2"";""0:end:5"";""1:start:6"";""1:end:6"";""0:end:7""] Output: [7;1] Explanation: Function 0 starts at the beginning of time 0; executes for 2 units of time; and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls function 1. Function 1 starts at the beginning of time 6; executes 1 unit of time; and ends at the end of time 6. Function 0 resumes execution at the beginning of time 6 and executes for 2 units of time. So function 0 spends 2 + 4 + 1 = 7 units of total time executing; and function 1 spends 1 unit of total time executing. Constraints: 1 <= n <= 100 1 <= logs.length <= 500 0 <= function_id < n 0 <= timestamp <= 109 No two start events will happen at the same timestamp. No two end events will happen at the same timestamp. Each function has an ""end"" log for each ""start"" log."816Google,682,Baseball Game,Easy,"Array, Stack, Simulation","You are keeping the scores for a baseball game with strange rules. At the beginning of the game; you start with an empty record. You are given a list of strings operations; where operations[i] is the ith operation you must apply to the record and is one of the following: An integer x. Record a new score of x. '+'. Record a new score that is the sum of the previous two scores. 'D'. Record a new score that is the double of the previous score. 'C'. Invalidate the previous score; removing it from the record. Return the sum of all the scores on the record after applying all the operations. The test cases are generated such that the answer and all intermediate calculations fit in a 32-bit integer and that all operations are valid. Example 1: Input: ops = [""5"";""2"";""C"";""D"";""+""] Output: 30 Explanation: ""5"" - Add 5 to the record; record is now [5]. ""2"" - Add 2 to the record; record is now [5; 2]. ""C"" - Invalidate and remove the previous score; record is now [5]. ""D"" - Add 2 * 5 = 10 to the record; record is now [5; 10]. ""+"" - Add 5 + 10 = 15 to the record; record is now [5; 10; 15]. The total sum is 5 + 10 + 15 = 30. Example 2: Input: ops = [""5"";""-2"";""4"";""C"";""D"";""9"";""+"";""+""] Output: 27 Explanation: ""5"" - Add 5 to the record; record is now [5]. ""-2"" - Add -2 to the record; record is now [5; -2]. ""4"" - Add 4 to the record; record is now [5; -2; 4]. ""C"" - Invalidate and remove the previous score; record is now [5; -2]. ""D"" - Add 2 * -2 = -4 to the record; record is now [5; -2; -4]. ""9"" - Add 9 to the record; record is now [5; -2; -4; 9]. ""+"" - Add -4 + 9 = 5 to the record; record is now [5; -2; -4; 9; 5]. ""+"" - Add 9 + 5 = 14 to the record; record is now [5; -2; -4; 9; 5; 14]. The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27. Example 3: Input: ops = [""1"";""C""] Output: 0 Explanation: ""1"" - Add 1 to the record; record is now [1]. ""C"" - Invalidate and remove the previous score; record is now []. Since the record is empty; the total sum is 0. Constraints: 1 <= operations.length <= 1000 operations[i] is ""C""; ""D""; ""+""; or a string representing an integer in the range [-3 * 104; 3 * 104]. For operation ""+""; there will always be at least two previous scores on the record. For operations ""C"" and ""D""; there will always be at least one previous score on the record."817Google,684,Redundant Connection,Med,"Depth-First Search, Breadth-First Search, Union Find, Graph",In this problem; a tree is an undirected graph that is connected and has no cycles. You are given a graph that started as a tree with n nodes labeled from 1 to n; with one additional edge added. The added edge has two different vertices chosen from 1 to n; and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai; bi] indicates that there is an edge between nodes ai and bi in the graph. Return an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers; return the answer that occurs last in the input. Example 1: Input: edges = [[1;2];[1;3];[2;3]] Output: [2;3] Example 2: Input: edges = [[1;2];[2;3];[3;4];[1;4];[1;5]] Output: [1;4] Constraints: n == edges.length 3 <= n <= 1000 edges[i].length == 2 1 <= ai < bi <= edges.length ai != bi There are no repeated edges. The given graph is connected.818Google,686,Repeated String Match,Med,"String, String Matching","Given two strings a and b; return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for b​​​​​​ to be a substring of a after repeating it; return -1. Notice: string ""abc"" repeated 0 times is """"; repeated 1 time is ""abc"" and repeated 2 times is ""abcabc"". Example 1: Input: a = ""abcd""; b = ""cdabcdab"" Output: 3 Explanation: We return 3 because by repeating a three times ""abcdabcdabcd""; b is a substring of it. Example 2: Input: a = ""a""; b = ""aa"" Output: 2 Constraints: 1 <= a.length; b.length <= 104 a and b consist of lowercase English letters."819Google,718,Maximum Length of Repeated Subarray,Med,"Array, Binary Search, Dynamic Programming, Sliding Window, Rolling Hash, Hash Function",Given two integer arrays nums1 and nums2; return the maximum length of a subarray that appears in both arrays. Example 1: 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]. Example 2: Input: nums1 = [0;0;0;0;0]; nums2 = [0;0;0;0;0] Output: 5 Explanation: The repeated subarray with maximum length is [0;0;0;0;0]. Constraints: 1 <= nums1.length; nums2.length <= 1000 0 <= nums1[i]; nums2[i] <= 100820Google,724,Find Pivot Index,Easy,"Array, Prefix Sum",Given an array of integers nums; calculate the pivot index of this array. The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. If the index is on the left edge of the array; then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array. Return the leftmost pivot index. If no such index exists; return -1. Example 1: Input: nums = [1;7;3;6;5;6] Output: 3 Explanation: The pivot index is 3. Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 Right sum = nums[4] + nums[5] = 5 + 6 = 11 Example 2: Input: nums = [1;2;3] Output: -1 Explanation: There is no index that satisfies the conditions in the problem statement. Example 3: Input: nums = [2;1;-1] Output: 0 Explanation: The pivot index is 0. Left sum = 0 (no elements to the left of index 0) Right sum = nums[1] + nums[2] = 1 + -1 = 0 Constraints: 1 <= nums.length <= 104 -1000 <= nums[i] <= 1000 Note: This question is the same as 1991: https://leetcode.com/problems/find-the-middle-index-in-array/821Google,729,My Calendar I,Med,"Array, Binary Search, Design, Segment Tree, Ordered Set","You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a double booking. A double booking happens when two events have some non-empty intersection (i.e.; some moment is common to both events.). The event can be represented as a pair of integers startTime and endTime that represents a booking on the half-open interval [startTime; endTime); the range of real numbers x such that startTime <= x < endTime. Implement the MyCalendar class: MyCalendar() Initializes the calendar object. boolean book(int startTime; int endTime) Returns true if the event can be added to the calendar successfully without causing a double booking. Otherwise; return false and do not add the event to the calendar. Example 1: Input [""MyCalendar""; ""book""; ""book""; ""book""] [[]; [10; 20]; [15; 25]; [20; 30]] Output [null; true; false; true] Explanation MyCalendar myCalendar = new MyCalendar(); myCalendar.book(10; 20); // return True myCalendar.book(15; 25); // return False; It can not be booked because time 15 is already booked by another event. myCalendar.book(20; 30); // return True; The event can be booked; as the first event takes every time less than 20; but not including 20. Constraints: 0 <= start < end <= 109 At most 1000 calls will be made to book."822Google,731,My Calendar II,Med,"Array, Binary Search, Design, Segment Tree, Prefix Sum, Ordered Set","You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking. A triple booking happens when three events have some non-empty intersection (i.e.; some moment is common to all the three events.). The event can be represented as a pair of integers startTime and endTime that represents a booking on the half-open interval [startTime; endTime); the range of real numbers x such that startTime <= x < endTime. Implement the MyCalendarTwo class: MyCalendarTwo() Initializes the calendar object. boolean book(int startTime; int endTime) Returns true if the event can be added to the calendar successfully without causing a triple booking. Otherwise; return false and do not add the event to the calendar. Example 1: Input [""MyCalendarTwo""; ""book""; ""book""; ""book""; ""book""; ""book""; ""book""] [[]; [10; 20]; [50; 60]; [10; 40]; [5; 15]; [5; 10]; [25; 55]] Output [null; true; true; true; false; true; true] Explanation MyCalendarTwo myCalendarTwo = new MyCalendarTwo(); myCalendarTwo.book(10; 20); // return True; The event can be booked. myCalendarTwo.book(50; 60); // return True; The event can be booked. myCalendarTwo.book(10; 40); // return True; The event can be double booked. myCalendarTwo.book(5; 15); // return False; The event cannot be booked; because it would result in a triple booking. myCalendarTwo.book(5; 10); // return True; The event can be booked; as it does not use time 10 which is already double booked. myCalendarTwo.book(25; 55); // return True; The event can be booked; as the time in [25; 40) will be double booked with the third event; the time [40; 50) will be single booked; and the time [50; 55) will be double booked with the second event. Constraints: 0 <= start < end <= 109 At most 1000 calls will be made to book."823Google,741,Cherry Pickup,Hard,"Array, Dynamic Programming, Matrix",You are given an n x n grid representing a field of cherries; each cell is one of three possible integers. 0 means the cell is empty; so you can pass through; 1 means the cell contains a cherry that you can pick up and pass through; or -1 means the cell contains a thorn that blocks your way. Return the maximum number of cherries you can collect by following the rules below: Starting at the position (0; 0) and reaching (n - 1; n - 1) by moving right or down through valid path cells (cells with value 0 or 1). After reaching (n - 1; n - 1); returning to (0; 0) by moving left or up through valid path cells. When passing through a path cell containing a cherry; you pick it up; and the cell becomes an empty cell 0. If there is no valid path between (0; 0) and (n - 1; n - 1); then no cherries can be collected. Example 1: Input: grid = [[0;1;-1];[1;0;-1];[1;1;1]] Output: 5 Explanation: The player started at (0; 0) and went down; down; right right to reach (2; 2). 4 cherries were picked up during this single trip; and the matrix becomes [[0;1;-1];[0;0;-1];[0;0;0]]. Then; the player went left; up; up; left to return home; picking up one more cherry. The total number of cherries picked up is 5; and this is the maximum possible. Example 2: Input: grid = [[1;1;-1];[1;-1;1];[-1;1;1]] Output: 0 Constraints: n == grid.length n == grid[i].length 1 <= n <= 50 grid[i][j] is -1; 0; or 1. grid[0][0] != -1 grid[n - 1][n - 1] != -1824Google,709,To Lower Case,Easy,,825Google,771,Jewels and Stones,Easy,"Tree, Depth-First Search, Breadth-First Search, Design, Binary Tree",826Google,779,K-th Symbol in Grammar,Med,"Array, Stack, Greedy, Sorting, Monotonic Stack",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. Example 1: Input: arr = [5;4;3;2;1] Output: 1 Explanation: Splitting into two or more chunks will not return the required result. For example; splitting into [5; 4]; [3; 2; 1] will result in [4; 5; 1; 2; 3]; which isn't sorted. Example 2: 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. Constraints: 1 <= arr.length <= 2000 0 <= arr[i] <= 108827Google,785,Is Graph Bipartite?,Med,"Math, String, Stack, Recursion",828Google,706,Design HashMap,Easy,,829Google,810,Chalkboard XOR Game,Hard,"Array, Matrix","Given a Tic-Tac-Toe board as a string array board; return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game. The board is a 3 x 3 array that consists of characters ' '; 'X'; and 'O'. The ' ' character represents an empty square. Here are the rules of Tic-Tac-Toe: Players take turns placing characters into empty squares ' '. The first player always places 'X' characters; while the second player always places 'O' characters. 'X' and 'O' characters are always placed into empty squares; never filled ones. The game ends when there are three of the same (non-empty) character filling any row; column; or diagonal. The game also ends if all squares are non-empty. No more moves can be played if the game is over. Example 1: Input: board = [""O "";"" "";"" ""] Output: false Explanation: The first player always plays ""X"". Example 2: Input: board = [""XOX"";"" X "";"" ""] Output: false Explanation: Players take turns making moves. Example 3: Input: board = [""XOX"";""O O"";""XOX""] Output: true Constraints: board.length == 3 board[i].length == 3 board[i][j] is either 'X'; 'O'; or ' '."830Google,827,Making A Large Island,Hard,"Array, Two Pointers, String","Sometimes people repeat letters to represent extra feeling. For example: ""hello"" -> ""heeellooo"" ""hi"" -> ""hiiii"" In these strings like ""heeellooo""; we have groups of adjacent letters that are all the same: ""h""; ""eee""; ""ll""; ""ooo"". You are given a string s and an array of query strings words. A query word is stretchy if it can be made to be equal to s by any number of applications of the following extension operation: choose a group consisting of characters c; and add some number of characters c to the group so that the size of the group is three or more. For example; starting with ""hello""; we could do an extension on the group ""o"" to get ""hellooo""; but we cannot get ""helloo"" since the group ""oo"" has a size less than three. Also; we could do another extension like ""ll"" -> ""lllll"" to get ""helllllooo"". If s = ""helllllooo""; then the query word ""hello"" would be stretchy because of these two extension operations: query = ""hello"" -> ""hellooo"" -> ""helllllooo"" = s. Return the number of query strings that are stretchy. Example 1: Input: s = ""heeellooo""; words = [""hello""; ""hi""; ""helo""] Output: 1 Explanation: We can extend ""e"" and ""o"" in the word ""hello"" to get ""heeellooo"". We can't extend ""helo"" to get ""heeellooo"" because the group ""ll"" is not size 3 or more. Example 2: Input: s = ""zzzzzyyyyy""; words = [""zzyy"";""zy"";""zyy""] Output: 3 Constraints: 1 <= s.length; words.length <= 100 1 <= words[i].length <= 100 s and words[i] consist of lowercase letters."831Google,489,Robot Room Cleaner,Hard,"Array, Math, Dynamic Programming, Combinatorics","Bob is standing at cell (0; 0); and he wants to reach destination: (row; column). He can only travel right and down. You are going to help Bob by providing instructions for him to reach destination. The instructions are represented as a string; where each character is either: 'H'; meaning move horizontally (go right); or 'V'; meaning move vertically (go down). Multiple instructions will lead Bob to destination. For example; if destination is (2; 3); both ""HHHVV"" and ""HVHVH"" are valid instructions. However; Bob is very picky. Bob has a lucky number k; and he wants the kth lexicographically smallest instructions that will lead him to destination. k is 1-indexed. Given an integer array destination and an integer k; return the kth lexicographically smallest instructions that will take Bob to destination. Example 1: Input: destination = [2;3]; k = 1 Output: ""HHHVV"" Explanation: All the instructions that reach (2; 3) in lexicographic order are as follows: [""HHHVV""; ""HHVHV""; ""HHVVH""; ""HVHHV""; ""HVHVH""; ""HVVHH""; ""VHHHV""; ""VHHVH""; ""VHVHH""; ""VVHHH""]. Example 2: Input: destination = [2;3]; k = 2 Output: ""HHVHV"" Example 3: Input: destination = [2;3]; k = 3 Output: ""HHVVH"" Constraints: destination.length == 2 1 <= row; column <= 15 1 <= k <= nCr(row + column; row); where nCr(a; b) denotes a choose b​​​​​."832Google,877,Stone Game,Med,"Dynamic Programming, Bit Manipulation, Breadth-First Search, Graph, Bitmask",You have an undirected; connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge. Return the length of the shortest path that visits every node. You may start and stop at any node; you may revisit nodes multiple times; and you may reuse edges. Example 1: Input: graph = [[1;2;3];[0];[0];[0]] Output: 4 Explanation: One possible path is [1;0;2;0;3] Example 2: Input: graph = [[1];[0;2;4];[1;3;4];[2];[1;2]] Output: 4 Explanation: One possible path is [0;1;4;2;3] Constraints: n == graph.length 1 <= n <= 12 0 <= graph[i].length < n graph[i] does not contain i. If graph[a] contains b; then graph[b] contains a. The input graph is always connected.833Google,881,Boats to Save People,Med,"Array, Depth-First Search, Graph, Topological Sort",There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness. You are given an array richer where richer[i] = [ai; bi] indicates that ai has more money than bi and an integer array quiet where quiet[i] is the quietness of the ith person. All the given data in richer are logically correct (i.e.; the data will not lead you to a situation where x is richer than y and y is richer than x at the same time). Return an integer array answer where answer[x] = y if y is the least quiet person (that is; the person y with the smallest value of quiet[y]) among all people who definitely have equal to or more money than the person x. Example 1: Input: richer = [[1;0];[2;1];[3;1];[3;7];[4;3];[5;3];[6;3]]; quiet = [3;2;5;4;6;1;7;0] Output: [5;5;2;5;4;5;6;7] Explanation: answer[0] = 5. Person 5 has more money than 3; which has more money than 1; which has more money than 0. The only person who is quieter (has lower quiet[x]) is person 7; but it is not clear if they have more money than person 0. answer[7] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3; 4; 5; 6; or 7); the person who is the quietest (has lower quiet[x]) is person 7. The other answers can be filled out with similar reasoning. Example 2: Input: richer = []; quiet = [0] Output: [0] Constraints: n == quiet.length 1 <= n <= 500 0 <= quiet[i] < n All the values of quiet are unique. 0 <= richer.length <= n * (n - 1) / 2 0 <= ai; bi < n ai != bi All the pairs of richer are unique. The observations in richer are all logically consistent.834Google,884,Uncommon Words from Two Sentences,Easy,"String, Breadth-First Search","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. Example 1: Input: s1 = ""ab""; s2 = ""ba"" Output: 1 Explanation: The two string are 1-similar because we can use one swap to change s1 to s2: ""ab"" --> ""ba"". Example 2: 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"". Constraints: 1 <= s1.length <= 20 s2.length == s1.length s1 and s2 contain only lowercase letters from the set {'a'; 'b'; 'c'; 'd'; 'e'; 'f'}. s2 is an anagram of s1."835Google,888,Fair Candy Swap,Easy,"Math, Geometry, Number Theory",There is a special square room with mirrors on each of the four walls. Except for the southwest corner; there are receptors on each of the remaining corners; numbered 0; 1; and 2. The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor. Given the two integers p and q; return the number of the receptor that the ray meets first. The test cases are guaranteed so that the ray will meet a receptor eventually. Example 1: Input: p = 2; q = 1 Output: 2 Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall. Example 2: Input: p = 3; q = 1 Output: 1 Constraints: 1 <= q <= p <= 1000836Google,901,Online Stock Span,Med,"Array, Two Pointers, Greedy, Sorting",You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i]. Return any permutation of nums1 that maximizes its advantage with respect to nums2. Example 1: Input: nums1 = [2;7;11;15]; nums2 = [1;10;4;11] Output: [2;11;7;15] Example 2: Input: nums1 = [12;24;8;32]; nums2 = [13;25;32;11] Output: [24;32;8;12] Constraints: 1 <= nums1.length <= 105 nums2.length == nums1.length 0 <= nums1[i]; nums2[i] <= 109837Google,907,Sum of Subarray Minimums,Med,"Array, Binary Search",Koko loves to eat bananas. There are n piles of bananas; the ith pile has piles[i] bananas. The guards have gone and will come back in h hours. Koko can decide her bananas-per-hour eating speed of k. Each hour; she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas; she eats all of them instead and will not eat any more bananas during this hour. Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. Return the minimum integer k such that she can eat all the bananas within h hours. Example 1: Input: piles = [3;6;7;11]; h = 8 Output: 4 Example 2: Input: piles = [30;11;23;4;20]; h = 5 Output: 30 Example 3: Input: piles = [30;11;23;4;20]; h = 6 Output: 23 Constraints: 1 <= piles.length <= 104 piles.length <= h <= 109 1 <= piles[i] <= 109838Google,929,Unique Email Addresses,Easy,"Array, Hash Table, String, Sorting","You are given an array of strings of the same length words. In one move; you can swap any two even indexed characters or any two odd indexed characters of a string words[i]. Two strings words[i] and words[j] are special-equivalent if after any number of moves; words[i] == words[j]. For example; words[i] = ""zzxy"" and words[j] = ""xyzz"" are special-equivalent because we may make the moves ""zzxy"" -> ""xzzy"" -> ""xyzz"". A group of special-equivalent strings from words is a non-empty subset of words such that: Every pair of strings in the group are special equivalent; and The group is the largest size possible (i.e.; there is not a string words[i] not in the group such that words[i] is special-equivalent to every string in the group). Return the number of groups of special-equivalent strings from words. Example 1: Input: words = [""abcd"";""cdab"";""cbad"";""xyzz"";""zzxy"";""zzyx""] Output: 3 Explanation: One group is [""abcd""; ""cdab""; ""cbad""]; since they are all pairwise special equivalent; and none of the other strings is all pairwise special equivalent to these. The other two groups are [""xyzz""; ""zzxy""] and [""zzyx""]. Note that in particular; ""zzxy"" is not special equivalent to ""zzyx"". Example 2: Input: words = [""abc"";""acb"";""bac"";""bca"";""cab"";""cba""] Output: 3 Constraints: 1 <= words.length <= 1000 1 <= words[i].length <= 20 words[i] consist of lowercase English letters. All the strings are of the same length."839Google,930,Binary Subarrays With Sum,Med,"Dynamic Programming, Tree, Recursion, Memoization, Binary Tree",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. Example 1: 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]] Example 2: Input: n = 3 Output: [[0;0;0]] Constraints: 1 <= n <= 20840Google,934,Shortest Bridge,Med,"Array, Dynamic Programming, Bit Manipulation",Given an integer array arr; return the number of distinct bitwise ORs of all the non-empty subarrays of arr. The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: arr = [0] Output: 1 Explanation: There is only one possible result: 0. Example 2: Input: arr = [1;1;2] Output: 3 Explanation: The possible subarrays are [1]; [1]; [2]; [1; 1]; [1; 2]; [1; 1; 2]. These yield the results 1; 1; 2; 1; 3; 3. There are 3 unique values; so the answer is 3. Example 3: Input: arr = [1;2;4] Output: 6 Explanation: The possible results are 1; 2; 3; 4; 6; and 7. Constraints: 1 <= arr.length <= 5 * 104 0 <= arr[i] <= 109841Google,974,Subarray Sums Divisible by K,Med,"Array, String, Sorting","You are given an array of logs. Each log is a space-delimited string of words; where the first word is the identifier. There are two types of logs: Letter-logs: All words (except the identifier) consist of lowercase English letters. Digit-logs: All words (except the identifier) consist of digits. Reorder these logs so that: The letter-logs come before all digit-logs. The letter-logs are sorted lexicographically by their contents. If their contents are the same; then sort them lexicographically by their identifiers. The digit-logs maintain their relative ordering. Return the final order of the logs. Example 1: Input: logs = [""dig1 8 1 5 1"";""let1 art can"";""dig2 3 6"";""let2 own kit dig"";""let3 art zero""] Output: [""let1 art can"";""let3 art zero"";""let2 own kit dig"";""dig1 8 1 5 1"";""dig2 3 6""] Explanation: The letter-log contents are all different; so their ordering is ""art can""; ""art zero""; ""own kit dig"". The digit-logs have a relative order of ""dig1 8 1 5 1""; ""dig2 3 6"". Example 2: Input: logs = [""a1 9 2 3 1"";""g1 act car"";""zo4 4 7"";""ab1 off key dog"";""a8 act zoo""] Output: [""g1 act car"";""a8 act zoo"";""ab1 off key dog"";""a1 9 2 3 1"";""zo4 4 7""] Constraints: 1 <= logs.length <= 100 3 <= logs[i].length <= 100 All the tokens of logs[i] are separated by a single space. logs[i] is guaranteed to have an identifier and at least one word after the identifier."842Google,981,Time Based Key-Value Store,Med,"Array, String","You are given an array of n strings strs; all of the same length. The strings can be arranged such that there is one on each line; making a grid. For example; strs = [""abc""; ""bce""; ""cae""] can be arranged as follows: abc bce cae You want to delete the columns that are not sorted lexicographically. In the above example (0-indexed); columns 0 ('a'; 'b'; 'c') and 2 ('c'; 'e'; 'e') are sorted; while column 1 ('b'; 'c'; 'a') is not; so you would delete column 1. Return the number of columns that you will delete. Example 1: Input: strs = [""cba"";""daf"";""ghi""] Output: 1 Explanation: The grid looks as follows: cba daf ghi Columns 0 and 2 are sorted; but column 1 is not; so you only need to delete 1 column. Example 2: Input: strs = [""a"";""b""] Output: 0 Explanation: The grid looks as follows: a b Column 0 is the only column and is sorted; so you will not delete any columns. Example 3: Input: strs = [""zyx"";""wvu"";""tsr""] Output: 3 Explanation: The grid looks as follows: zyx wvu tsr All 3 columns are not sorted; so you will delete all 3. Constraints: n == strs.length 1 <= n <= 100 1 <= strs[i].length <= 1000 strs[i] consists of lowercase English letters."843Google,997,Find the Town Judge,Easy,,844Google,1043,Partition Array for Maximum Sum,Med,"Array, Hash Table",There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off. You are given a 2D array of lamp positions lamps; where lamps[i] = [rowi; coli] indicates that the lamp at grid[rowi][coli] is turned on. Even if the same lamp is listed more than once; it is turned on. When a lamp is turned on; it illuminates its cell and all other cells in the same row; column; or diagonal. You are also given another 2D array queries; where queries[j] = [rowj; colj]. For the jth query; determine whether grid[rowj][colj] is illuminated or not. After answering the jth query; turn off the lamp at grid[rowj][colj] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[rowj][colj]. Return an array of integers ans; where ans[j] should be 1 if the cell in the jth query was illuminated; or 0 if the lamp was not. Example 1: Input: n = 5; lamps = [[0;0];[4;4]]; queries = [[1;1];[1;0]] Output: [1;0] Explanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4]. The 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated; so set ans[0] = 1. Then; we turn off all lamps in the red square. The 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated; so set ans[1] = 0. Then; we turn off all lamps in the red rectangle. Example 2: Input: n = 5; lamps = [[0;0];[4;4]]; queries = [[1;1];[1;1]] Output: [1;1] Example 3: Input: n = 5; lamps = [[0;0];[0;4]]; queries = [[0;4];[0;1];[1;4]] Output: [1;1;0] Constraints: 1 <= n <= 109 0 <= lamps.length <= 20000 0 <= queries.length <= 20000 lamps[i].length == 2 0 <= rowi; coli < n queries[j].length == 2 0 <= rowj; colj < n845Google,1074,Number of Submatrices That Sum to Target,Hard,"Array, Hash Table, Sorting, Heap (Priority Queue)",846Google,1068,Product Sales Analysis I,Easy,"Math, Dynamic Programming",847Google,1229,Meeting Scheduler,Med,"Breadth-First Search, Graph",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. Example 1: Input: n = 3; redEdges = [[0;1];[1;2]]; blueEdges = [] Output: [0;1;-1] Example 2: Input: n = 3; redEdges = [[0;1]]; blueEdges = [[2;1]] Output: [0;1;-1] Constraints: 1 <= n <= 100 0 <= redEdges.length; blueEdges.length <= 400 redEdges[i].length == blueEdges[j].length == 2 0 <= ai; bi; uj; vj < n848Google,1089,Duplicate Zeros,Easy,String,849Google,1091,Shortest Path in Binary Matrix,Med,"Tree, Depth-First Search, Binary Tree",850Google,550,Game Play Analysis IV,Med,"Array, Breadth-First Search, Matrix",851Google,1164,Product Price at a Given Date,Med,"Array, Math",852Google,1185,Day of the Week,Easy,"Array, Binary Search, Interactive",(This problem is an interactive problem.) You may recall that an array arr is a mountain array if and only if: arr.length >= 3 There exists some i 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 a mountain array mountainArr; return the minimum index such that mountainArr.get(index) == target. If such an index does not exist; return -1. You cannot access the mountain array directly. You may only access the array using a MountainArray interface: MountainArray.get(k) returns the element of the array at index k (0-indexed). MountainArray.length() returns the length of the array. Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also; any solutions that attempt to circumvent the judge will result in disqualification. Example 1: Input: mountainArr = [1;2;3;4;5;3;1]; target = 3 Output: 2 Explanation: 3 exists in the array; at index=2 and index=5. Return the minimum index; which is 2. Example 2: Input: mountainArr = [0;1;2;4;2;1]; target = 3 Output: -1 Explanation: 3 does not exist in the array; so we return -1. Constraints: 3 <= mountainArr.length() <= 104 0 <= target <= 109 0 <= mountainArr.get(index) <= 109853Google,1174,Immediate Food Delivery II,Med,Database,Table: Product +--------------+---------+ | Column Name | Type | +--------------+---------+ | product_id | int | | product_name | varchar | | unit_price | int | +--------------+---------+ product_id is the primary key (column with unique values) of this table. Each row of this table indicates the name and the price of each product. Table: Sales +-------------+---------+ | Column Name | Type | +-------------+---------+ | seller_id | int | | product_id | int | | buyer_id | int | | sale_date | date | | quantity | int | | price | int | +-------------+---------+ This table can have duplicate rows. product_id is a foreign key (reference column) to the Product table. Each row of this table contains some information about one sale. Write a solution to report the products that were only sold in the first quarter of 2019. That is; between 2019-01-01 and 2019-03-31 inclusive. Return the result table in any order. The result format is in the following example. Example 1: Input: Product table: +------------+--------------+------------+ | product_id | product_name | unit_price | +------------+--------------+------------+ | 1 | S8 | 1000 | | 2 | G4 | 800 | | 3 | iPhone | 1400 | +------------+--------------+------------+ Sales table: +-----------+------------+----------+------------+----------+-------+ | seller_id | product_id | buyer_id | sale_date | quantity | price | +-----------+------------+----------+------------+----------+-------+ | 1 | 1 | 1 | 2019-01-21 | 2 | 2000 | | 1 | 2 | 2 | 2019-02-17 | 1 | 800 | | 2 | 2 | 3 | 2019-06-02 | 1 | 800 | | 3 | 3 | 4 | 2019-05-13 | 2 | 2800 | +-----------+------------+----------+------------+----------+-------+ Output: +-------------+--------------+ | product_id | product_name | +-------------+--------------+ | 1 | S8 | +-------------+--------------+ Explanation: The product with id 1 was only sold in the spring of 2019. The product with id 2 was sold in the spring of 2019 but was also sold after the spring of 2019. The product with id 3 was sold after spring 2019. We return only product 1 as it is the product that was only sold in the spring of 2019.854Google,1193,Monthly Transactions I,Med,Database,855Google,1514,Path with Maximum Probability,Med,"Array, Prefix Sum",Given an array of integers nums; you start with an initial positive value startValue. In each iteration; you calculate the step by step sum of startValue plus elements in nums (from left to right). Return the minimum positive value of startValue such that the step by step sum is never less than 1. Example 1: Input: nums = [-3;2;-3;4;2] Output: 5 Explanation: If you choose startValue = 4; in the third iteration your step by step sum is less than 1. step by step sum startValue = 4 | startValue = 5 | nums (4 -3 ) = 1 | (5 -3 ) = 2 | -3 (1 +2 ) = 3 | (2 +2 ) = 4 | 2 (3 -3 ) = 0 | (4 -3 ) = 1 | -3 (0 +4 ) = 4 | (1 +4 ) = 5 | 4 (4 +2 ) = 6 | (5 +2 ) = 7 | 2 Example 2: Input: nums = [1;2] Output: 1 Explanation: Minimum start value should be positive. Example 3: Input: nums = [1;-2;-3] Output: 5 Constraints: 1 <= nums.length <= 100 -100 <= nums[i] <= 100856Google,1691,Maximum Height by Stacking Cuboids,Hard,"Array, Depth-First Search, Breadth-First Search, Matrix, Strongly Connected Component",You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's. The grid is said to be connected if we have exactly one island; otherwise is said disconnected. In one day; we are allowed to change any single land cell (1) into a water cell (0). Return the minimum number of days to disconnect the grid. Example 1: Input: grid = [[0;1;1;0];[0;1;1;0];[0;0;0;0]] Output: 2 Explanation: We need at least 2 days to get a disconnected grid. Change land grid[1][1] and grid[0][2] to water and get 2 disconnected island. Example 2: Input: grid = [[1;1]] Output: 2 Explanation: Grid of full water is also disconnected ([[1;1]] -> [[0;0]]); 0 islands. Constraints: m == grid.length n == grid[i].length 1 <= m; n <= 30 grid[i][j] is either 0 or 1.857Google,1251,Average Selling Price,Easy,"Two Pointers, String, Dynamic Programming, Greedy, Rolling Hash, Hash Function","You are given a string text. You should split it to k substrings (subtext1; subtext2; ...; subtextk) such that: subtexti is a non-empty string. The concatenation of all the substrings is equal to text (i.e.; subtext1 + subtext2 + ... + subtextk == text). subtexti == subtextk - i + 1 for all valid values of i (i.e.; 1 <= i <= k). Return the largest possible value of k. Example 1: Input: text = ""ghiabcdefhelloadamhelloabcdefghi"" Output: 7 Explanation: We can split the string on ""(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)"". Example 2: Input: text = ""merchant"" Output: 1 Explanation: We can split the string on ""(merchant)"". Example 3: Input: text = ""antaprezatepzapreanta"" Output: 11 Explanation: We can split the string on ""(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)"". Constraints: 1 <= text.length <= 1000 text consists only of lowercase English characters."858Google,2215,Find the Difference of Two Arrays,Easy,"Array, Hash Table, Sorting, Enumeration",You are given an integer array digits; where each element is a digit. The array may contain duplicates. You need to find all the unique integers that follow the given requirements: The integer consists of the concatenation of three elements from digits in any arbitrary order. The integer does not have leading zeros. The integer is even. For example; if the given digits were [1; 2; 3]; integers 132 and 312 follow the requirements. Return a sorted array of the unique integers. Example 1: Input: digits = [2;1;3;0] Output: [102;120;130;132;210;230;302;310;312;320] Explanation: All the possible integers that follow the requirements are in the output array. Notice that there are no odd integers or integers with leading zeros. Example 2: Input: digits = [2;2;8;8;2] Output: [222;228;282;288;822;828;882] Explanation: The same digit can be used as many times as it appears in digits. In this example; the digit 8 is used twice each time in 288; 828; and 882. Example 3: Input: digits = [3;7;5] Output: [] Explanation: No even integers can be formed using the given digits. Constraints: 3 <= digits.length <= 100 0 <= digits[i] <= 9859Google,1334,Find the City With the Smallest Number of Neighbors at a Threshold Distance,Med,"Math, Dynamic Programming, Greedy, Enumeration",Given two integers num and k; consider a set of positive integers with the following properties: The units digit of each integer is k. The sum of the integers is num. Return the minimum possible size of such a set; or -1 if no such set exists. Note: The set can contain multiple instances of the same integer; and the sum of an empty set is considered 0. The units digit of a number is the rightmost digit of the number. Example 1: Input: num = 58; k = 9 Output: 2 Explanation: One valid set is [9;49]; as the sum is 58 and each integer has a units digit of 9. Another valid set is [19;39]. It can be shown that 2 is the minimum possible size of a valid set. Example 2: Input: num = 37; k = 2 Output: -1 Explanation: It is not possible to obtain a sum of 37 using only integers that have a units digit of 2. Example 3: Input: num = 0; k = 7 Output: 0 Explanation: The sum of an empty set is considered 0. Constraints: 0 <= num <= 3000 0 <= k <= 9860Google,1347,Minimum Number of Steps to Make Two Strings Anagram,Med,"Depth-First Search, Breadth-First Search, Union Find, Graph",861Google,1371,Find the Longest Substring Containing Vowels in Even Counts,Med,"String, Stack","Given a string s of '(' ; ')' and lowercase English characters. Your task is to remove the minimum number of parentheses ( '(' or ')'; in any positions ) so that the resulting parentheses string is valid and return any valid string. Formally; a parentheses string is valid if and only if: It is the empty string; contains only lowercase characters; or It can be written as AB (A concatenated with B); where A and B are valid strings; or It can be written as (A); where A is a valid string. Example 1: Input: s = ""lee(t(c)o)de)"" Output: ""lee(t(c)o)de"" Explanation: ""lee(t(co)de)"" ; ""lee(t(c)ode)"" would also be accepted. Example 2: Input: s = ""a)b(c)d"" Output: ""ab(c)d"" Example 3: Input: s = ""))(("" Output: """" Explanation: An empty string is also valid. Constraints: 1 <= s.length <= 105 s[i] is either '(' ; ')'; or lowercase English letter."862Google,1423,Maximum Points You Can Obtain from Cards,Med,"Hash Table, String, Sliding Window","Given a string s; return the maximum number of occurrences of any substring under the following rules: The number of unique characters in the substring must be less than or equal to maxLetters. The substring size must be between minSize and maxSize inclusive. Example 1: Input: s = ""aababcaab""; maxLetters = 2; minSize = 3; maxSize = 4 Output: 2 Explanation: Substring ""aab"" has 2 occurrences in the original string. It satisfies the conditions; 2 unique letters and size 3 (between minSize and maxSize). Example 2: Input: s = ""aaaa""; maxLetters = 1; minSize = 3; maxSize = 3 Output: 2 Explanation: Substring ""aaa"" occur 2 times in the string. It can overlap. Constraints: 1 <= s.length <= 105 1 <= maxLetters <= 26 1 <= minSize <= maxSize <= min(26; s.length) s consists of only lowercase English letters."863Google,1470,Shuffle the Array,Easy,"Hash Table, Binary Search, Design, Sorting, Ordered Set","A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute; hour; or day). For example; the period [10; 10000] (in seconds) would be partitioned into the following time chunks with these frequencies: Every minute (60-second chunks): [10;69]; [70;129]; [130;189]; ...; [9970;10000] Every hour (3600-second chunks): [10;3609]; [3610;7209]; [7210;10000] Every day (86400-second chunks): [10;10000] Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (10000 in the above example). Design and implement an API to help the company with their analysis. Implement the TweetCounts class: TweetCounts() Initializes the TweetCounts object. void recordTweet(String tweetName; int time) Stores the tweetName at the recorded time (in seconds). List<Integer> getTweetCountsPerFrequency(String freq; String tweetName; int startTime; int endTime) Returns a list of integers representing the number of tweets with tweetName in each time chunk for the given period of time [startTime; endTime] (in seconds) and frequency freq. freq is one of ""minute""; ""hour""; or ""day"" representing a frequency of every minute; hour; or day respectively. Example: Input [""TweetCounts"";""recordTweet"";""recordTweet"";""recordTweet"";""getTweetCountsPerFrequency"";""getTweetCountsPerFrequency"";""recordTweet"";""getTweetCountsPerFrequency""] [[];[""tweet3"";0];[""tweet3"";60];[""tweet3"";10];[""minute"";""tweet3"";0;59];[""minute"";""tweet3"";0;60];[""tweet3"";120];[""hour"";""tweet3"";0;210]] Output [null;null;null;null;[2];[2;1];null;[4]] Explanation TweetCounts tweetCounts = new TweetCounts(); tweetCounts.recordTweet(""tweet3""; 0); // New tweet ""tweet3"" at time 0 tweetCounts.recordTweet(""tweet3""; 60); // New tweet ""tweet3"" at time 60 tweetCounts.recordTweet(""tweet3""; 10); // New tweet ""tweet3"" at time 10 tweetCounts.getTweetCountsPerFrequency(""minute""; ""tweet3""; 0; 59); // return [2]; chunk [0;59] had 2 tweets tweetCounts.getTweetCountsPerFrequency(""minute""; ""tweet3""; 0; 60); // return [2;1]; chunk [0;59] had 2 tweets; chunk [60;60] had 1 tweet tweetCounts.recordTweet(""tweet3""; 120); // New tweet ""tweet3"" at time 120 tweetCounts.getTweetCountsPerFrequency(""hour""; ""tweet3""; 0; 210); // return [4]; chunk [0;210] had 4 tweets Constraints: 0 <= time; startTime; endTime <= 109 0 <= endTime - startTime <= 104 There will be at most 104 calls in total to recordTweet and getTweetCountsPerFrequency."864Google,1493,Longest Subarray of 1's After Deleting One Element,Med,"Tree, Depth-First Search, Breadth-First Search, Graph",Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second; the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices; it jumps randomly to one of them with the same probability. Otherwise; when the frog can not jump to any unvisited vertex; it jumps forever on the same vertex. The edges of the undirected tree are given in the array edges; where edges[i] = [ai; bi] means that exists an edge connecting the vertices ai and bi. Return the probability that after t seconds the frog is on the vertex target. Answers within 10-5 of the actual answer will be accepted. Example 1: Input: n = 7; edges = [[1;2];[1;3];[1;7];[2;4];[2;6];[3;5]]; t = 2; target = 4 Output: 0.16666666666666666 Explanation: The figure above shows the given graph. The frog starts at vertex 1; jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666. Example 2: Input: n = 7; edges = [[1;2];[1;3];[1;7];[2;4];[2;6];[3;5]]; t = 1; target = 7 Output: 0.3333333333333333 Explanation: The figure above shows the given graph. The frog starts at vertex 1; jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1. Constraints: 1 <= n <= 100 edges.length == n - 1 edges[i].length == 2 1 <= ai; bi <= n 1 <= t <= 50 1 <= target <= n865Google,1509,Minimum Difference Between Largest and Smallest Value in Three Moves,Med,Database,Table: Employees +---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | name | varchar | +---------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table contains the id and the name of an employee in a company. Table: EmployeeUNI +---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | unique_id | int | +---------------+---------+ (id; unique_id) is the primary key (combination of columns with unique values) for this table. Each row of this table contains the id and the corresponding unique id of an employee in the company. Write a solution to show the unique ID of each user; If a user does not have a unique ID replace just show null. Return the result table in any order. The result format is in the following example. Example 1: Input: Employees table: +----+----------+ | id | name | +----+----------+ | 1 | Alice | | 7 | Bob | | 11 | Meir | | 90 | Winston | | 3 | Jonathan | +----+----------+ EmployeeUNI table: +----+-----------+ | id | unique_id | +----+-----------+ | 3 | 1 | | 11 | 2 | | 90 | 3 | +----+-----------+ Output: +-----------+----------+ | unique_id | name | +-----------+----------+ | null | Alice | | null | Bob | | 2 | Meir | | 3 | Winston | | 1 | Jonathan | +-----------+----------+ Explanation: Alice and Bob do not have a unique ID; We will show null instead. The unique ID of Meir is 2. The unique ID of Winston is 3. The unique ID of Jonathan is 1.866Google,1525,Number of Good Ways to Split a String,Med,"Array, Binary Indexed Tree, Simulation",Given the array queries of positive integers between 1 and m; you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules: In the beginning; you have the permutation P=[1;2;3;...;m]. For the current i; find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i]. Return an array containing the result for the given queries. Example 1: Input: queries = [3;1;2;1]; m = 5 Output: [2;1;2;1] Explanation: The queries are processed as follow: For i=0: queries[i]=3; P=[1;2;3;4;5]; position of 3 in P is 2; then we move 3 to the beginning of P resulting in P=[3;1;2;4;5]. For i=1: queries[i]=1; P=[3;1;2;4;5]; position of 1 in P is 1; then we move 1 to the beginning of P resulting in P=[1;3;2;4;5]. For i=2: queries[i]=2; P=[1;3;2;4;5]; position of 2 in P is 2; then we move 2 to the beginning of P resulting in P=[2;1;3;4;5]. For i=3: queries[i]=1; P=[2;1;3;4;5]; position of 1 in P is 1; then we move 1 to the beginning of P resulting in P=[1;2;3;4;5]. Therefore; the array containing the result is [2;1;2;1]. Example 2: Input: queries = [4;1;2;2]; m = 4 Output: [3;1;2;0] Example 3: Input: queries = [7;5;5;8;3]; m = 8 Output: [6;5;0;7;5] Constraints: 1 <= m <= 10^3 1 <= queries.length <= m 1 <= queries[i] <= m867Google,1518,Water Bottles,Easy,Database,868Google,1539,Kth Missing Positive Number,Easy,"Array, Sorting, Heap (Priority Queue)",Given a 2D integer array nums; return all elements of nums in diagonal order as shown in the below images. Example 1: Input: nums = [[1;2;3];[4;5;6];[7;8;9]] Output: [1;4;2;7;5;3;8;6;9] Example 2: Input: nums = [[1;2;3;4;5];[6;7];[8];[9;10;11];[12;13;14;15;16]] Output: [1;6;2;8;7;3;9;4;12;10;5;13;11;14;15;16] Constraints: 1 <= nums.length <= 105 1 <= nums[i].length <= 105 1 <= sum(nums[i].length) <= 105 1 <= nums[i][j] <= 105869Google,1590,Make Sum Divisible by P,Med,,870Google,1652,Defuse the Bomb,Easy,"String, Greedy","You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target. In one operation; you can pick an index i where 0 <= i < n and flip all bits in the inclusive range [i; n - 1]. Flip means changing '0' to '1' and '1' to '0'. Return the minimum number of operations needed to make s equal to target. Example 1: Input: target = ""10111"" Output: 3 Explanation: Initially; s = ""00000"". Choose index i = 2: ""00000"" -> ""00111"" Choose index i = 0: ""00111"" -> ""11000"" Choose index i = 1: ""11000"" -> ""10111"" We need at least 3 flip operations to form target. Example 2: Input: target = ""101"" Output: 3 Explanation: Initially; s = ""000"". Choose index i = 0: ""000"" -> ""111"" Choose index i = 1: ""111"" -> ""100"" Choose index i = 2: ""100"" -> ""101"" We need at least 3 flip operations to form target. Example 3: Input: target = ""00000"" Output: 0 Explanation: We do not need any operations since the initial s already equals target. Constraints: n == target.length 1 <= n <= 105 target[i] is either '0' or '1'."871Google,1658,Minimum Operations to Reduce X to Zero,Med,"Array, Greedy, Matrix",Given an n x n binary grid; in one step you can choose two adjacent rows of the grid and swap them. A grid is said to be valid if all the cells above the main diagonal are zeros. Return the minimum number of steps needed to make the grid valid; or -1 if the grid cannot be valid. The main diagonal of a grid is the diagonal that starts at cell (1; 1) and ends at cell (n; n). Example 1: Input: grid = [[0;0;1];[1;1;0];[1;0;0]] Output: 3 Example 2: Input: grid = [[0;1;1;0];[0;1;1;0];[0;1;1;0];[0;1;1;0]] Output: -1 Explanation: All rows are similar; swaps have no effect on the grid. Example 3: Input: grid = [[1;0;0];[1;1;0];[1;1;1]] Output: 0 Constraints: n == grid.length == grid[i].length 1 <= n <= 200 grid[i][j] is either 0 or 1872Google,1662,Check If Two String Arrays are Equivalent,Easy,"Array, Greedy, Bit Manipulation",You are given an integer array nums. You have an integer array arr of the same length with all values set to 0 initially. You also have the following modify function: You want to use the modify function to convert arr to nums using the minimum number of calls. Return the minimum number of function calls to make nums from arr. The test cases are generated so that the answer fits in a 32-bit signed integer. Example 1: Input: nums = [1;5] Output: 5 Explanation: Increment by 1 (second element): [0; 0] to get [0; 1] (1 operation). Double all the elements: [0; 1] -> [0; 2] -> [0; 4] (2 operations). Increment by 1 (both elements) [0; 4] -> [1; 4] -> [1; 5] (2 operations). Total of operations: 1 + 2 + 2 = 5. Example 2: Input: nums = [2;2] Output: 3 Explanation: Increment by 1 (both elements) [0; 0] -> [0; 1] -> [1; 1] (2 operations). Double all the elements: [1; 1] -> [2; 2] (1 operation). Total of operations: 2 + 1 = 3. Example 3: Input: nums = [4;2;5] Output: 6 Explanation: (initial)[0;0;0] -> [1;0;0] -> [1;0;1] -> [2;0;2] -> [2;1;2] -> [4;2;4] -> [4;2;5](nums). Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 109873Google,1650,Lowest Common Ancestor of a Binary Tree III,Med,"Hash Table, Bit Manipulation, Tree, Depth-First Search",874Google,1700,Number of Students Unable to Eat Lunch,Easy,"Array, String, Dynamic Programming, Greedy","Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon. Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color; so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the ith balloon from the rope. Return the minimum time Bob needs to make the rope colorful. Example 1: Input: colors = ""abaac""; neededTime = [1;2;3;4;5] Output: 3 Explanation: In the above image; 'a' is blue; 'b' is red; and 'c' is green. Bob can remove the blue balloon at index 2. This takes 3 seconds. There are no longer two consecutive balloons of the same color. Total time = 3. Example 2: Input: colors = ""abc""; neededTime = [1;2;3] Output: 0 Explanation: The rope is already colorful. Bob does not need to remove any balloons from the rope. Example 3: Input: colors = ""aabaa""; neededTime = [1;2;3;4;1] Output: 2 Explanation: Bob will remove the balloons at indices 0 and 4. Each balloons takes 1 second to remove. There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2. Constraints: n == colors.length == neededTime.length 1 <= n <= 105 1 <= neededTime[i] <= 104 colors contains only lowercase English letters."875Google,1732,Find the Highest Altitude,Easy,"Dynamic Programming, Bit Manipulation, Memoization","Given an integer n; you must transform it into 0 using the following operations any number of times: Change the rightmost (0th) bit in the binary representation of n. Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0. Return the minimum number of operations to transform n into 0. Example 1: Input: n = 3 Output: 2 Explanation: The binary representation of 3 is ""11"". ""11"" -> ""01"" with the 2nd operation since the 0th bit is 1. ""01"" -> ""00"" with the 1st operation. Example 2: Input: n = 6 Output: 4 Explanation: The binary representation of 6 is ""110"". ""110"" -> ""010"" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0. ""010"" -> ""011"" with the 1st operation. ""011"" -> ""001"" with the 2nd operation since the 0th bit is 1. ""001"" -> ""000"" with the 1st operation. Constraints: 0 <= n <= 109"876Google,1813,Sentence Similarity III,Med,"Array, Hash Table, Sliding Window",You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements. Return the maximum score you can get by erasing exactly one subarray. An array b is called to be a subarray of a if it forms a contiguous subsequence of a; that is; if it is equal to a[l];a[l+1];...;a[r] for some (l;r). Example 1: Input: nums = [4;2;4;5;6] Output: 17 Explanation: The optimal subarray here is [2;4;5;6]. Example 2: Input: nums = [5;2;1;2;5;2;1;2;5] Output: 8 Explanation: The optimal subarray here is [5;2;1] or [1;2;5]. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 104877Google,1845,Seat Reservation Manager,Med,"Array, Greedy, Sorting, Matrix",You are given a binary matrix matrix of size m x n; and you are allowed to rearrange the columns of the matrix in any order. Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally. Example 1: Input: matrix = [[0;0;1];[1;1;1];[1;0;1]] Output: 4 Explanation: You can rearrange the columns as shown above. The largest submatrix of 1s; in bold; has an area of 4. Example 2: Input: matrix = [[1;0;1;0;1]] Output: 3 Explanation: You can rearrange the columns as shown above. The largest submatrix of 1s; in bold; has an area of 3. Example 3: Input: matrix = [[1;1;0];[1;0;1]] Output: 2 Explanation: Notice that you must rearrange entire columns; and there is no way to make a submatrix of 1s larger than an area of 2. Constraints: m == matrix.length n == matrix[i].length 1 <= m * n <= 105 matrix[i][j] is either 0 or 1.878Google,1838,Frequency of the Most Frequent Element,Med,"String, Trie, Rolling Hash, Suffix Array, Hash Function",879Google,1820,Maximum Number of Accepted Invitations,Med,"Tree, Graph",You are given an array pairs; where pairs[i] = [xi; yi]; and: There are no duplicates. xi < yi Let ways be the number of rooted trees that satisfy the following conditions: The tree consists of nodes whose values appeared in pairs. A pair [xi; yi] exists in pairs if and only if xi is an ancestor of yi or yi is an ancestor of xi. Note: the tree does not have to be a binary tree. Two ways are considered to be different if there is at least one node that has different parents in both ways. Return: 0 if ways == 0 1 if ways == 1 2 if ways > 1 A rooted tree is a tree that has a single root node; and all edges are oriented to be outgoing from the root. An ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors. Example 1: Input: pairs = [[1;2];[2;3]] Output: 1 Explanation: There is exactly one valid rooted tree; which is shown in the above figure. Example 2: Input: pairs = [[1;2];[2;3];[1;3]] Output: 2 Explanation: There are multiple valid rooted trees. Three of them are shown in the above figures. Example 3: Input: pairs = [[1;2];[2;3];[2;4];[1;5]] Output: 0 Explanation: There are no valid rooted trees. Constraints: 1 <= pairs.length <= 105 1 <= xi < yi <= 500 The elements in pairs are unique.880Google,1859,Sorting the Sentence,Easy,"Hash Table, String, Counting, Prefix Sum","You are given two strings a and b that consist of lowercase letters. In one operation; you can change any character in a or b to any lowercase letter. Your goal is to satisfy one of the following three conditions: Every letter in a is strictly less than every letter in b in the alphabet. Every letter in b is strictly less than every letter in a in the alphabet. Both a and b consist of only one distinct letter. Return the minimum number of operations needed to achieve your goal. Example 1: Input: a = ""aba""; b = ""caa"" Output: 2 Explanation: Consider the best way to make each condition true: 1) Change b to ""ccc"" in 2 operations; then every letter in a is less than every letter in b. 2) Change a to ""bbb"" and b to ""aaa"" in 3 operations; then every letter in b is less than every letter in a. 3) Change a to ""aaa"" and b to ""aaa"" in 2 operations; then a and b consist of one distinct letter. The best way was done in 2 operations (either condition 1 or condition 3). Example 2: Input: a = ""dabadd""; b = ""cda"" Output: 3 Explanation: The best way is to make condition 1 true by changing b to ""eee"". Constraints: 1 <= a.length; b.length <= 105 a and b consist only of lowercase letters."881Google,1894,Find the Student that Will Replace the Chalk,Med,"Two Pointers, String","You are given two strings word1 and word2. Merge the strings by adding letters in alternating order; starting with word1. If a string is longer than the other; append the additional letters onto the end of the merged string. Return the merged string. Example 1: Input: word1 = ""abc""; word2 = ""pqr"" Output: ""apbqcr"" Explanation: The merged string will be merged as so: word1: a b c word2: p q r merged: a p b q c r Example 2: Input: word1 = ""ab""; word2 = ""pqrs"" Output: ""apbqrs"" Explanation: Notice that as word2 is longer; ""rs"" is appended to the end. word1: a b word2: p q r s merged: a p b q r s Example 3: Input: word1 = ""abcd""; word2 = ""pq"" Output: ""apbqcd"" Explanation: Notice that as word1 is longer; ""cd"" is appended to the end. word1: a b c d word2: p q merged: a p b q c d Constraints: 1 <= word1.length; word2.length <= 100 word1 and word2 consist of lowercase English letters."882Google,1905,Count Sub Islands,Med,"Hash Table, Linked List, Design, Doubly-Linked List","There is an authentication system that works with authentication tokens. For each session; the user will receive a new authentication token that will expire timeToLive seconds after the currentTime. If the token is renewed; the expiry time will be extended to expire timeToLive seconds after the (potentially different) currentTime. Implement the AuthenticationManager class: AuthenticationManager(int timeToLive) constructs the AuthenticationManager and sets the timeToLive. generate(string tokenId; int currentTime) generates a new token with the given tokenId at the given currentTime in seconds. renew(string tokenId; int currentTime) renews the unexpired token with the given tokenId at the given currentTime in seconds. If there are no unexpired tokens with the given tokenId; the request is ignored; and nothing happens. countUnexpiredTokens(int currentTime) returns the number of unexpired tokens at the given currentTime. Note that if a token expires at time t; and another action happens on time t (renew or countUnexpiredTokens); the expiration takes place before the other actions. Example 1: Input [""AuthenticationManager""; ""renew""; ""generate""; ""countUnexpiredTokens""; ""generate""; ""renew""; ""renew""; ""countUnexpiredTokens""] [[5]; [""aaa""; 1]; [""aaa""; 2]; [6]; [""bbb""; 7]; [""aaa""; 8]; [""bbb""; 10]; [15]] Output [null; null; null; 1; null; null; null; 0] Explanation AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with timeToLive = 5 seconds. authenticationManager.renew(""aaa""; 1); // No token exists with tokenId ""aaa"" at time 1; so nothing happens. authenticationManager.generate(""aaa""; 2); // Generates a new token with tokenId ""aaa"" at time 2. authenticationManager.countUnexpiredTokens(6); // The token with tokenId ""aaa"" is the only unexpired one at time 6; so return 1. authenticationManager.generate(""bbb""; 7); // Generates a new token with tokenId ""bbb"" at time 7. authenticationManager.renew(""aaa""; 8); // The token with tokenId ""aaa"" expired at time 7; and 8 >= 7; so at time 8 the renew request is ignored; and nothing happens. authenticationManager.renew(""bbb""; 10); // The token with tokenId ""bbb"" is unexpired at time 10; so the renew request is fulfilled and now the token will expire at time 15. authenticationManager.countUnexpiredTokens(15); // The token with tokenId ""bbb"" expires at time 15; and the token with tokenId ""aaa"" expired at time 7; so currently no token is unexpired; so return 0. Constraints: 1 <= timeToLive <= 108 1 <= currentTime <= 108 1 <= tokenId.length <= 5 tokenId consists only of lowercase letters. All calls to generate will contain unique values of tokenId. The values of currentTime across all the function calls will be strictly increasing. At most 2000 calls will be made to all functions combined."883Google,1920,Build Array from Permutation,Easy,"Math, String","You are given coordinates; a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return true if the square is white; and false if the square is black. The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first; and the number second. Example 1: Input: coordinates = ""a1"" Output: false Explanation: From the chessboard above; the square with coordinates ""a1"" is black; so return false. Example 2: Input: coordinates = ""h3"" Output: true Explanation: From the chessboard above; the square with coordinates ""h3"" is white; so return true. Example 3: Input: coordinates = ""c7"" Output: false Constraints: coordinates.length == 2 'a' <= coordinates[0] <= 'h' '1' <= coordinates[1] <= '8'"884Google,1929,Concatenation of Array,Easy,"Binary Search, Greedy",You are given three positive integers: n; index; and maxSum. You want to construct an array nums (0-indexed) that satisfies the following conditions: nums.length == n nums[i] is a positive integer where 0 <= i < n. abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1. The sum of all the elements of nums does not exceed maxSum. nums[index] is maximized. Return nums[index] of the constructed array. Note that abs(x) equals x if x >= 0; and -x otherwise. Example 1: Input: n = 4; index = 2; maxSum = 6 Output: 2 Explanation: nums = [1;2;2;1] is one array that satisfies all the conditions. There are no arrays that satisfy all the conditions and have nums[2] == 3; so 2 is the maximum nums[2]. Example 2: Input: n = 6; index = 1; maxSum = 10 Output: 3 Constraints: 1 <= n <= maxSum <= 109 0 <= index < n885Google,1945,Sum of Digits of String After Convert,Easy,"Array, Hash Table",You are given the logs for users' actions on LeetCode; and an integer k. The logs are represented by a 2D integer array logs where each logs[i] = [IDi; timei] indicates that the user with IDi performed an action at the minute timei. Multiple users can perform actions simultaneously; and a single user can perform multiple actions in the same minute. The user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once; even if multiple actions occur during it. You are to calculate a 1-indexed array answer of size k such that; for each j (1 <= j <= k); answer[j] is the number of users whose UAM equals j. Return the array answer as described above. Example 1: Input: logs = [[0;5];[1;2];[0;2];[0;5];[1;3]]; k = 5 Output: [0;2;0;0;0] Explanation: The user with ID=0 performed actions at minutes 5; 2; and 5 again. Hence; they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence; they have a UAM of 2. Since both users have a UAM of 2; answer[2] is 2; and the remaining answer[j] values are 0. Example 2: Input: logs = [[1;1];[2;2];[2;3]]; k = 4 Output: [1;1;0;0] Explanation: The user with ID=1 performed a single action at minute 1. Hence; they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence; they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence; answer[1] = 1; answer[2] = 1; and the remaining values are 0. Constraints: 1 <= logs.length <= 104 0 <= IDi <= 109 1 <= timei <= 105 k is in the range [The maximum UAM for a user; 105].886Google,1934,Confirmation Rate,Med,"Array, Hash Table, String","You are given a string s that contains some bracket pairs; with each pair containing a non-empty key. For example; in the string ""(name)is(age)yearsold""; there are two bracket pairs that contain the keys ""name"" and ""age"". You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [keyi; valuei] indicates that key keyi has a value of valuei. You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi; you will: Replace keyi and the bracket pair with the key's corresponding valuei. If you do not know the value of the key; you will replace keyi and the bracket pair with a question mark ""?"" (without the quotation marks). Each key will appear at most once in your knowledge. There will not be any nested brackets in s. Return the resulting string after evaluating all of the bracket pairs. Example 1: Input: s = ""(name)is(age)yearsold""; knowledge = [[""name"";""bob""];[""age"";""two""]] Output: ""bobistwoyearsold"" Explanation: The key ""name"" has a value of ""bob""; so replace ""(name)"" with ""bob"". The key ""age"" has a value of ""two""; so replace ""(age)"" with ""two"". Example 2: Input: s = ""hi(name)""; knowledge = [[""a"";""b""]] Output: ""hi?"" Explanation: As you do not know the value of the key ""name""; replace ""(name)"" with ""?"". Example 3: Input: s = ""(a)(a)(a)aaa""; knowledge = [[""a"";""yes""]] Output: ""yesyesyesaaa"" Explanation: The same key can appear multiple times. The key ""a"" has a value of ""yes""; so replace all occurrences of ""(a)"" with ""yes"". Notice that the ""a""s not in a bracket pair are not evaluated. Constraints: 1 <= s.length <= 105 0 <= knowledge.length <= 105 knowledge[i].length == 2 1 <= keyi.length; valuei.length <= 10 s consists of lowercase English letters and round brackets '(' and ')'. Every open bracket '(' in s will have a corresponding close bracket ')'. The key in each bracket pair of s will be non-empty. There will not be any nested bracket pairs in s. keyi and valuei consist of lowercase English letters. Each keyi in knowledge is unique."887Google,1976,Number of Ways to Arrive at Destination,Med,"String, Backtracking","You are given a string s that consists of only digits. Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1. For example; the string s = ""0090089"" can be split into [""0090""; ""089""] with numerical values [90;89]. The values are in descending order and adjacent values differ by 1; so this way is valid. Another example; the string s = ""001"" can be split into [""0""; ""01""]; [""00""; ""1""]; or [""0""; ""0""; ""1""]. However all the ways are invalid because they have numerical values [0;1]; [0;1]; and [0;0;1] respectively; all of which are not in descending order. Return true if it is possible to split s​​​​​​ as described above; or false otherwise. A substring is a contiguous sequence of characters in a string. Example 1: Input: s = ""1234"" Output: false Explanation: There is no valid way to split s. Example 2: Input: s = ""050043"" Output: true Explanation: s can be split into [""05""; ""004""; ""3""] with numerical values [5;4;3]. The values are in descending order with adjacent values differing by 1. Example 3: Input: s = ""9080701"" Output: false Explanation: There is no valid way to split s. Constraints: 1 <= s.length <= 20 s only consists of digits."888Google,1984,Minimum Difference Between Highest and Lowest of K Scores,Easy,"Array, Two Pointers, Binary Search",You are given two non-increasing 0-indexed integer arrays nums1​​​​​​ and nums2​​​​​​. A pair of indices (i; j); where 0 <= i < nums1.length and 0 <= j < nums2.length; is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i​​​​. Return the maximum distance of any valid pair (i; j). If there are no valid pairs; return 0. An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length. Example 1: Input: nums1 = [55;30;5;4;2]; nums2 = [100;20;10;10;5] Output: 2 Explanation: The valid pairs are (0;0); (2;2); (2;3); (2;4); (3;3); (3;4); and (4;4). The maximum distance is 2 with pair (2;4). Example 2: Input: nums1 = [2;2;2]; nums2 = [10;10;1] Output: 1 Explanation: The valid pairs are (0;0); (0;1); and (1;1). The maximum distance is 1 with pair (0;1). Example 3: Input: nums1 = [30;29;19;5]; nums2 = [25;25;25;25;25] Output: 2 Explanation: The valid pairs are (2;2); (2;3); (2;4); (3;3); and (3;4). The maximum distance is 2 with pair (2;4). Constraints: 1 <= nums1.length; nums2.length <= 105 1 <= nums1[i]; nums2[j] <= 105 Both nums1 and nums2 are non-increasing.889Google,2006,Count Number of Pairs With Absolute Difference K,Easy,"Array, Binary Search, Simulation, Prefix Sum",There are n students in a class numbered from 0 to n - 1. The teacher will give each student a problem starting with the student number 0; then the student number 1; and so on until the teacher reaches the student number n - 1. After that; the teacher will restart the process; starting with the student number 0 again. You are given a 0-indexed integer array chalk and an integer k. There are initially k pieces of chalk. When the student number i is given a problem to solve; they will use chalk[i] pieces of chalk to solve that problem. However; if the current number of chalk pieces is strictly less than chalk[i]; then the student number i will be asked to replace the chalk. Return the index of the student that will replace the chalk pieces. Example 1: Input: chalk = [5;1;5]; k = 22 Output: 0 Explanation: The students go in turns as follows: - Student number 0 uses 5 chalk; so k = 17. - Student number 1 uses 1 chalk; so k = 16. - Student number 2 uses 5 chalk; so k = 11. - Student number 0 uses 5 chalk; so k = 6. - Student number 1 uses 1 chalk; so k = 5. - Student number 2 uses 5 chalk; so k = 0. Student number 0 does not have enough chalk; so they will have to replace it. Example 2: Input: chalk = [3;4;1;2]; k = 25 Output: 1 Explanation: The students go in turns as follows: - Student number 0 uses 3 chalk so k = 22. - Student number 1 uses 4 chalk so k = 18. - Student number 2 uses 1 chalk so k = 17. - Student number 3 uses 2 chalk so k = 15. - Student number 0 uses 3 chalk so k = 12. - Student number 1 uses 4 chalk so k = 8. - Student number 2 uses 1 chalk so k = 7. - Student number 3 uses 2 chalk so k = 5. - Student number 0 uses 3 chalk so k = 2. Student number 1 does not have enough chalk; so they will have to replace it. Constraints: chalk.length == n 1 <= n <= 105 1 <= chalk[i] <= 105 1 <= k <= 109890Google,2007,Find Original Array From Doubled Array,Med,"Dynamic Programming, Bit Manipulation, Graph, Bitmask",891Google,2009,Minimum Number of Operations to Make Array Continuous,Hard,"Depth-First Search, Trie",892Google,2027,Minimum Moves to Convert String,Easy,"Array, Two Pointers, String, Binary Search","You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed). You want to choose an integer k (0 <= k <= removable.length) such that; after removing k characters from s using the first k indices in removable; p is still a subsequence of s. More formally; you will mark the character at s[removable[i]] for each 0 <= i < k; then remove all marked characters and check if p is still a subsequence. Return the maximum k you can choose such that p is still a subsequence of s after the removals. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. Example 1: Input: s = ""abcacb""; p = ""ab""; removable = [3;1;0] Output: 2 Explanation: After removing the characters at indices 3 and 1; ""abcacb"" becomes ""accb"". ""ab"" is a subsequence of ""accb"". If we remove the characters at indices 3; 1; and 0; ""abcacb"" becomes ""ccb""; and ""ab"" is no longer a subsequence. Hence; the maximum k is 2. Example 2: Input: s = ""abcbddddd""; p = ""abcd""; removable = [3;2;1;4;5;6] Output: 1 Explanation: After removing the character at index 3; ""abcbddddd"" becomes ""abcddddd"". ""abcd"" is a subsequence of ""abcddddd"". Example 3: Input: s = ""abcab""; p = ""abc""; removable = [0;1;2;3;4] Output: 0 Explanation: If you remove the first index in the array removable; ""abc"" is no longer a subsequence. Constraints: 1 <= p.length <= s.length <= 105 0 <= removable.length < s.length 0 <= removable[i] < s.length p is a subsequence of s. s and p both consist of lowercase English letters. The elements in removable are distinct."893Google,2028,Find Missing Observations,Med,"Dynamic Programming, Memoization",There is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row; player 2 is the second player in the row; etc.). The tournament consists of multiple rounds (starting from round number 1). In each round; the ith player from the front of the row competes against the ith player from the end of the row; and the winner advances to the next round. When the number of players is odd for the current round; the player in the middle automatically advances to the next round. For example; if the row consists of players 1; 2; 4; 6; 7 Player 1 competes against player 7. Player 2 competes against player 6. Player 4 automatically advances to the next round. After each round is over; the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order). The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other; either of them might win; and thus you may choose the outcome of this round. Given the integers n; firstPlayer; and secondPlayer; return an integer array containing two values; the earliest possible round number and the latest possible round number in which these two players will compete against each other; respectively. Example 1: Input: n = 11; firstPlayer = 2; secondPlayer = 4 Output: [3;4] Explanation: One possible scenario which leads to the earliest round number: First round: 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11 Second round: 2; 3; 4; 5; 6; 11 Third round: 2; 3; 4 One possible scenario which leads to the latest round number: First round: 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11 Second round: 1; 2; 3; 4; 5; 6 Third round: 1; 2; 4 Fourth round: 2; 4 Example 2: Input: n = 5; firstPlayer = 1; secondPlayer = 5 Output: [1;1] Explanation: The players numbered 1 and 5 compete in the first round. There is no way to make them compete in any other round. Constraints: 2 <= n <= 28 1 <= firstPlayer < secondPlayer <= n894Google,2127,Maximum Employees to Be Invited to a Meeting,Hard,Database,Table: Employees +-------------+----------+ | Column Name | Type | +-------------+----------+ | employee_id | int | | name | varchar | | manager_id | int | | salary | int | +-------------+----------+ In SQL; employee_id is the primary key for this table. This table contains information about the employees; their salary; and the ID of their manager. Some employees do not have a manager (manager_id is null). Find the IDs of the employees whose salary is strictly less than $30000 and whose manager left the company. When a manager leaves the company; their information is deleted from the Employees table; but the reports still have their manager_id set to the manager that left. Return the result table ordered by employee_id. The result format is in the following example. Example 1: Input: Employees table: +-------------+-----------+------------+--------+ | employee_id | name | manager_id | salary | +-------------+-----------+------------+--------+ | 3 | Mila | 9 | 60301 | | 12 | Antonella | null | 31000 | | 13 | Emery | null | 67084 | | 1 | Kalel | 11 | 21241 | | 9 | Mikaela | null | 50937 | | 11 | Joziah | 6 | 28485 | +-------------+-----------+------------+--------+ Output: +-------------+ | employee_id | +-------------+ | 11 | +-------------+ Explanation: The employees with a salary less than $30000 are 1 (Kalel) and 11 (Joziah). Kalel's manager is employee 11; who is still in the company (Joziah). Joziah's manager is employee 6; who left the company because there is no row for employee 6 as it was deleted.895Google,2239,Find Closest Number to Zero,Easy,"String, Simulation","There is an n x n grid; with the top-left cell at (0; 0) and the bottom-right cell at (n - 1; n - 1). You are given the integer n and an integer array startPos where startPos = [startrow; startcol] indicates that a robot is initially at cell (startrow; startcol). You are also given a 0-indexed string s of length m where s[i] is the ith instruction for the robot: 'L' (move left); 'R' (move right); 'U' (move up); and 'D' (move down). The robot can begin executing from any ith instruction in s. It executes the instructions one by one towards the end of s but it stops if either of these conditions is met: The next instruction will move the robot off the grid. There are no more instructions left to execute. Return an array answer of length m where answer[i] is the number of instructions the robot can execute if the robot begins executing from the ith instruction in s. Example 1: Input: n = 3; startPos = [0;1]; s = ""RRDDLU"" Output: [1;5;4;3;1;0] Explanation: Starting from startPos and beginning execution from the ith instruction: - 0th: ""RRDDLU"". Only one instruction ""R"" can be executed before it moves off the grid. - 1st: ""RDDLU"". All five instructions can be executed while it stays in the grid and ends at (1; 1). - 2nd: ""DDLU"". All four instructions can be executed while it stays in the grid and ends at (1; 0). - 3rd: ""DLU"". All three instructions can be executed while it stays in the grid and ends at (0; 0). - 4th: ""LU"". Only one instruction ""L"" can be executed before it moves off the grid. - 5th: ""U"". If moving up; it would move off the grid. Example 2: Input: n = 2; startPos = [1;1]; s = ""LURD"" Output: [4;1;0;0] Explanation: - 0th: ""LURD"". - 1st: ""URD"". - 2nd: ""RD"". - 3rd: ""D"". Example 3: Input: n = 1; startPos = [0;0]; s = ""LRUD"" Output: [0;0;0;0] Explanation: No matter which instruction the robot begins execution from; it would move off the grid. Constraints: m == s.length 1 <= n; m <= 500 startPos.length == 2 0 <= startrow; startcol < n s consists of 'L'; 'R'; 'U'; and 'D'."896Google,2296,Design a Text Editor,Hard,Database,897Google,2405,Optimal Partition of String,Med,"Hash Table, String, Greedy, Sorting, Counting",898Google,2407,Longest Increasing Subsequence II,Hard,,899Google,2463,Minimum Total Distance Traveled,Hard,"String, Sliding Window","You are given a 0-indexed string blocks of length n; where blocks[i] is either 'W' or 'B'; representing the color of the ith block. The characters 'W' and 'B' denote the colors white and black; respectively. You are also given an integer k; which is the desired number of consecutive black blocks. In one operation; you can recolor a white block such that it becomes a black block. Return the minimum number of operations needed such that there is at least one occurrence of k consecutive black blocks. Example 1: Input: blocks = ""WBBWWBBWBW""; k = 7 Output: 3 Explanation: One way to achieve 7 consecutive black blocks is to recolor the 0th; 3rd; and 4th blocks so that blocks = ""BBBBBBBWBW"". It can be shown that there is no way to achieve 7 consecutive black blocks in less than 3 operations. Therefore; we return 3. Example 2: Input: blocks = ""WBWBBBW""; k = 2 Output: 0 Explanation: No changes need to be made; since 2 consecutive black blocks already exist. Therefore; we return 0. Constraints: n == blocks.length 1 <= n <= 100 blocks[i] is either 'W' or 'B'. 1 <= k <= n"900Google,2530,Maximal Score After Applying K Operations,Med,"Array, Binary Search, Dynamic Programming, Greedy, Prefix Sum",You are given a 0-indexed array nums comprising of n non-negative integers. In one operation; you must: Choose an integer i such that 1 <= i < n and nums[i] > 0. Decrease nums[i] by 1. Increase nums[i - 1] by 1. Return the minimum possible value of the maximum integer of nums after performing any number of operations. Example 1: Input: nums = [3;7;1;6] Output: 5 Explanation: One set of optimal operations is as follows: 1. Choose i = 1; and nums becomes [4;6;1;6]. 2. Choose i = 3; and nums becomes [4;6;2;5]. 3. Choose i = 1; and nums becomes [5;5;2;5]. The maximum integer of nums is 5. It can be shown that the maximum number cannot be less than 5. Therefore; we return 5. Example 2: Input: nums = [10;1] Output: 10 Explanation: It is optimal to leave nums as is; and since 10 is the maximum value; we return 10. Constraints: n == nums.length 2 <= n <= 105 0 <= nums[i] <= 109901Google,2601,Prime Subtraction Operation,Med,"Array, Dynamic Programming",You are given an array nums consisting of positive integers and an integer k. Partition the array into two ordered groups such that each element is in exactly one group. A partition is called great if the sum of elements of each group is greater than or equal to k. Return the number of distinct great partitions. Since the answer may be too large; return it modulo 109 + 7. Two partitions are considered distinct if some element nums[i] is in different groups in the two partitions. Example 1: Input: nums = [1;2;3;4]; k = 4 Output: 6 Explanation: The great partitions are: ([1;2;3]; [4]); ([1;3]; [2;4]); ([1;4]; [2;3]); ([2;3]; [1;4]); ([2;4]; [1;3]) and ([4]; [1;2;3]). Example 2: Input: nums = [3;3;3]; k = 4 Output: 0 Explanation: There are no great partitions for this array. Example 3: Input: nums = [6;6]; k = 2 Output: 2 Explanation: We can either put nums[0] in the first partition or in the second partition. The great partitions will be ([6]; [6]) and ([6]; [6]). Constraints: 1 <= nums.length; k <= 1000 1 <= nums[i] <= 109902Google,2621,Sleep,Easy,"Array, Math, Bit Manipulation",You are given a 0-indexed integer array nums. The effective value of three indices i; j; and k is defined as ((nums[i] | nums[j]) & nums[k]). The xor-beauty of the array is the XORing of the effective values of all the possible triplets of indices (i; j; k) where 0 <= i; j; k < n. Return the xor-beauty of nums. Note that: val1 | val2 is bitwise OR of val1 and val2. val1 & val2 is bitwise AND of val1 and val2. Example 1: Input: nums = [1;4] Output: 5 Explanation: The triplets and their corresponding effective values are listed below: - (0;0;0) with effective value ((1 | 1) & 1) = 1 - (0;0;1) with effective value ((1 | 1) & 4) = 0 - (0;1;0) with effective value ((1 | 4) & 1) = 1 - (0;1;1) with effective value ((1 | 4) & 4) = 4 - (1;0;0) with effective value ((4 | 1) & 1) = 1 - (1;0;1) with effective value ((4 | 1) & 4) = 4 - (1;1;0) with effective value ((4 | 4) & 1) = 0 - (1;1;1) with effective value ((4 | 4) & 4) = 4 Xor-beauty of array will be bitwise XOR of all beauties = 1 ^ 0 ^ 1 ^ 4 ^ 1 ^ 4 ^ 0 ^ 4 = 5. Example 2: Input: nums = [15;45;20;2;34;35;5;44;32;30] Output: 34 Explanation: The xor-beauty of the given array is 34. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109903Google,2619,Array Prototype Last,Easy,Math,"Given four integers length; width; height; and mass; representing the dimensions and mass of a box; respectively; return a string representing the category of the box. The box is ""Bulky"" if: Any of the dimensions of the box is greater or equal to 104. Or; the volume of the box is greater or equal to 109. If the mass of the box is greater or equal to 100; it is ""Heavy"". If the box is both ""Bulky"" and ""Heavy""; then its category is ""Both"". If the box is neither ""Bulky"" nor ""Heavy""; then its category is ""Neither"". If the box is ""Bulky"" but not ""Heavy""; then its category is ""Bulky"". If the box is ""Heavy"" but not ""Bulky""; then its category is ""Heavy"". Note that the volume of the box is the product of its length; width and height. Example 1: Input: length = 1000; width = 35; height = 700; mass = 300 Output: ""Heavy"" Explanation: None of the dimensions of the box is greater or equal to 104. Its volume = 24500000 <= 109. So it cannot be categorized as ""Bulky"". However mass >= 100; so the box is ""Heavy"". Since the box is not ""Bulky"" but ""Heavy""; we return ""Heavy"". Example 2: Input: length = 200; width = 50; height = 800; mass = 50 Output: ""Neither"" Explanation: None of the dimensions of the box is greater or equal to 104. Its volume = 8 * 106 <= 109. So it cannot be categorized as ""Bulky"". Its mass is also less than 100; so it cannot be categorized as ""Heavy"" either. Since its neither of the two above categories; we return ""Neither"". Constraints: 1 <= length; width; height <= 105 1 <= mass <= 103"904Google,2633,Convert Object to JSON String,Med,"Array, Hash Table, Dynamic Programming, Counting",You are given an integer array nums and an integer k. Split the array into some number of non-empty subarrays. The cost of a split is the sum of the importance value of each subarray in the split. Let trimmed(subarray) be the version of the subarray where all numbers which appear only once are removed. For example; trimmed([3;1;2;4;3;4]) = [3;4;3;4]. The importance value of a subarray is k + trimmed(subarray).length. For example; if a subarray is [1;2;3;3;3;4;4]; then trimmed([1;2;3;3;3;4;4]) = [3;3;3;4;4].The importance value of this subarray will be k + 5. Return the minimum possible cost of a split of nums. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: nums = [1;2;1;2;1;3;3]; k = 2 Output: 8 Explanation: We split nums to have two subarrays: [1;2]; [1;2;1;3;3]. The importance value of [1;2] is 2 + (0) = 2. The importance value of [1;2;1;3;3] is 2 + (2 + 2) = 6. The cost of the split is 2 + 6 = 8. It can be shown that this is the minimum possible cost among all the possible splits. Example 2: Input: nums = [1;2;1;2;1]; k = 2 Output: 6 Explanation: We split nums to have two subarrays: [1;2]; [1;2;1]. The importance value of [1;2] is 2 + (0) = 2. The importance value of [1;2;1] is 2 + (2) = 4. The cost of the split is 2 + 4 = 6. It can be shown that this is the minimum possible cost among all the possible splits. Example 3: Input: nums = [1;2;1;2;1]; k = 5 Output: 10 Explanation: We split nums to have one subarray: [1;2;1;2;1]. The importance value of [1;2;1;2;1] is 5 + (3 + 2) = 10. The cost of the split is 10. It can be shown that this is the minimum possible cost among all the possible splits. Constraints: 1 <= nums.length <= 1000 0 <= nums[i] < nums.length 1 <= k <= 109905Google,2684,Maximum Number of Moves in a Grid,Med,"Array, Simulation",You are given two 0-indexed integer arrays player1 and player2; representing the number of pins that player 1 and player 2 hit in a bowling game; respectively. The bowling game consists of n turns; and the number of pins in each turn is exactly 10. Assume a player hits xi pins in the ith turn. The value of the ith turn for the player is: 2xi if the player hits 10 pins in either (i - 1)th or (i - 2)th turn. Otherwise; it is xi. The score of the player is the sum of the values of their n turns. Return 1 if the score of player 1 is more than the score of player 2; 2 if the score of player 2 is more than the score of player 1; and 0 in case of a draw. Example 1: Input: player1 = [5;10;3;2]; player2 = [6;5;7;3] Output: 1 Explanation: The score of player 1 is 5 + 10 + 2*3 + 2*2 = 25. The score of player 2 is 6 + 5 + 7 + 3 = 21. Example 2: Input: player1 = [3;5;7;6]; player2 = [8;10;10;2] Output: 2 Explanation: The score of player 1 is 3 + 5 + 7 + 6 = 21. The score of player 2 is 8 + 10 + 2*10 + 2*2 = 42. Example 3: Input: player1 = [2;3]; player2 = [4;1] Output: 0 Explanation: The score of player1 is 2 + 3 = 5. The score of player2 is 4 + 1 = 5. Example 4: Input: player1 = [1;1;1;10;10;10;10]; player2 = [10;10;10;10;1;1;1] Output: 2 Explanation: The score of player1 is 1 + 1 + 1 + 10 + 2*10 + 2*10 + 2*10 = 73. The score of player2 is 10 + 2*10 + 2*10 + 2*10 + 2*1 + 2*1 + 1 = 75. Constraints: n == player1.length == player2.length 1 <= n <= 1000 0 <= player1[i]; player2[i] <= 10906Google,2696,Minimum String Length After Removing Substrings,Easy,"Array, Hash Table, Math, Dynamic Programming, Backtracking, Sorting, Combinatorics",You are given an array nums of positive integers and a positive integer k. A subset of nums is beautiful if it does not contain two integers with an absolute difference equal to k. Return the number of non-empty beautiful subsets of the array nums. A subset of nums is an array that can be obtained by deleting some (possibly none) elements from nums. Two subsets are different if and only if the chosen indices to delete are different. Example 1: Input: nums = [2;4;6]; k = 2 Output: 4 Explanation: The beautiful subsets of the array nums are: [2]; [4]; [6]; [2; 6]. It can be proved that there are only 4 beautiful subsets in the array [2;4;6]. Example 2: Input: nums = [1]; k = 1 Output: 1 Explanation: The beautiful subset of the array nums is [1]. It can be proved that there is only 1 beautiful subset in the array [1]. Constraints: 1 <= nums.length <= 20 1 <= nums[i]; k <= 1000907Google,2699,Modify Graph Edge Weights,Hard,"Array, Two Pointers, Binary Search, Sorting",Given a 0-indexed integer array nums of size n and two integers lower and upper; return the number of fair pairs. A pair (i; j) is fair if: 0 <= i < j < n; and lower <= nums[i] + nums[j] <= upper Example 1: Input: nums = [0;1;7;4;4;5]; lower = 3; upper = 6 Output: 6 Explanation: There are 6 fair pairs: (0;3); (0;4); (0;5); (1;3); (1;4); and (1;5). Example 2: Input: nums = [1;7;9;2;5]; lower = 11; upper = 11 Output: 1 Explanation: There is a single fair pair: (2;3). Constraints: 1 <= nums.length <= 105 nums.length == n -109 <= nums[i] <= 109 -109 <= lower <= upper <= 109908Google,2800,Shortest String That Contains Three Strings,Med,"String, Stack, Simulation","You are given a string s consisting only of uppercase English letters. You can apply some operations to this string where; in one operation; you can remove any occurrence of one of the substrings ""AB"" or ""CD"" from s. Return the minimum possible length of the resulting string that you can obtain. Note that the string concatenates after removing the substring and could produce new ""AB"" or ""CD"" substrings. Example 1: Input: s = ""ABFCACDB"" Output: 2 Explanation: We can do the following operations: - Remove the substring ""ABFCACDB""; so s = ""FCACDB"". - Remove the substring ""FCACDB""; so s = ""FCAB"". - Remove the substring ""FCAB""; so s = ""FC"". So the resulting length of the string is 2. It can be shown that it is the minimum length that we can obtain. Example 2: Input: s = ""ACBBD"" Output: 5 Explanation: We cannot do any operations on the string so the length remains the same. Constraints: 1 <= s.length <= 100 s consists only of uppercase English letters."909Google,2965,Find Missing and Repeated Values,Easy,,910Google,2955,Number of Same-End Substrings,Med,Math,Initially; you have a bank account balance of 100 dollars. You are given an integer purchaseAmount representing the amount you will spend on a purchase in dollars; in other words; its price. When making the purchase; first the purchaseAmount is rounded to the nearest multiple of 10. Let us call this value roundedAmount. Then; roundedAmount dollars are removed from your bank account. Return an integer denoting your final bank account balance after this purchase. Notes: 0 is considered to be a multiple of 10 in this problem. When rounding; 5 is rounded upward (5 is rounded to 10; 15 is rounded to 20; 25 to 30; and so on). Example 1: Input: purchaseAmount = 9 Output: 90 Explanation: The nearest multiple of 10 to 9 is 10. So your account balance becomes 100 - 10 = 90. Example 2: Input: purchaseAmount = 15 Output: 80 Explanation: The nearest multiple of 10 to 15 is 20. So your account balance becomes 100 - 20 = 80. Example 3: Input: purchaseAmount = 10 Output: 90 Explanation: 10 is a multiple of 10 itself. So your account balance becomes 100 - 10 = 90. Constraints: 0 <= purchaseAmount <= 100911Google,3133,Minimum Array End,Med,,912Google,3120,Count the Number of Special Characters I,Easy,,913Google,3208,Alternating Groups II,Med,"Hash Table, Math, String, Number Theory, Prefix Sum","You are given a string s and a positive integer k. Let vowels and consonants be the number of vowels and consonants in a string. A string is beautiful if: vowels == consonants. (vowels * consonants) % k == 0; in other terms the multiplication of vowels and consonants is divisible by k. Return the number of non-empty beautiful substrings in the given string s. A substring is a contiguous sequence of characters in a string. Vowel letters in English are 'a'; 'e'; 'i'; 'o'; and 'u'. Consonant letters in English are every letter except vowels. Example 1: Input: s = ""baeyh""; k = 2 Output: 2 Explanation: There are 2 beautiful substrings in the given string. - Substring ""baeyh""; vowels = 2 ([""a"";e""]); consonants = 2 ([""y"";""h""]). You can see that string ""aeyh"" is beautiful as vowels == consonants and vowels * consonants % k == 0. - Substring ""baeyh""; vowels = 2 ([""a"";e""]); consonants = 2 ([""b"";""y""]). You can see that string ""baey"" is beautiful as vowels == consonants and vowels * consonants % k == 0. It can be shown that there are only 2 beautiful substrings in the given string. Example 2: Input: s = ""abba""; k = 1 Output: 3 Explanation: There are 3 beautiful substrings in the given string. - Substring ""abba""; vowels = 1 ([""a""]); consonants = 1 ([""b""]). - Substring ""abba""; vowels = 1 ([""a""]); consonants = 1 ([""b""]). - Substring ""abba""; vowels = 2 ([""a"";""a""]); consonants = 2 ([""b"";""b""]). It can be shown that there are only 3 beautiful substrings in the given string. Example 3: Input: s = ""bcdf""; k = 1 Output: 0 Explanation: There are no beautiful substrings in the given string. Constraints: 1 <= s.length <= 5 * 104 1 <= k <= 1000 s consists of only English lowercase letters."914Google,3275,K-th Nearest Obstacle Queries,Med,"Math, String, Greedy","You are given a string word containing distinct lowercase English letters. Telephone keypads have keys mapped with distinct collections of lowercase English letters; which can be used to form words by pushing them. For example; the key 2 is mapped with [""a"";""b"";""c""]; we need to push the key one time to type ""a""; two times to type ""b""; and three times to type ""c"" . It is allowed to remap the keys numbered 2 to 9 to distinct collections of letters. The keys can be remapped to any amount of letters; but each letter must be mapped to exactly one key. You need to find the minimum number of times the keys will be pushed to type the string word. Return the minimum number of pushes needed to type word after remapping the keys. An example mapping of letters to keys on a telephone keypad is given below. Note that 1; *; #; and 0 do not map to any letters. Example 1: Input: word = ""abcde"" Output: 5 Explanation: The remapped keypad given in the image provides the minimum cost. ""a"" -> one push on key 2 ""b"" -> one push on key 3 ""c"" -> one push on key 4 ""d"" -> one push on key 5 ""e"" -> one push on key 6 Total cost is 1 + 1 + 1 + 1 + 1 = 5. It can be shown that no other mapping can provide a lower cost. Example 2: Input: word = ""xycdefghij"" Output: 12 Explanation: The remapped keypad given in the image provides the minimum cost. ""x"" -> one push on key 2 ""y"" -> two pushes on key 2 ""c"" -> one push on key 3 ""d"" -> two pushes on key 3 ""e"" -> one push on key 4 ""f"" -> one push on key 5 ""g"" -> one push on key 6 ""h"" -> one push on key 7 ""i"" -> one push on key 8 ""j"" -> one push on key 9 Total cost is 1 + 2 + 1 + 2 + 1 + 1 + 1 + 1 + 1 + 1 = 12. It can be shown that no other mapping can provide a lower cost. Constraints: 1 <= word.length <= 26 word consists of lowercase English letters. All letters in word are distinct."915Google,3325,Count Substrings With K-Frequency Characters I,Med,"Array, Math, Geometry",There exist n rectangles in a 2D plane with edges parallel to the x and y axis. You are given two 2D integer arrays bottomLeft and topRight where bottomLeft[i] = [a_i; b_i] and topRight[i] = [c_i; d_i] represent the bottom-left and top-right coordinates of the ith rectangle; respectively. You need to find the maximum area of a square that can fit inside the intersecting region of at least two rectangles. Return 0 if such a square does not exist. Example 1: Input: bottomLeft = [[1;1];[2;2];[3;1]]; topRight = [[3;3];[4;4];[6;6]] Output: 1 Explanation: A square with side length 1 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is 1. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles. Example 2: Input: bottomLeft = [[1;1];[1;3];[1;5]]; topRight = [[5;5];[5;7];[5;9]] Output: 4 Explanation: A square with side length 2 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is 2 * 2 = 4. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles. Example 3: Input: bottomLeft = [[1;1];[2;2];[1;2]]; topRight = [[3;3];[4;4];[3;4]] Output: 1 Explanation: A square with side length 1 can fit inside the intersecting region of any two rectangles. Also; no larger square can; so the maximum area is 1. Note that the region can be formed by the intersection of more than 2 rectangles. Example 4: Input: bottomLeft = [[1;1];[3;3];[3;1]]; topRight = [[2;2];[4;4];[4;2]] Output: 0 Explanation: No pair of rectangles intersect; hence; the answer is 0. Constraints: n == bottomLeft.length == topRight.length 2 <= n <= 103 bottomLeft[i].length == topRight[i].length == 2 1 <= bottomLeft[i][0]; bottomLeft[i][1] <= 107 1 <= topRight[i][0]; topRight[i][1] <= 107 bottomLeft[i][0] < topRight[i][0] bottomLeft[i][1] < topRight[i][1]916Google,3282,Reach End of Array With Max Score,Med,Database,917Google,3248,Snake in Matrix,Easy,"Array, Two Pointers, Binary Search",You are given a 0-indexed array of positive integers nums. A subarray of nums is called incremovable if nums becomes strictly increasing on removing the subarray. For example; the subarray [3; 4] is an incremovable subarray of [5; 3; 4; 6; 7] because removing this subarray changes the array [5; 3; 4; 6; 7] to [5; 6; 7] which is strictly increasing. Return the total number of incremovable subarrays of nums. Note that an empty array is considered strictly increasing. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: nums = [1;2;3;4] Output: 10 Explanation: The 10 incremovable subarrays are: [1]; [2]; [3]; [4]; [1;2]; [2;3]; [3;4]; [1;2;3]; [2;3;4]; and [1;2;3;4]; because on removing any one of these subarrays nums becomes strictly increasing. Note that you cannot select an empty subarray. Example 2: Input: nums = [6;5;7;8] Output: 7 Explanation: The 7 incremovable subarrays are: [5]; [6]; [5;7]; [6;5]; [5;7;8]; [6;5;7] and [6;5;7;8]. It can be shown that there are only 7 incremovable subarrays in nums. Example 3: Input: nums = [8;7;6;6] Output: 3 Explanation: The 3 incremovable subarrays are: [8;7;6]; [7;6;6]; and [8;7;6;6]. Note that [8;7] is not an incremovable subarray because after removing [8;7] nums becomes [6;6]; which is sorted in ascending order but not strictly increasing. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109918Google,3283,Maximum Number of Moves to Kill All Pawns,Hard,Database,919Google,3312,Sorted GCD Pair Queries,Hard,String,"You are given a 0-indexed string s typed by a user. Changing a key is defined as using a key different from the last used key. For example; s = ""ab"" has a change of a key while s = ""bBBb"" does not have any. Return the number of times the user had to change the key. Note: Modifiers like shift or caps lock won't be counted in changing the key that is if a user typed the letter 'a' and then the letter 'A' then it will not be considered as a changing of key. Example 1: Input: s = ""aAbBcC"" Output: 2 Explanation: From s[0] = 'a' to s[1] = 'A'; there is no change of key as caps lock or shift is not counted. From s[1] = 'A' to s[2] = 'b'; there is a change of key. From s[2] = 'b' to s[3] = 'B'; there is no change of key as caps lock or shift is not counted. From s[3] = 'B' to s[4] = 'c'; there is a change of key. From s[4] = 'c' to s[5] = 'C'; there is no change of key as caps lock or shift is not counted. Example 2: Input: s = ""AaAaAaaA"" Output: 0 Explanation: There is no change of key since only the letters 'a' and 'A' are pressed which does not require change of key. Constraints: 1 <= s.length <= 100 s consists of only upper case and lower case English letters."920Google,3327,Check if DFS Strings Are Palindromes,Hard,"Array, Greedy, Sliding Window, Prefix Sum",You are given a binary array nums of length n; a positive integer k and a non-negative integer maxChanges. Alice plays a game; where the goal is for Alice to pick up k ones from nums using the minimum number of moves. When the game starts; Alice picks up any index aliceIndex in the range [0; n - 1] and stands there. If nums[aliceIndex] == 1 ; Alice picks up the one and nums[aliceIndex] becomes 0(this does not count as a move). After this; Alice can make any number of moves (including zero) where in each move Alice must perform exactly one of the following actions: Select any index j != aliceIndex such that nums[j] == 0 and set nums[j] = 1. This action can be performed at most maxChanges times. Select any two adjacent indices x and y (|x - y| == 1) such that nums[x] == 1; nums[y] == 0; then swap their values (set nums[y] = 1 and nums[x] = 0). If y == aliceIndex; Alice picks up the one after this move and nums[y] becomes 0. Return the minimum number of moves required by Alice to pick exactly k ones. Example 1: Input: nums = [1;1;0;0;0;1;1;0;0;1]; k = 3; maxChanges = 1 Output: 3 Explanation: Alice can pick up 3 ones in 3 moves; if Alice performs the following actions in each move when standing at aliceIndex == 1: At the start of the game Alice picks up the one and nums[1] becomes 0. nums becomes [1;0;0;0;0;1;1;0;0;1]. Select j == 2 and perform an action of the first type. nums becomes [1;0;1;0;0;1;1;0;0;1] Select x == 2 and y == 1; and perform an action of the second type. nums becomes [1;1;0;0;0;1;1;0;0;1]. As y == aliceIndex; Alice picks up the one and nums becomes [1;0;0;0;0;1;1;0;0;1]. Select x == 0 and y == 1; and perform an action of the second type. nums becomes [0;1;0;0;0;1;1;0;0;1]. As y == aliceIndex; Alice picks up the one and nums becomes [0;0;0;0;0;1;1;0;0;1]. Note that it may be possible for Alice to pick up 3 ones using some other sequence of 3 moves. Example 2: Input: nums = [0;0;0;0]; k = 2; maxChanges = 3 Output: 4 Explanation: Alice can pick up 2 ones in 4 moves; if Alice performs the following actions in each move when standing at aliceIndex == 0: Select j == 1 and perform an action of the first type. nums becomes [0;1;0;0]. Select x == 1 and y == 0; and perform an action of the second type. nums becomes [1;0;0;0]. As y == aliceIndex; Alice picks up the one and nums becomes [0;0;0;0]. Select j == 1 again and perform an action of the first type. nums becomes [0;1;0;0]. Select x == 1 and y == 0 again; and perform an action of the second type. nums becomes [1;0;0;0]. As y == aliceIndex; Alice picks up the one and nums becomes [0;0;0;0]. Constraints: 2 <= n <= 105 0 <= nums[i] <= 1 1 <= k <= 105 0 <= maxChanges <= 105 maxChanges + sum(nums) >= k921Google,3326,Minimum Division Operations to Make Array Non Decreasing,Med,"Array, Tree, Depth-First Search",You are given an unrooted weighted tree with n vertices representing servers numbered from 0 to n - 1; an array edges where edges[i] = [ai; bi; weighti] represents a bidirectional edge between vertices ai and bi of weight weighti. You are also given an integer signalSpeed. Two servers a and b are connectable through a server c if: a < b; a != c and b != c. The distance from c to a is divisible by signalSpeed. The distance from c to b is divisible by signalSpeed. The path from c to b and the path from c to a do not share any edges. Return an integer array count of length n where count[i] is the number of server pairs that are connectable through the server i. Example 1: Input: edges = [[0;1;1];[1;2;5];[2;3;13];[3;4;9];[4;5;2]]; signalSpeed = 1 Output: [0;4;6;6;4;0] Explanation: Since signalSpeed is 1; count[c] is equal to the number of pairs of paths that start at c and do not share any edges. In the case of the given path graph; count[c] is equal to the number of servers to the left of c multiplied by the servers to the right of c. Example 2: Input: edges = [[0;6;3];[6;5;3];[0;3;1];[3;2;7];[3;1;6];[3;4;2]]; signalSpeed = 3 Output: [2;0;0;0;0;0;2] Explanation: Through server 0; there are 2 pairs of connectable servers: (4; 5) and (4; 6). Through server 6; there are 2 pairs of connectable servers: (4; 5) and (0; 5). It can be shown that no two servers are connectable through servers other than 0 and 6. Constraints: 2 <= n <= 1000 edges.length == n - 1 edges[i].length == 3 0 <= ai; bi < n edges[i] = [ai; bi; weighti] 1 <= weighti <= 106 1 <= signalSpeed <= 106 The input is generated such that edges represents a valid tree.922Amazon,1,Two Sum,Easy,"Array, Hash Table",Given an array of integers nums and an integer target; return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution; and you may not use the same element twice. You can return the answer in any order. Example 1: Input: nums = [2;7;11;15]; target = 9 Output: [0;1] Explanation: Because nums[0] + nums[1] == 9; we return [0; 1]. Example 2: Input: nums = [3;2;4]; target = 6 Output: [1;2] Example 3: Input: nums = [3;3]; target = 6 Output: [0;1] Constraints: 2 <= nums.length <= 104 -109 <= nums[i] <= 109 -109 <= target <= 109 Only one valid answer exists. Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?923Amazon,146,LRU Cache,Med,"Hash Table, Linked List, Design, Doubly-Linked List","Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class: LRUCache(int capacity) Initialize the LRU cache with positive size capacity. int get(int key) Return the value of the key if the key exists; otherwise return -1. void put(int key; int value) Update the value of the key if the key exists. Otherwise; add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation; evict the least recently used key. The functions get and put must each run in O(1) average time complexity. Example 1: Input [""LRUCache""; ""put""; ""put""; ""get""; ""put""; ""get""; ""put""; ""get""; ""get""; ""get""] [[2]; [1; 1]; [2; 2]; [1]; [3; 3]; [2]; [4; 4]; [1]; [3]; [4]] Output [null; null; null; 1; null; -1; null; -1; 3; 4] Explanation LRUCache lRUCache = new LRUCache(2); lRUCache.put(1; 1); // cache is {1=1} lRUCache.put(2; 2); // cache is {1=1; 2=2} lRUCache.get(1); // return 1 lRUCache.put(3; 3); // LRU key was 2; evicts key 2; cache is {1=1; 3=3} lRUCache.get(2); // returns -1 (not found) lRUCache.put(4; 4); // LRU key was 1; evicts key 1; cache is {4=4; 3=3} lRUCache.get(1); // return -1 (not found) lRUCache.get(3); // return 3 lRUCache.get(4); // return 4 Constraints: 1 <= capacity <= 3000 0 <= key <= 104 0 <= value <= 105 At most 2 * 105 calls will be made to get and put."924Amazon,88,Merge Sorted Array,Easy,"Array, Two Pointers, Sorting",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. Example 1: 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. Example 2: Input: nums1 = [1]; m = 1; nums2 = []; n = 0 Output: [1] Explanation: The arrays we are merging are [1] and []. The result of the merge is [1]. Example 3: Input: nums1 = [0]; m = 0; nums2 = [1]; n = 1 Output: [1] Explanation: The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0; there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. Constraints: nums1.length == m + n nums2.length == n 0 <= m; n <= 200 1 <= m + n <= 200 -109 <= nums1[i]; nums2[j] <= 109 Follow up: Can you come up with an algorithm that runs in O(m + n) time?925Amazon,42,Trapping Rain Water,Hard,"Array, Two Pointers, Dynamic Programming, Stack, Monotonic Stack",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. Example 1: 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. Example 2: Input: height = [4;2;0;3;2;5] Output: 9 Constraints: n == height.length 1 <= n <= 2 * 104 0 <= height[i] <= 105926Amazon,3,Longest Substring Without Repeating Characters,Med,"Hash Table, String, Sliding Window","Given a string s; find the length of the longest substring without repeating characters. Example 1: Input: s = ""abcabcbb"" Output: 3 Explanation: The answer is ""abc""; with the length of 3. Example 2: Input: s = ""bbbbb"" Output: 1 Explanation: The answer is ""b""; with the length of 1. Example 3: Input: s = ""pwwkew"" Output: 3 Explanation: The answer is ""wke""; with the length of 3. Notice that the answer must be a substring; ""pwke"" is a subsequence and not a substring. Constraints: 0 <= s.length <= 5 * 104 s consists of English letters; digits; symbols and spaces."927Amazon,200,Number of Islands,Med,"Array, Depth-First Search, Breadth-First Search, Union Find, Matrix","Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water); return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: grid = [ [""1"";""1"";""1"";""1"";""0""]; [""1"";""1"";""0"";""1"";""0""]; [""1"";""1"";""0"";""0"";""0""]; [""0"";""0"";""0"";""0"";""0""] ] Output: 1 Example 2: Input: grid = [ [""1"";""1"";""0"";""0"";""0""]; [""1"";""1"";""0"";""0"";""0""]; [""0"";""0"";""1"";""0"";""0""]; [""0"";""0"";""0"";""1"";""1""] ] Output: 3 Constraints: m == grid.length n == grid[i].length 1 <= m; n <= 300 grid[i][j] is '0' or '1'."928Amazon,49,Group Anagrams,Med,"Array, Hash Table, String, Sorting","Given an array of strings strs; group the anagrams together. You can return the answer in any order. Example 1: Input: strs = [""eat"";""tea"";""tan"";""ate"";""nat"";""bat""] Output: [[""bat""];[""nat"";""tan""];[""ate"";""eat"";""tea""]] Explanation: There is no string in strs that can be rearranged to form ""bat"". The strings ""nat"" and ""tan"" are anagrams as they can be rearranged to form each other. The strings ""ate""; ""eat""; and ""tea"" are anagrams as they can be rearranged to form each other. Example 2: Input: strs = [""""] Output: [[""""]] Example 3: Input: strs = [""a""] Output: [[""a""]] Constraints: 1 <= strs.length <= 104 0 <= strs[i].length <= 100 strs[i] consists of lowercase English letters."929Amazon,121,Best Time to Buy and Sell Stock,Easy,"Array, Dynamic Programming",You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit; return 0. Example 1: Input: prices = [7;1;5;3;6;4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6); profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. Example 2: Input: prices = [7;6;4;3;1] Output: 0 Explanation: In this case; no transactions are done and the max profit = 0. Constraints: 1 <= prices.length <= 105 0 <= prices[i] <= 104930Amazon,621,Task Scheduler,Med,"Array, Hash Table, Greedy, Sorting, Heap (Priority Queue), Counting","You are given an array of CPU tasks; each labeled with a letter from A to Z; and a number n. Each CPU interval can be idle or allow the completion of one task. Tasks can be completed in any order; but there's a constraint: there has to be a gap of at least n intervals between two tasks with the same label. Return the minimum number of CPU intervals required to complete all tasks. Example 1: Input: tasks = [""A"";""A"";""A"";""B"";""B"";""B""]; n = 2 Output: 8 Explanation: A possible sequence is: A -> B -> idle -> A -> B -> idle -> A -> B. After completing task A; you must wait two intervals before doing A again. The same applies to task B. In the 3rd interval; neither A nor B can be done; so you idle. By the 4th interval; you can do A again as 2 intervals have passed. Example 2: Input: tasks = [""A"";""C"";""A"";""B"";""D"";""B""]; n = 1 Output: 6 Explanation: A possible sequence is: A -> B -> C -> D -> A -> B. With a cooling interval of 1; you can repeat a task after just one other task. Example 3: Input: tasks = [""A"";""A"";""A""; ""B"";""B"";""B""]; n = 3 Output: 10 Explanation: A possible sequence is: A -> B -> idle -> idle -> A -> B -> idle -> idle -> A -> B. There are only two types of tasks; A and B; which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks. Constraints: 1 <= tasks.length <= 104 tasks[i] is an uppercase English letter. 0 <= n <= 100"931Amazon,207,Course Schedule,Med,"Depth-First Search, Breadth-First Search, Graph, Topological Sort",There are a total of numCourses courses you have to take; labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai; bi] indicates that you must take course bi first if you want to take course ai. For example; the pair [0; 1]; indicates that to take course 0 you have to first take course 1. Return true if you can finish all courses. Otherwise; return false. Example 1: Input: numCourses = 2; prerequisites = [[1;0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. Example 2: Input: numCourses = 2; prerequisites = [[1;0];[0;1]] Output: false Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0; and to take course 0 you should also have finished course 1. So it is impossible. Constraints: 1 <= numCourses <= 2000 0 <= prerequisites.length <= 5000 prerequisites[i].length == 2 0 <= ai; bi < numCourses All the pairs prerequisites[i] are unique.932Amazon,1768,Merge Strings Alternately,Easy,"Array, Math, Stack, Tree, Design, Binary Tree",933Amazon,347,Top K Frequent Elements,Med,"Array, Hash Table, Divide and Conquer, Sorting, Heap (Priority Queue), Bucket Sort, Counting, Quickselect",Given an integer array nums and an integer k; return the k most frequent elements. You may return the answer in any order. Example 1: Input: nums = [1;1;1;2;2;3]; k = 2 Output: [1;2] Example 2: Input: nums = [1]; k = 1 Output: [1] Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 k is in the range [1; the number of unique elements in the array]. It is guaranteed that the answer is unique. Follow up: Your algorithm's time complexity must be better than O(n log n); where n is the array's size.934Amazon,767,Reorganize String,Med,"Math, Bit Manipulation",Given two integers left and right; return the count of numbers in the inclusive range [left; right] having a prime number of set bits in their binary representation. Recall that the number of set bits an integer has is the number of 1's present when written in binary. For example; 21 written in binary is 10101; which has 3 set bits. Example 1: Input: left = 6; right = 10 Output: 4 Explanation: 6 -> 110 (2 set bits; 2 is prime) 7 -> 111 (3 set bits; 3 is prime) 8 -> 1000 (1 set bit; 1 is not prime) 9 -> 1001 (2 set bits; 2 is prime) 10 -> 1010 (2 set bits; 2 is prime) 4 numbers have a prime number of set bits. Example 2: Input: left = 10; right = 15 Output: 5 Explanation: 10 -> 1010 (2 set bits; 2 is prime) 11 -> 1011 (3 set bits; 3 is prime) 12 -> 1100 (2 set bits; 2 is prime) 13 -> 1101 (3 set bits; 3 is prime) 14 -> 1110 (3 set bits; 3 is prime) 15 -> 1111 (4 set bits; 4 is not prime) 5 numbers have a prime number of set bits. Constraints: 1 <= left <= right <= 106 0 <= right - left <= 104935Amazon,55,Jump Game,Med,"Array, Dynamic Programming, Greedy",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. Example 1: 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. Example 2: 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. Constraints: 1 <= nums.length <= 104 0 <= nums[i] <= 105936Amazon,2667,Create Hello World Function,Easy,"Array, Hash Table, Math, Stack, Sliding Window",937Amazon,2,Add Two Numbers,Med,"Linked List, Math, Recursion",You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order; and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero; except the number 0 itself. Example 1: Input: l1 = [2;4;3]; l2 = [5;6;4] Output: [7;0;8] Explanation: 342 + 465 = 807. Example 2: Input: l1 = [0]; l2 = [0] Output: [0] Example 3: Input: l1 = [9;9;9;9;9;9;9]; l2 = [9;9;9;9] Output: [8;9;9;9;0;0;0;1] Constraints: The number of nodes in each linked list is in the range [1; 100]. 0 <= Node.val <= 9 It is guaranteed that the list represents a number that does not have leading zeros.938Amazon,5,Longest Palindromic Substring,Med,"Two Pointers, String, Dynamic Programming","Given a string s; return the longest palindromic substring in s. Example 1: Input: s = ""babad"" Output: ""bab"" Explanation: ""aba"" is also a valid answer. Example 2: Input: s = ""cbbd"" Output: ""bb"" Constraints: 1 <= s.length <= 1000 s consist of only digits and English letters."939Amazon,127,Word Ladder,Hard,"Hash Table, String, Breadth-First Search","A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Every adjacent pair of words differs by a single letter. Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. sk == endWord Given two words; beginWord and endWord; and a dictionary wordList; return the number of words in the shortest transformation sequence from beginWord to endWord; or 0 if no such sequence exists. Example 1: Input: beginWord = ""hit""; endWord = ""cog""; wordList = [""hot"";""dot"";""dog"";""lot"";""log"";""cog""] Output: 5 Explanation: One shortest transformation sequence is ""hit"" -> ""hot"" -> ""dot"" -> ""dog"" -> cog""; which is 5 words long. Example 2: Input: beginWord = ""hit""; endWord = ""cog""; wordList = [""hot"";""dot"";""dog"";""lot"";""log""] Output: 0 Explanation: The endWord ""cog"" is not in wordList; therefore there is no valid transformation sequence. Constraints: 1 <= beginWord.length <= 10 endWord.length == beginWord.length 1 <= wordList.length <= 5000 wordList[i].length == beginWord.length beginWord; endWord; and wordList[i] consist of lowercase English letters. beginWord != endWord All the words in wordList are unique."940Amazon,875,Koko Eating Bananas,Med,"Array, Two Pointers, Dynamic Programming, Enumeration",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. Example 1: 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. Example 2: Input: arr = [2;2;2] Output: 0 Explanation: There is no mountain. Constraints: 1 <= arr.length <= 104 0 <= arr[i] <= 104 Follow up: Can you solve it using only one pass? Can you solve it in O(1) space?941Amazon,994,Rotting Oranges,Med,"Array, Hash Table, Math, Bit Manipulation",There are 8 prison cells in a row and each cell is either occupied or vacant. Each day; whether the cell is occupied or vacant changes according to the following rules: If a cell has two adjacent neighbors that are both occupied or both vacant; then the cell becomes occupied. Otherwise; it becomes vacant. Note that because the prison is a row; the first and the last cells in the row can't have two adjacent neighbors. You are given an integer array cells where cells[i] == 1 if the ith cell is occupied and cells[i] == 0 if the ith cell is vacant; and you are given an integer n. Return the state of the prison after n days (i.e.; n such changes described above). Example 1: Input: cells = [0;1;0;1;1;0;0;1]; n = 7 Output: [0;0;1;1;0;0;0;0] Explanation: The following table summarizes the state of the prison on each day: Day 0: [0; 1; 0; 1; 1; 0; 0; 1] Day 1: [0; 1; 1; 0; 0; 0; 0; 0] Day 2: [0; 0; 0; 0; 1; 1; 1; 0] Day 3: [0; 1; 1; 0; 0; 1; 0; 0] Day 4: [0; 0; 0; 0; 0; 1; 0; 0] Day 5: [0; 1; 1; 1; 0; 1; 0; 0] Day 6: [0; 0; 1; 0; 1; 1; 0; 0] Day 7: [0; 0; 1; 1; 0; 0; 0; 0] Example 2: Input: cells = [1;0;0;1;0;0;1;0]; n = 1000000000 Output: [0;0;1;1;1;1;1;0] Constraints: cells.length == 8 cells[i] is either 0 or 1. 1 <= n <= 109942Amazon,210,Course Schedule II,Med,"Depth-First Search, Breadth-First Search, Graph, Topological Sort",There are a total of numCourses courses you have to take; labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai; bi] indicates that you must take course bi first if you want to take course ai. For example; the pair [0; 1]; indicates that to take course 0 you have to first take course 1. Return the ordering of courses you should take to finish all courses. If there are many valid answers; return any of them. If it is impossible to finish all courses; return an empty array. Example 1: Input: numCourses = 2; prerequisites = [[1;0]] Output: [0;1] Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0;1]. Example 2: Input: numCourses = 4; prerequisites = [[1;0];[2;0];[3;1];[3;2]] Output: [0;2;1;3] Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0;1;2;3]. Another correct ordering is [0;2;1;3]. Example 3: Input: numCourses = 1; prerequisites = [] Output: [0] Constraints: 1 <= numCourses <= 2000 0 <= prerequisites.length <= numCourses * (numCourses - 1) prerequisites[i].length == 2 0 <= ai; bi < numCourses ai != bi All the pairs [ai; bi] are distinct.943Amazon,9,Palindrome Number,Easy,Math,Given an integer x; return true if x is a palindrome; and false otherwise. Example 1: Input: x = 121 Output: true Explanation: 121 reads as 121 from left to right and from right to left. Example 2: Input: x = -121 Output: false Explanation: From left to right; it reads -121. From right to left; it becomes 121-. Therefore it is not a palindrome. Example 3: Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Constraints: -231 <= x <= 231 - 1 Follow up: Could you solve it without converting the integer to a string?944Amazon,1757,Recyclable and Low Fat Products,Easy,"Array, Dynamic Programming, Breadth-First Search",A certain bug's home is on the x-axis at position x. Help them get there from position 0. The bug jumps according to the following rules: It can jump exactly a positions forward (to the right). It can jump exactly b positions backward (to the left). It cannot jump backward twice in a row. It cannot jump to any forbidden positions. The bug may jump forward beyond its home; but it cannot jump to positions numbered with negative integers. Given an array of integers forbidden; where forbidden[i] means that the bug cannot jump to the position forbidden[i]; and integers a; b; and x; return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x; return -1. Example 1: Input: forbidden = [14;4;18;1;15]; a = 3; b = 15; x = 9 Output: 3 Explanation: 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home. Example 2: Input: forbidden = [8;3;16;6;12;20]; a = 15; b = 13; x = 11 Output: -1 Example 3: Input: forbidden = [1;6;2;14;5;17;4]; a = 16; b = 9; x = 7 Output: 2 Explanation: One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home. Constraints: 1 <= forbidden.length <= 1000 1 <= a; b; forbidden[i] <= 2000 0 <= x <= 2000 All the elements in forbidden are distinct. Position x is not forbidden.945Amazon,138,Copy List with Random Pointer,Med,"Hash Table, Linked List",A linked list of length n is given such that each node contains an additional random pointer; which could point to any node in the list; or null. Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes; where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list. For example; if there are two nodes X and Y in the original list; where X.random --> Y; then for the corresponding two nodes x and y in the copied list; x.random --> y. Return the head of the copied linked list. The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val; random_index] where: val: an integer representing Node.val random_index: the index of the node (range from 0 to n-1) that the random pointer points to; or null if it does not point to any node. Your code will only be given the head of the original linked list. Example 1: Input: head = [[7;null];[13;0];[11;4];[10;2];[1;0]] Output: [[7;null];[13;0];[11;4];[10;2];[1;0]] Example 2: Input: head = [[1;1];[2;1]] Output: [[1;1];[2;1]] Example 3: Input: head = [[3;null];[3;0];[3;null]] Output: [[3;null];[3;0];[3;null]] Constraints: 0 <= n <= 1000 -104 <= Node.val <= 104 Node.random is null or is pointing to some node in the linked list.946Amazon,20,Valid Parentheses,Easy,"String, Stack","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. Example 1: Input: s = ""()"" Output: true Example 2: Input: s = ""()[]{}"" Output: true Example 3: Input: s = ""(]"" Output: false Example 4: Input: s = ""([])"" Output: true Constraints: 1 <= s.length <= 104 s consists of parentheses only '()[]{}'."947Amazon,53,Maximum Subarray,Med,"Array, Divide and Conquer, Dynamic Programming",Given an integer array nums; find the subarray with the largest sum; and return its sum. Example 1: Input: nums = [-2;1;-3;4;-1;2;1;-5;4] Output: 6 Explanation: The subarray [4;-1;2;1] has the largest sum 6. Example 2: Input: nums = [1] Output: 1 Explanation: The subarray [1] has the largest sum 1. Example 3: Input: nums = [5;4;-1;7;8] Output: 23 Explanation: The subarray [5;4;-1;7;8] has the largest sum 23. Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 Follow up: If you have figured out the O(n) solution; try coding another solution using the divide and conquer approach; which is more subtle.948Amazon,4,Median of Two Sorted Arrays,Hard,"Array, Binary Search, Divide and Conquer",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)). Example 1: Input: nums1 = [1;3]; nums2 = [2] Output: 2.00000 Explanation: merged array = [1;2;3] and median is 2. Example 2: Input: nums1 = [1;2]; nums2 = [3;4] Output: 2.50000 Explanation: merged array = [1;2;3;4] and median is (2 + 3) / 2 = 2.5. Constraints: nums1.length == m nums2.length == n 0 <= m <= 1000 0 <= n <= 1000 1 <= m + n <= 2000 -106 <= nums1[i]; nums2[i] <= 106949Amazon,14,Longest Common Prefix,Easy,"String, Trie","Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix; return an empty string """". Example 1: Input: strs = [""flower"";""flow"";""flight""] Output: ""fl"" Example 2: Input: strs = [""dog"";""racecar"";""car""] Output: """" Explanation: There is no common prefix among the input strings. Constraints: 1 <= strs.length <= 200 0 <= strs[i].length <= 200 strs[i] consists of only lowercase English letters."950Amazon,22,Generate Parentheses,Med,"String, Dynamic Programming, Backtracking","Given n pairs of parentheses; write a function to generate all combinations of well-formed parentheses. Example 1: Input: n = 3 Output: [""((()))"";""(()())"";""(())()"";""()(())"";""()()()""] Example 2: Input: n = 1 Output: [""()""] Constraints: 1 <= n <= 8"951Amazon,23,Merge k Sorted Lists,Hard,"Linked List, Divide and Conquer, Heap (Priority Queue), Merge Sort",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. Example 1: 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 Example 2: Input: lists = [] Output: [] Example 3: Input: lists = [[]] Output: [] Constraints: k == lists.length 0 <= k <= 104 0 <= lists[i].length <= 500 -104 <= lists[i][j] <= 104 lists[i] is sorted in ascending order. The sum of lists[i].length will not exceed 104.952Amazon,70,Climbing Stairs,Easy,"Math, Dynamic Programming, Memoization",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? Example 1: Input: n = 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: Input: n = 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step Constraints: 1 <= n <= 45953Amazon,79,Word Search,Med,"Array, String, Backtracking, Matrix","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. Example 1: Input: board = [[""A"";""B"";""C"";""E""];[""S"";""F"";""C"";""S""];[""A"";""D"";""E"";""E""]]; word = ""ABCCED"" Output: true Example 2: Input: board = [[""A"";""B"";""C"";""E""];[""S"";""F"";""C"";""S""];[""A"";""D"";""E"";""E""]]; word = ""SEE"" Output: true Example 3: Input: board = [[""A"";""B"";""C"";""E""];[""S"";""F"";""C"";""S""];[""A"";""D"";""E"";""E""]]; word = ""ABCB"" Output: false Constraints: m == board.length n = board[i].length 1 <= m; n <= 6 1 <= word.length <= 15 board and word consists of only lowercase and uppercase English letters. Follow up: Could you use search pruning to make your solution faster with a larger board?"954Amazon,139,Word Break,Med,"Array, Hash Table, String, Dynamic Programming, Trie, Memoization","Given a string s and a dictionary of strings wordDict; return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation. Example 1: Input: s = ""leetcode""; wordDict = [""leet"";""code""] Output: true Explanation: Return true because ""leetcode"" can be segmented as ""leet code"". Example 2: Input: s = ""applepenapple""; wordDict = [""apple"";""pen""] Output: true Explanation: Return true because ""applepenapple"" can be segmented as ""apple pen apple"". Note that you are allowed to reuse a dictionary word. Example 3: Input: s = ""catsandog""; wordDict = [""cats"";""dog"";""sand"";""and"";""cat""] Output: false Constraints: 1 <= s.length <= 300 1 <= wordDict.length <= 1000 1 <= wordDict[i].length <= 20 s and wordDict[i] consist of only lowercase English letters. All the strings of wordDict are unique."955Amazon,236,Lowest Common Ancestor of a Binary Tree,Med,"Tree, Depth-First Search, Binary Tree",Given a binary tree; find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Example 1: Input: root = [3;5;1;6;2;0;8;null;null;7;4]; p = 5; q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3. Example 2: Input: root = [3;5;1;6;2;0;8;null;null;7;4]; p = 5; q = 4 Output: 5 Explanation: The LCA of nodes 5 and 4 is 5; since a node can be a descendant of itself according to the LCA definition. Example 3: Input: root = [1;2]; p = 1; q = 2 Output: 1 Constraints: The number of nodes in the tree is in the range [2; 105]. -109 <= Node.val <= 109 All Node.val are unique. p != q p and q will exist in the tree.956Amazon,253,Meeting Rooms II,Med,"Array, Two Pointers, Greedy, Sorting, Heap (Priority Queue), Prefix Sum",957Amazon,15,3Sum,Med,"Array, Two Pointers, Sorting",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. Example 1: Input: nums = [-1;0;1;2;-1;-4] Output: [[-1;-1;2];[-1;0;1]] Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1;0;1] and [-1;-1;2]. Notice that the order of the output and the order of the triplets does not matter. Example 2: Input: nums = [0;1;1] Output: [] Explanation: The only possible triplet does not sum up to 0. Example 3: Input: nums = [0;0;0] Output: [[0;0;0]] Explanation: The only possible triplet sums up to 0. Constraints: 3 <= nums.length <= 3000 -105 <= nums[i] <= 105958Amazon,17,Letter Combinations of a Phone Number,Med,"Hash Table, String, Backtracking","Given a string containing digits from 2-9 inclusive; return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. Example 1: Input: digits = ""23"" Output: [""ad"";""ae"";""af"";""bd"";""be"";""bf"";""cd"";""ce"";""cf""] Example 2: Input: digits = """" Output: [] Example 3: Input: digits = ""2"" Output: [""a"";""b"";""c""] Constraints: 0 <= digits.length <= 4 digits[i] is a digit in the range ['2'; '9']."959Amazon,13,Roman to Integer,Easy,"Hash Table, Math, String","Roman numerals are represented by seven different symbols: I; V; X; L; C; D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example; 2 is written as II in Roman numeral; just two ones added together. 12 is written as XII; which is simply X + II. The number 27 is written as XXVII; which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However; the numeral for four is not IIII. Instead; the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine; which is written as IX. There are six instances where subtraction is used: I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900. Given a roman numeral; convert it to an integer. Example 1: Input: s = ""III"" Output: 3 Explanation: III = 3. Example 2: Input: s = ""LVIII"" Output: 58 Explanation: L = 50; V= 5; III = 3. Example 3: Input: s = ""MCMXCIV"" Output: 1994 Explanation: M = 1000; CM = 900; XC = 90 and IV = 4. Constraints: 1 <= s.length <= 15 s contains only the characters ('I'; 'V'; 'X'; 'L'; 'C'; 'D'; 'M'). It is guaranteed that s is a valid roman numeral in the range [1; 3999]."960Amazon,54,Spiral Matrix,Med,"Array, Matrix, Simulation",Given an m x n matrix; return all elements of the matrix in spiral order. Example 1: Input: matrix = [[1;2;3];[4;5;6];[7;8;9]] Output: [1;2;3;6;9;8;7;4;5] Example 2: Input: matrix = [[1;2;3;4];[5;6;7;8];[9;10;11;12]] Output: [1;2;3;4;8;12;11;10;9;5;6;7] Constraints: m == matrix.length n == matrix[i].length 1 <= m; n <= 10 -100 <= matrix[i][j] <= 100961Amazon,56,Merge Intervals,Med,"Array, Sorting",Given an array of intervals where intervals[i] = [starti; endi]; merge all overlapping intervals; and return an array of the non-overlapping intervals that cover all the intervals in the input. Example 1: Input: intervals = [[1;3];[2;6];[8;10];[15;18]] Output: [[1;6];[8;10];[15;18]] Explanation: Since intervals [1;3] and [2;6] overlap; merge them into [1;6]. Example 2: Input: intervals = [[1;4];[4;5]] Output: [[1;5]] Explanation: Intervals [1;4] and [4;5] are considered overlapping. Constraints: 1 <= intervals.length <= 104 intervals[i].length == 2 0 <= starti <= endi <= 104962Amazon,104,Maximum Depth of Binary Tree,Easy,"Tree, Depth-First Search, Breadth-First Search, Binary Tree",Given the root of a binary tree; return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Example 1: Input: root = [3;9;20;null;null;15;7] Output: 3 Example 2: Input: root = [1;null;2] Output: 2 Constraints: The number of nodes in the tree is in the range [0; 104]. -100 <= Node.val <= 100963Amazon,128,Longest Consecutive Sequence,Med,"Array, Hash Table, Union Find",Given an unsorted array of integers nums; return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time. Example 1: Input: nums = [100;4;200;1;3;2] Output: 4 Explanation: The longest consecutive elements sequence is [1; 2; 3; 4]. Therefore its length is 4. Example 2: Input: nums = [0;3;7;2;5;8;4;6;0;1] Output: 9 Constraints: 0 <= nums.length <= 105 -109 <= nums[i] <= 109964Amazon,215,Kth Largest Element in an Array,Med,"Array, Divide and Conquer, Sorting, Heap (Priority Queue), Quickselect",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. Can you solve it without sorting? Example 1: Input: nums = [3;2;1;5;6;4]; k = 2 Output: 5 Example 2: Input: nums = [3;2;3;1;2;4;5;5;6]; k = 4 Output: 4 Constraints: 1 <= k <= nums.length <= 105 -104 <= nums[i] <= 104965Amazon,227,Basic Calculator II,Med,"Math, String, Stack","Given a string s which represents an expression; evaluate this expression and return its value. 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(). Example 1: Input: s = ""3+2*2"" Output: 7 Example 2: Input: s = "" 3/2 "" Output: 1 Example 3: Input: s = "" 3+5 / 2 "" Output: 5 Constraints: 1 <= s.length <= 3 * 105 s consists of integers and operators ('+'; '-'; '*'; '/') separated by some number of spaces. s represents a valid expression. All the integers in the expression are non-negative integers in the range [0; 231 - 1]. The answer is guaranteed to fit in a 32-bit integer."966Amazon,380,Insert Delete GetRandom O(1),Med,"Array, Hash Table, Math, Design, Randomized","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. Example 1: Input [""RandomizedSet""; ""insert""; ""remove""; ""insert""; ""getRandom""; ""remove""; ""insert""; ""getRandom""] [[]; [1]; [2]; [2]; []; [1]; [2]; []] Output [null; true; false; true; 2; true; false; 2] Explanation RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set; returns true. Set now contains [1;2]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set; returns true. Set now contains [2]. randomizedSet.insert(2); // 2 was already in the set; so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set; getRandom() will always return 2. Constraints: -231 <= val <= 231 - 1 At most 2 * 105 calls will be made to insert; remove; and getRandom. There will be at least one element in the data structure when getRandom is called."967Amazon,45,Jump Game II,Med,"Array, Dynamic Programming, Greedy",You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0]. Each element nums[i] represents the maximum length of a forward jump from index i. In other words; if you are at nums[i]; you can jump to any nums[i + j] where: 0 <= j <= nums[i] and i + j < n Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1]. Example 1: 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. Example 2: Input: nums = [2;3;0;1;4] Output: 2 Constraints: 1 <= nums.length <= 104 0 <= nums[i] <= 1000 It's guaranteed that you can reach nums[n - 1].968Amazon,283,Move Zeroes,Easy,"Array, Two Pointers",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. Example 1: Input: nums = [0;1;0;3;12] Output: [1;3;12;0;0] Example 2: Input: nums = [0] Output: [0] Constraints: 1 <= nums.length <= 104 -231 <= nums[i] <= 231 - 1 Follow up: Could you minimize the total number of operations done?969Amazon,1650,Lowest Common Ancestor of a Binary Tree III,Med,"Hash Table, Bit Manipulation, Tree, Depth-First Search",970Amazon,3317,Find the Number of Possible Ways for an Event,Hard,"Array, Hash Table, String, Greedy, Sorting, Counting","You are given a 0-indexed string array words having length n and containing 0-indexed strings. You are allowed to perform the following operation any number of times (including zero): Choose integers i; j; x; and y such that 0 <= i; j < n; 0 <= x < words[i].length; 0 <= y < words[j].length; and swap the characters words[i][x] and words[j][y]. Return an integer denoting the maximum number of palindromes words can contain; after performing some operations. Note: i and j may be equal during an operation. Example 1: Input: words = [""abbb"";""ba"";""aa""] Output: 3 Explanation: In this example; one way to get the maximum number of palindromes is: Choose i = 0; j = 1; x = 0; y = 0; so we swap words[0][0] and words[1][0]. words becomes [""bbbb"";""aa"";""aa""]. All strings in words are now palindromes. Hence; the maximum number of palindromes achievable is 3. Example 2: Input: words = [""abc"";""ab""] Output: 2 Explanation: In this example; one way to get the maximum number of palindromes is: Choose i = 0; j = 1; x = 1; y = 0; so we swap words[0][1] and words[1][0]. words becomes [""aac"";""bb""]. Choose i = 0; j = 0; x = 1; y = 2; so we swap words[0][1] and words[0][2]. words becomes [""aca"";""bb""]. Both strings are now palindromes. Hence; the maximum number of palindromes achievable is 2. Example 3: Input: words = [""cd"";""ef"";""a""] Output: 1 Explanation: In this example; there is no need to perform any operation. There is one palindrome in words ""a"". It can be shown that it is not possible to get more than one palindrome after any number of operations. Hence; the answer is 1. Constraints: 1 <= words.length <= 1000 1 <= words[i].length <= 100 words[i] consists only of lowercase English letters."971Amazon,11,Container With Most Water,Med,"Array, Two Pointers, Greedy",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. Example 1: 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. Example 2: Input: height = [1;1] Output: 1 Constraints: n == height.length 2 <= n <= 105 0 <= height[i] <= 104972Amazon,179,Largest Number,Med,"Array, String, Greedy, Sorting","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. Example 1: Input: nums = [10;2] Output: ""210"" Example 2: Input: nums = [3;30;34;5;9] Output: ""9534330"" Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 109"973Amazon,189,Rotate Array,Med,"Array, Math, Two Pointers",Given an integer array nums; rotate the array to the right by k steps; where k is non-negative. Example 1: 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] Example 2: Input: nums = [-1;-100;3;99]; k = 2 Output: [3;99;-1;-100] Explanation: rotate 1 steps to the right: [99;-1;-100;3] rotate 2 steps to the right: [3;99;-1;-100] Constraints: 1 <= nums.length <= 105 -231 <= nums[i] <= 231 - 1 0 <= k <= 105 Follow up: Try to come up with as many solutions as you can. There are at least three different ways to solve this problem. Could you do it in-place with O(1) extra space?974Amazon,212,Word Search II,Hard,"Array, String, Backtracking, Trie, Matrix","Given an m x n board of characters and a list of strings words; return all words on the board. Each word must 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 in a word. Example 1: Input: board = [[""o"";""a"";""a"";""n""];[""e"";""t"";""a"";""e""];[""i"";""h"";""k"";""r""];[""i"";""f"";""l"";""v""]]; words = [""oath"";""pea"";""eat"";""rain""] Output: [""eat"";""oath""] Example 2: Input: board = [[""a"";""b""];[""c"";""d""]]; words = [""abcb""] Output: [] Constraints: m == board.length n == board[i].length 1 <= m; n <= 12 board[i][j] is a lowercase English letter. 1 <= words.length <= 3 * 104 1 <= words[i].length <= 10 words[i] consists of lowercase English letters. All the strings of words are unique."975Amazon,297,Serialize and Deserialize Binary Tree,Hard,"String, Tree, Depth-First Search, Breadth-First Search, Design, Binary Tree",Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer; or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format; so please be creative and come up with different approaches yourself. Example 1: Input: root = [1;2;3;null;null;4;5] Output: [1;2;3;null;null;4;5] Example 2: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0; 104]. -1000 <= Node.val <= 1000976Amazon,739,Daily Temperatures,Med,"Array, Stack, Monotonic Stack",Given an array of integers temperatures represents the daily temperatures; return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible; keep answer[i] == 0 instead. Example 1: Input: temperatures = [73;74;75;71;69;72;76;73] Output: [1;1;4;2;1;1;0;0] Example 2: Input: temperatures = [30;40;50;60] Output: [1;1;1;0] Example 3: Input: temperatures = [30;60;90] Output: [1;1;0] Constraints: 1 <= temperatures.length <= 105 30 <= temperatures[i] <= 100977Amazon,2979,Most Expensive Item That Can Not Be Bought,Med,"Array, Hash Table, Binary Search, Dynamic Programming, Sorting",You are given an integer n representing the number of houses on a number line; numbered from 0 to n - 1. Additionally; you are given a 2D integer array offers where offers[i] = [starti; endi; goldi]; indicating that ith buyer wants to buy all the houses from starti to endi for goldi amount of gold. As a salesman; your goal is to maximize your earnings by strategically selecting and selling houses to buyers. Return the maximum amount of gold you can earn. Note that different buyers can't buy the same house; and some houses may remain unsold. Example 1: Input: n = 5; offers = [[0;0;1];[0;2;2];[1;3;2]] Output: 3 Explanation: There are 5 houses numbered from 0 to 4 and there are 3 purchase offers. We sell houses in the range [0;0] to 1st buyer for 1 gold and houses in the range [1;3] to 3rd buyer for 2 golds. It can be proven that 3 is the maximum amount of gold we can achieve. Example 2: Input: n = 5; offers = [[0;0;1];[0;2;10];[1;3;2]] Output: 10 Explanation: There are 5 houses numbered from 0 to 4 and there are 3 purchase offers. We sell houses in the range [0;2] to 2nd buyer for 10 golds. It can be proven that 10 is the maximum amount of gold we can achieve. Constraints: 1 <= n <= 105 1 <= offers.length <= 105 offers[i].length == 3 0 <= starti <= endi <= n - 1 1 <= goldi <= 103978Amazon,33,Search in Rotated Sorted Array,Med,"Array, Binary Search",There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function; nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k]; nums[k+1]; ...; nums[n-1]; nums[0]; nums[1]; ...; nums[k-1]] (0-indexed). For example; [0;1;2;4;5;6;7] might be rotated at pivot index 3 and become [4;5;6;7;0;1;2]. Given the array nums after the possible rotation and an integer target; return the index of target if it is in nums; or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [4;5;6;7;0;1;2]; target = 0 Output: 4 Example 2: Input: nums = [4;5;6;7;0;1;2]; target = 3 Output: -1 Example 3: Input: nums = [1]; target = 0 Output: -1 Constraints: 1 <= nums.length <= 5000 -104 <= nums[i] <= 104 All values of nums are unique. nums is an ascending array that is possibly rotated. -104 <= target <= 104979Amazon,124,Binary Tree Maximum Path Sum,Hard,"Dynamic Programming, Tree, Depth-First Search, Binary Tree",A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree; return the maximum path sum of any non-empty path. Example 1: Input: root = [1;2;3] Output: 6 Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. Example 2: Input: root = [-10;9;20;null;null;15;7] Output: 42 Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42. Constraints: The number of nodes in the tree is in the range [1; 3 * 104]. -1000 <= Node.val <= 1000980Amazon,134,Gas Station,Med,"Array, Greedy",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. Example 1: 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. Example 2: Input: gas = [2;3;4]; cost = [3;4;3] Output: -1 Explanation: You can't start at station 0 or 1; as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2; as it requires 4 unit of gas but you only have 3. Therefore; you can't travel around the circuit once no matter where you start. Constraints: n == gas.length == cost.length 1 <= n <= 105 0 <= gas[i]; cost[i] <= 104981Amazon,162,Find Peak Element,Med,"Array, Binary Search",A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums; find a peak element; and return its index. If the array contains multiple peaks; return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -∞. In other words; an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in O(log n) time. Example 1: Input: nums = [1;2;3;1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2. Example 2: Input: nums = [1;2;1;3;5;6;4] Output: 5 Explanation: Your function can return either index number 1 where the peak element is 2; or index number 5 where the peak element is 6. Constraints: 1 <= nums.length <= 1000 -231 <= nums[i] <= 231 - 1 nums[i] != nums[i + 1] for all valid i.982Amazon,224,Basic Calculator,Hard,"Math, String, Stack, Recursion","Given a string s representing a valid expression; implement a basic calculator to evaluate it; and return the result of the evaluation. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions; such as eval(). Example 1: Input: s = ""1 + 1"" Output: 2 Example 2: Input: s = "" 2-1 + 2 "" Output: 3 Example 3: Input: s = ""(1+(4+5+2)-3)+(6+8)"" Output: 23 Constraints: 1 <= s.length <= 3 * 105 s consists of digits; '+'; '-'; '('; ')'; and ' '. s represents a valid expression. '+' is not used as a unary operation (i.e.; ""+1"" and ""+(2 + 3)"" is invalid). '-' could be used as a unary operation (i.e.; ""-1"" and ""-(2 + 3)"" is valid). There will be no two consecutive operators in the input. Every number and running calculation will fit in a signed 32-bit integer."983Amazon,239,Sliding Window Maximum,Hard,"Array, Queue, Sliding Window, Heap (Priority Queue), Monotonic Queue",You are given an array of integers nums; 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 max sliding window. Example 1: Input: nums = [1;3;-1;-3;5;3;6;7]; k = 3 Output: [3;3;5;5;6;7] Explanation: Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 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 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 Example 2: Input: nums = [1]; k = 1 Output: [1] Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 1 <= k <= nums.length984Amazon,295,Find Median from Data Stream,Hard,"Two Pointers, Design, Sorting, Heap (Priority Queue), 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. Example 1: 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 Constraints: -105 <= num <= 105 There will be at least one element in the data structure before calling findMedian. At most 5 * 104 calls will be made to addNum and findMedian. Follow up: If all integer numbers from the stream are in the range [0; 100]; how would you optimize your solution? If 99% of all integer numbers from the stream are in the range [0; 100]; how would you optimize your solution?"985Amazon,560,Subarray Sum Equals K,Med,"Array, Hash Table, Prefix Sum",Given an array of integers nums and an integer k; return the total number of subarrays whose sum equals to k. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: nums = [1;1;1]; k = 2 Output: 2 Example 2: Input: nums = [1;2;3]; k = 3 Output: 2 Constraints: 1 <= nums.length <= 2 * 104 -1000 <= nums[i] <= 1000 -107 <= k <= 107986Amazon,863,All Nodes Distance K in Binary Tree,Med,"Dynamic Programming, Tree, Depth-First Search, Graph",There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [ai; bi] indicates that there is an edge between nodes ai and bi in the tree. Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes. Example 1: Input: n = 6; edges = [[0;1];[0;2];[2;3];[2;4];[2;5]] Output: [8;12;6;10;10;10] Explanation: The tree is shown above. We can see that dist(0;1) + dist(0;2) + dist(0;3) + dist(0;4) + dist(0;5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence; answer[0] = 8; and so on. Example 2: Input: n = 1; edges = [] Output: [0] Example 3: Input: n = 2; edges = [[1;0]] Output: [1;1] Constraints: 1 <= n <= 3 * 104 edges.length == n - 1 edges[i].length == 2 0 <= ai; bi < n ai != bi The given input represents a valid tree.987Amazon,962,Maximum Width Ramp,Med,"String, Dynamic Programming","A binary string is monotone increasing if it consists of some number of 0's (possibly none); followed by some number of 1's (also possibly none). You are given a binary string s. You can flip s[i] changing it from 0 to 1 or from 1 to 0. Return the minimum number of flips to make s monotone increasing. Example 1: Input: s = ""00110"" Output: 1 Explanation: We flip the last digit to get 00111. Example 2: Input: s = ""010110"" Output: 2 Explanation: We flip to get 011111; or alternatively 000111. Example 3: Input: s = ""00011000"" Output: 2 Explanation: We flip to get 00000000. Constraints: 1 <= s.length <= 105 s[i] is either '0' or '1'."988Amazon,1152,Analyze User Website Visit Pattern,Med,"Greedy, Heap (Priority Queue)",989Amazon,7,Reverse Integer,Med,Math,Given a signed 32-bit integer x; return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231; 231 - 1]; then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). Example 1: Input: x = 123 Output: 321 Example 2: Input: x = -123 Output: -321 Example 3: Input: x = 120 Output: 21 Constraints: -231 <= x <= 231 - 1990Amazon,12,Integer to Roman,Med,"Hash Table, Math, String","Seven different symbols represent Roman numerals with the following values: Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 Roman numerals are formed by appending the conversions of decimal place values from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules: If the value does not start with 4 or 9; select the symbol of the maximal value that can be subtracted from the input; append that symbol to the result; subtract its value; and convert the remainder to a Roman numeral. If the value starts with 4 or 9 use the subtractive form representing one symbol subtracted from the following symbol; for example; 4 is 1 (I) less than 5 (V): IV and 9 is 1 (I) less than 10 (X): IX. Only the following subtractive forms are used: 4 (IV); 9 (IX); 40 (XL); 90 (XC); 400 (CD) and 900 (CM). Only powers of 10 (I; X; C; M) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5 (V); 50 (L); or 500 (D) multiple times. If you need to append a symbol 4 times use the subtractive form. Given an integer; convert it to a Roman numeral. Example 1: Input: num = 3749 Output: ""MMMDCCXLIX"" Explanation: 3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M) 700 = DCC as 500 (D) + 100 (C) + 100 (C) 40 = XL as 10 (X) less of 50 (L) 9 = IX as 1 (I) less of 10 (X) Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places Example 2: Input: num = 58 Output: ""LVIII"" Explanation: 50 = L 8 = VIII Example 3: Input: num = 1994 Output: ""MCMXCIV"" Explanation: 1000 = M 900 = CM 90 = XC 4 = IV Constraints: 1 <= num <= 3999"991Amazon,21,Merge Two Sorted Lists,Easy,"Linked List, Recursion",You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list. Example 1: Input: list1 = [1;2;4]; list2 = [1;3;4] Output: [1;1;2;3;4;4] Example 2: Input: list1 = []; list2 = [] Output: [] Example 3: Input: list1 = []; list2 = [0] Output: [0] Constraints: The number of nodes in both lists is in the range [0; 50]. -100 <= Node.val <= 100 Both list1 and list2 are sorted in non-decreasing order.992Amazon,27,Remove Element,Easy,"Array, Two Pointers",Given an integer array nums and an integer val; remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val. Consider the number of elements in nums which are not equal to val be k; to get accepted; you need to do the following things: Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums. Return k. Custom Judge: The judge will test your solution with the following code: int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums; val); // Calls your implementation assert k == expectedNums.length; sort(nums; 0; k); // Sort the first k elements of nums for (int i = 0; i < actualLength; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass; then your solution will be accepted. Example 1: Input: nums = [3;2;2;3]; val = 3 Output: 2; nums = [2;2;_;_] Explanation: Your function should return k = 2; with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). Example 2: Input: nums = [0;1;2;2;3;0;4;2]; val = 2 Output: 5; nums = [0;1;4;0;3;_;_;_] Explanation: Your function should return k = 5; with the first five elements of nums containing 0; 0; 1; 3; and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). Constraints: 0 <= nums.length <= 100 0 <= nums[i] <= 50 0 <= val <= 100993Amazon,84,Largest Rectangle in Histogram,Hard,"Array, Stack, Monotonic Stack",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 1: Input: heights = [2;1;5;6;2;3] Output: 10 Explanation: The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area; which has an area = 10 units. Example 2: Input: heights = [2;4] Output: 4 Constraints: 1 <= heights.length <= 105 0 <= heights[i] <= 104994Amazon,122,Best Time to Buy and Sell Stock II,Med,"Array, Dynamic Programming, Greedy",You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day; you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However; you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve. Example 1: Input: prices = [7;1;5;3;6;4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5); profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6); profit = 6-3 = 3. Total profit is 4 + 3 = 7. Example 2: Input: prices = [1;2;3;4;5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5); profit = 5-1 = 4. Total profit is 4. Example 3: Input: prices = [7;6;4;3;1] Output: 0 Explanation: There is no way to make a positive profit; so we never buy the stock to achieve the maximum profit of 0. Constraints: 1 <= prices.length <= 3 * 104 0 <= prices[i] <= 104995Amazon,135,Candy,Hard,"Array, Greedy",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. Example 1: Input: ratings = [1;0;2] Output: 5 Explanation: You can allocate to the first; second and third child with 2; 1; 2 candies respectively. Example 2: 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. Constraints: n == ratings.length 1 <= n <= 2 * 104 0 <= ratings[i] <= 2 * 104996Amazon,198,House Robber,Med,"Array, Dynamic Programming",You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed; the only constraint stopping you from robbing each of them is that adjacent houses have security systems 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. Example 1: 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. Example 2: Input: nums = [2;7;9;3;1] Output: 12 Explanation: Rob house 1 (money = 2); rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 400997Amazon,238,Product of Array Except Self,Med,"Array, Prefix Sum",Given an integer array nums; return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation. Example 1: Input: nums = [1;2;3;4] Output: [24;12;8;6] Example 2: Input: nums = [-1;1;0;-3;3] Output: [0;0;9;0;0] Constraints: 2 <= nums.length <= 105 -30 <= nums[i] <= 30 The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)998Amazon,242,Valid Anagram,Easy,"Hash Table, String, Sorting","Given two strings s and t; return true if t is an anagram of s; and false otherwise. Example 1: Input: s = ""anagram""; t = ""nagaram"" Output: true Example 2: Input: s = ""rat""; t = ""car"" Output: false Constraints: 1 <= s.length; t.length <= 5 * 104 s and t consist of lowercase English letters. Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?"999Amazon,273,Integer to English Words,Hard,"Math, String, Recursion","Convert a non-negative integer num to its English words representation. Example 1: Input: num = 123 Output: ""One Hundred Twenty Three"" Example 2: Input: num = 12345 Output: ""Twelve Thousand Three Hundred Forty Five"" Example 3: Input: num = 1234567 Output: ""One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"" Constraints: 0 <= num <= 231 - 1"1000Amazon,322,Coin Change,Med,"Array, Dynamic Programming, Breadth-First Search",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. Example 1: Input: coins = [1;2;5]; amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1 Example 2: Input: coins = [2]; amount = 3 Output: -1 Example 3: Input: coins = [1]; amount = 0 Output: 0 Constraints: 1 <= coins.length <= 12 1 <= coins[i] <= 231 - 1 0 <= amount <= 1041001Amazon,349,Intersection of Two Arrays,Easy,"Array, Hash Table, Two Pointers, Binary Search, Sorting",Given two integer arrays nums1 and nums2; return an array of their intersection. Each element in the result must be unique and you may return the result in any order. Example 1: Input: nums1 = [1;2;2;1]; nums2 = [2;2] Output: [2] Example 2: Input: nums1 = [4;9;5]; nums2 = [9;4;9;8;4] Output: [9;4] Explanation: [4;9] is also accepted. Constraints: 1 <= nums1.length; nums2.length <= 1000 0 <= nums1[i]; nums2[i] <= 10001002Amazon,394,Decode String,Med,"String, Stack, Recursion","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. Example 1: Input: s = ""3[a]2[bc]"" Output: ""aaabcbc"" Example 2: Input: s = ""3[a2[c]]"" Output: ""accaccacc"" Example 3: Input: s = ""2[abc]3[cd]ef"" Output: ""abcabccdcdcdef"" Constraints: 1 <= s.length <= 30 s consists of lowercase English letters; digits; and square brackets '[]'. s is guaranteed to be a valid input. All the integers in s are in the range [1; 300]."1003Amazon,733,Flood Fill,Easy,"Array, Depth-First Search, Breadth-First Search, Matrix",You are given an image represented by an m x n grid of integers image; where image[i][j] represents the pixel value of the image. You are also given three integers sr; sc; and color. Your task is to perform a flood fill on the image starting from the pixel image[sr][sc]. To perform a flood fill: Begin with the starting pixel and change its color to color. Perform the same process for each pixel that is directly adjacent (pixels that share a side with the original pixel; either horizontally or vertically) and shares the same color as the starting pixel. Keep repeating this process by checking neighboring pixels of the updated pixels and modifying their color if it matches the original color of the starting pixel. The process stops when there are no more adjacent pixels of the original color to update. Return the modified image after performing the flood fill. Example 1: Input: image = [[1;1;1];[1;1;0];[1;0;1]]; sr = 1; sc = 1; color = 2 Output: [[2;2;2];[2;2;0];[2;0;1]] Explanation: From the center of the image with position (sr; sc) = (1; 1) (i.e.; the red pixel); all pixels connected by a path of the same color as the starting pixel (i.e.; the blue pixels) are colored with the new color. Note the bottom corner is not colored 2; because it is not horizontally or vertically connected to the starting pixel. Example 2: Input: image = [[0;0;0];[0;0;0]]; sr = 0; sc = 0; color = 0 Output: [[0;0;0];[0;0;0]] Explanation: The starting pixel is already colored with 0; which is the same as the target color. Therefore; no changes are made to the image. Constraints: m == image.length n == image[i].length 1 <= m; n <= 50 0 <= image[i][j]; color < 216 0 <= sr < m 0 <= sc < n1004Amazon,1492,The kth Factor of n,Med,"Tree, Depth-First Search, Breadth-First Search",A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID. Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee; manager[headID] = -1. Also; it is guaranteed that the subordination relationships have a tree structure. The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates; and they will inform their subordinates; and so on until all employees know about the urgent news. The i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e.; After informTime[i] minutes; all his direct subordinates can start spreading the news). Return the number of minutes needed to inform all the employees about the urgent news. Example 1: Input: n = 1; headID = 0; manager = [-1]; informTime = [0] Output: 0 Explanation: The head of the company is the only employee in the company. Example 2: Input: n = 6; headID = 2; manager = [2;2;-1;2;2;2]; informTime = [0;0;1;0;0;0] Output: 1 Explanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all. The tree structure of the employees in the company is shown. Constraints: 1 <= n <= 105 0 <= headID < n manager.length == n 0 <= manager[i] < n manager[headID] == -1 informTime.length == n 0 <= informTime[i] <= 1000 informTime[i] == 0 if employee i has no subordinates. It is guaranteed that all the employees can be informed.1005Amazon,25,Reverse Nodes in k-Group,Hard,"Linked List, Recursion",Given the head of a linked list; reverse the nodes of the list k at a time; and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes; in the end; should remain as it is. You may not alter the values in the list's nodes; only nodes themselves may be changed. Example 1: Input: head = [1;2;3;4;5]; k = 2 Output: [2;1;4;3;5] Example 2: Input: head = [1;2;3;4;5]; k = 3 Output: [3;2;1;4;5] Constraints: The number of nodes in the list is n. 1 <= k <= n <= 5000 0 <= Node.val <= 1000 Follow-up: Can you solve the problem in O(1) extra memory space?1006Amazon,36,Valid Sudoku,Med,"Array, Hash Table, Matrix","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. Example 1: Input: board = [[""5"";""3"";""."";""."";""7"";""."";""."";""."";"".""] ;[""6"";""."";""."";""1"";""9"";""5"";""."";""."";"".""] ;[""."";""9"";""8"";""."";""."";""."";""."";""6"";"".""] ;[""8"";""."";""."";""."";""6"";""."";""."";""."";""3""] ;[""4"";""."";""."";""8"";""."";""3"";""."";""."";""1""] ;[""7"";""."";""."";""."";""2"";""."";""."";""."";""6""] ;[""."";""6"";""."";""."";""."";""."";""2"";""8"";"".""] ;[""."";""."";""."";""4"";""1"";""9"";""."";""."";""5""] ;[""."";""."";""."";""."";""8"";""."";""."";""7"";""9""]] Output: true Example 2: Input: board = [[""8"";""3"";""."";""."";""7"";""."";""."";""."";"".""] ;[""6"";""."";""."";""1"";""9"";""5"";""."";""."";"".""] ;[""."";""9"";""8"";""."";""."";""."";""."";""6"";"".""] ;[""8"";""."";""."";""."";""6"";""."";""."";""."";""3""] ;[""4"";""."";""."";""8"";""."";""3"";""."";""."";""1""] ;[""7"";""."";""."";""."";""2"";""."";""."";""."";""6""] ;[""."";""6"";""."";""."";""."";""."";""2"";""8"";"".""] ;[""."";""."";""."";""4"";""1"";""9"";""."";""."";""5""] ;[""."";""."";""."";""."";""8"";""."";""."";""7"";""9""]] Output: false Explanation: Same as Example 1; except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box; it is invalid. Constraints: board.length == 9 board[i].length == 9 board[i][j] is a digit 1-9 or '.'."1007Amazon,69,Sqrt(x),Easy,"Math, Binary Search",Given a non-negative integer x; return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well. You must not use any built-in exponent function or operator. For example; do not use pow(x; 0.5) in c++ or x ** 0.5 in python. Example 1: Input: x = 4 Output: 2 Explanation: The square root of 4 is 2; so we return 2. Example 2: Input: x = 8 Output: 2 Explanation: The square root of 8 is 2.82842...; and since we round it down to the nearest integer; 2 is returned. Constraints: 0 <= x <= 231 - 11008Amazon,126,Word Ladder II,Hard,"Hash Table, String, Backtracking, Breadth-First Search","A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Every adjacent pair of words differs by a single letter. Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. sk == endWord Given two words; beginWord and endWord; and a dictionary wordList; return all the shortest transformation sequences from beginWord to endWord; or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord; s1; s2; ...; sk]. Example 1: Input: beginWord = ""hit""; endWord = ""cog""; wordList = [""hot"";""dot"";""dog"";""lot"";""log"";""cog""] Output: [[""hit"";""hot"";""dot"";""dog"";""cog""];[""hit"";""hot"";""lot"";""log"";""cog""]] Explanation: There are 2 shortest transformation sequences: ""hit"" -> ""hot"" -> ""dot"" -> ""dog"" -> ""cog"" ""hit"" -> ""hot"" -> ""lot"" -> ""log"" -> ""cog"" Example 2: Input: beginWord = ""hit""; endWord = ""cog""; wordList = [""hot"";""dot"";""dog"";""lot"";""log""] Output: [] Explanation: The endWord ""cog"" is not in wordList; therefore there is no valid transformation sequence. Constraints: 1 <= beginWord.length <= 5 endWord.length == beginWord.length 1 <= wordList.length <= 500 wordList[i].length == beginWord.length beginWord; endWord; and wordList[i] consist of lowercase English letters. beginWord != endWord All the words in wordList are unique. The sum of all shortest transformation sequences does not exceed 105."1009Amazon,143,Reorder List,Med,"Linked List, Two Pointers, Stack, Recursion",You are given the head of a singly linked-list. The list can be represented as: L0 → L1 → … → Ln - 1 → Ln Reorder the list to be on the following form: L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … You may not modify the values in the list's nodes. Only nodes themselves may be changed. Example 1: Input: head = [1;2;3;4] Output: [1;4;2;3] Example 2: Input: head = [1;2;3;4;5] Output: [1;5;2;4;3] Constraints: The number of nodes in the list is in the range [1; 5 * 104]. 1 <= Node.val <= 10001010Amazon,169,Majority Element,Easy,"Array, Hash Table, Divide and Conquer, Sorting, Counting",Given an array nums of size n; return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. Example 1: Input: nums = [3;2;3] Output: 3 Example 2: Input: nums = [2;2;1;1;1;2;2] Output: 2 Constraints: n == nums.length 1 <= n <= 5 * 104 -109 <= nums[i] <= 109 Follow-up: Could you solve the problem in linear time and in O(1) space?1011Amazon,206,Reverse Linked List,Easy,"Linked List, Recursion",Given the head of a singly linked list; reverse the list; and return the reversed list. Example 1: Input: head = [1;2;3;4;5] Output: [5;4;3;2;1] Example 2: Input: head = [1;2] Output: [2;1] Example 3: Input: head = [] Output: [] Constraints: The number of nodes in the list is the range [0; 5000]. -5000 <= Node.val <= 5000 Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?1012Amazon,268,Missing Number,Easy,"Array, Hash Table, Math, Binary Search, Bit Manipulation, Sorting",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. Example 1: 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. Example 2: Input: nums = [0;1] Output: 2 Explanation: n = 2 since there are 2 numbers; so all numbers are in the range [0;2]. 2 is the missing number in the range since it does not appear in nums. Example 3: Input: nums = [9;6;4;2;3;5;7;0;1] Output: 8 Explanation: n = 9 since there are 9 numbers; so all numbers are in the range [0;9]. 8 is the missing number in the range since it does not appear in nums. Constraints: n == nums.length 1 <= n <= 104 0 <= nums[i] <= n All the numbers of nums are unique. Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?1013Amazon,450,Delete Node in a BST,Med,"Tree, Binary Search Tree, Binary Tree",Given a root node reference of a BST and a key; delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. Basically; the deletion can be divided into two stages: Search for a node to remove. If the node is found; delete the node. Example 1: Input: root = [5;3;6;2;4;null;7]; key = 3 Output: [5;4;6;2;null;null;7] Explanation: Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5;4;6;2;null;null;7]; shown in the above BST. Please notice that another valid answer is [5;2;6;null;4;null;7] and it's also accepted. Example 2: Input: root = [5;3;6;2;4;null;7]; key = 0 Output: [5;3;6;2;4;null;7] Explanation: The tree does not contain a node with value = 0. Example 3: Input: root = []; key = 0 Output: [] Constraints: The number of nodes in the tree is in the range [0; 104]. -105 <= Node.val <= 105 Each node has a unique value. root is a valid binary search tree. -105 <= key <= 105 Follow up: Could you solve it with time complexity O(height of tree)?1014Amazon,567,Permutation in String,Med,"Hash Table, Two Pointers, String, Sliding Window","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. Example 1: Input: s1 = ""ab""; s2 = ""eidbaooo"" Output: true Explanation: s2 contains one permutation of s1 (""ba""). Example 2: Input: s1 = ""ab""; s2 = ""eidboaoo"" Output: false Constraints: 1 <= s1.length; s2.length <= 104 s1 and s2 consist of lowercase English letters."1015Amazon,973,K Closest Points to Origin,Med,"String, Stack, Greedy, Queue","You are given two strings stamp and target. Initially; there is a string s of length target.length with all s[i] == '?'. In one turn; you can place stamp over s and replace every letter in the s with the corresponding letter from stamp. For example; if stamp = ""abc"" and target = ""abcba""; then s is ""?????"" initially. In one turn you can: place stamp at index 0 of s to obtain ""abc??""; place stamp at index 1 of s to obtain ""?abc?""; or place stamp at index 2 of s to obtain ""??abc"". Note that stamp must be fully contained in the boundaries of s in order to stamp (i.e.; you cannot place stamp at index 3 of s). We want to convert s to target using at most 10 * target.length turns. Return an array of the index of the left-most letter being stamped at each turn. If we cannot obtain target from s within 10 * target.length turns; return an empty array. Example 1: Input: stamp = ""abc""; target = ""ababc"" Output: [0;2] Explanation: Initially s = ""?????"". - Place stamp at index 0 to get ""abc??"". - Place stamp at index 2 to get ""ababc"". [1;0;2] would also be accepted as an answer; as well as some other answers. Example 2: Input: stamp = ""abca""; target = ""aabcaca"" Output: [3;0;1] Explanation: Initially s = ""???????"". - Place stamp at index 3 to get ""???abca"". - Place stamp at index 0 to get ""abcabca"". - Place stamp at index 1 to get ""aabcaca"". Constraints: 1 <= stamp.length <= target.length <= 1000 stamp and target consist of lowercase English letters."1016Amazon,1011,Capacity To Ship Packages Within D Days,Med,"Tree, Depth-First Search, Binary Tree",You are given the root of a binary tree with n nodes; where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage; which is the desired pre-order traversal of the binary tree. Any node in the binary tree can be flipped by swapping its left and right subtrees. For example; flipping node 1 will have the following effect: Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage. Return a list of the values of all flipped nodes. You may return the answer in any order. If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage; return the list [-1]. Example 1: Input: root = [1;2]; voyage = [2;1] Output: [-1] Explanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage. Example 2: Input: root = [1;2;3]; voyage = [1;3;2] Output: [1] Explanation: Flipping node 1 swaps nodes 2 and 3; so the pre-order traversal matches voyage. Example 3: Input: root = [1;2;3]; voyage = [1;2;3] Output: [] Explanation: The tree's pre-order traversal already matches voyage; so no nodes need to be flipped. Constraints: The number of nodes in the tree is n. n == voyage.length 1 <= n <= 100 1 <= Node.val; voyage[i] <= n All the values in the tree are unique. All the values in voyage are unique.1017Amazon,1268,Search Suggestions System,Med,Database,Table: Users +----------------+---------+ | Column Name | Type | +----------------+---------+ | user_id | int | | join_date | date | | favorite_brand | varchar | +----------------+---------+ user_id is the primary key (column with unique values) of this table. This table has the info of the users of an online shopping website where users can sell and buy items. Table: Orders +---------------+---------+ | Column Name | Type | +---------------+---------+ | order_id | int | | order_date | date | | item_id | int | | buyer_id | int | | seller_id | int | +---------------+---------+ order_id is the primary key (column with unique values) of this table. item_id is a foreign key (reference column) to the Items table. buyer_id and seller_id are foreign keys to the Users table. Table: Items +---------------+---------+ | Column Name | Type | +---------------+---------+ | item_id | int | | item_brand | varchar | +---------------+---------+ item_id is the primary key (column with unique values) of this table. Write a solution to find for each user; the join date and the number of orders they made as a buyer in 2019. Return the result table in any order. The result format is in the following example. Example 1: Input: Users table: +---------+------------+----------------+ | user_id | join_date | favorite_brand | +---------+------------+----------------+ | 1 | 2018-01-01 | Lenovo | | 2 | 2018-02-09 | Samsung | | 3 | 2018-01-19 | LG | | 4 | 2018-05-21 | HP | +---------+------------+----------------+ Orders table: +----------+------------+---------+----------+-----------+ | order_id | order_date | item_id | buyer_id | seller_id | +----------+------------+---------+----------+-----------+ | 1 | 2019-08-01 | 4 | 1 | 2 | | 2 | 2018-08-02 | 2 | 1 | 3 | | 3 | 2019-08-03 | 3 | 2 | 3 | | 4 | 2018-08-04 | 1 | 4 | 2 | | 5 | 2018-08-04 | 1 | 3 | 4 | | 6 | 2019-08-05 | 2 | 2 | 4 | +----------+------------+---------+----------+-----------+ Items table: +---------+------------+ | item_id | item_brand | +---------+------------+ | 1 | Samsung | | 2 | Lenovo | | 3 | LG | | 4 | HP | +---------+------------+ Output: +-----------+------------+----------------+ | buyer_id | join_date | orders_in_2019 | +-----------+------------+----------------+ | 1 | 2018-01-01 | 1 | | 2 | 2018-02-09 | 2 | | 3 | 2018-01-19 | 0 | | 4 | 2018-05-21 | 0 | +-----------+------------+----------------+1018Amazon,2055,Plates Between Candles,Med,"Array, Hash Table, Sorting, Prefix Sum",There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments; where segments[i] = [starti; endi; colori] represents the half-closed segment [starti; endi) with colori as the color. The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix; they form a new color that can be represented as a set of mixed colors. For example; if colors 2; 4; and 6 are mixed; then the resulting mixed color is {2;4;6}. For the sake of simplicity; you should only output the sum of the elements in the set rather than the full set. You want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [leftj; rightj; mixj] describes a half-closed segment [leftj; rightj) with the mixed color sum of mixj. For example; the painting created with segments = [[1;4;5];[1;7;7]] can be described by painting = [[1;4;12];[4;7;7]] because: [1;4) is colored {5;7} (with a sum of 12) from both the first and second segments. [4;7) is colored {7} from only the second segment. Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order. A half-closed segment [a; b) is the section of the number line between points a and b including point a and not including point b. Example 1: Input: segments = [[1;4;5];[4;7;7];[1;7;9]] Output: [[1;4;14];[4;7;16]] Explanation: The painting can be described as follows: - [1;4) is colored {5;9} (with a sum of 14) from the first and third segments. - [4;7) is colored {7;9} (with a sum of 16) from the second and third segments. Example 2: Input: segments = [[1;7;9];[6;8;15];[8;10;7]] Output: [[1;6;9];[6;7;24];[7;8;15];[8;10;7]] Explanation: The painting can be described as follows: - [1;6) is colored 9 from the first segment. - [6;7) is colored {9;15} (with a sum of 24) from the first and second segments. - [7;8) is colored 15 from the second segment. - [8;10) is colored 7 from the third segment. Example 3: Input: segments = [[1;4;5];[1;4;7];[4;7;1];[4;7;11]] Output: [[1;4;12];[4;7;12]] Explanation: The painting can be described as follows: - [1;4) is colored {5;7} (with a sum of 12) from the first and second segments. - [4;7) is colored {1;11} (with a sum of 12) from the third and fourth segments. Note that returning a single segment [1;7) is incorrect because the mixed color sets are different. Constraints: 1 <= segments.length <= 2 * 104 segments[i].length == 3 1 <= starti < endi <= 105 1 <= colori <= 109 Each colori is distinct.1019Amazon,31,Next Permutation,Med,"Array, Two Pointers",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 all the permutations of arr: [1;2;3]; [1;3;2]; [2; 1; 3]; [2; 3; 1]; [3;1;2]; [3;2;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. The replacement must be in place and use only constant extra memory. Example 1: Input: nums = [1;2;3] Output: [1;3;2] Example 2: Input: nums = [3;2;1] Output: [1;2;3] Example 3: Input: nums = [1;1;5] Output: [1;5;1] Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 1001020Amazon,34,Find First and Last Position of Element in Sorted Array,Med,"Array, Binary Search",Given an array of integers nums sorted in non-decreasing order; find the starting and ending position of a given target value. If target is not found in the array; return [-1; -1]. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [5;7;7;8;8;10]; target = 8 Output: [3;4] Example 2: Input: nums = [5;7;7;8;8;10]; target = 6 Output: [-1;-1] Example 3: Input: nums = []; target = 0 Output: [-1;-1] Constraints: 0 <= nums.length <= 105 -109 <= nums[i] <= 109 nums is a non-decreasing array. -109 <= target <= 1091021Amazon,41,First Missing Positive,Hard,"Array, Hash Table",Given an unsorted integer array nums. Return the smallest positive integer that is not present in nums. You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space. Example 1: Input: nums = [1;2;0] Output: 3 Explanation: The numbers in the range [1;2] are all in the array. Example 2: Input: nums = [3;4;-1;1] Output: 2 Explanation: 1 is in the array but 2 is missing. Example 3: Input: nums = [7;8;9;11;12] Output: 1 Explanation: The smallest positive integer 1 is missing. Constraints: 1 <= nums.length <= 105 -231 <= nums[i] <= 231 - 11022Amazon,48,Rotate Image,Med,"Array, Math, Matrix",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. Example 1: Input: matrix = [[1;2;3];[4;5;6];[7;8;9]] Output: [[7;4;1];[8;5;2];[9;6;3]] Example 2: Input: matrix = [[5;1;9;11];[2;4;8;10];[13;3;6;7];[15;14;12;16]] Output: [[15;13;2;5];[14;3;4;1];[12;6;8;9];[16;7;10;11]] Constraints: n == matrix.length == matrix[i].length 1 <= n <= 20 -1000 <= matrix[i][j] <= 10001023Amazon,50,"Pow(x, n)",Med,"Math, Recursion",Implement pow(x; n); which calculates x raised to the power n (i.e.; xn). Example 1: Input: x = 2.00000; n = 10 Output: 1024.00000 Example 2: Input: x = 2.10000; n = 3 Output: 9.26100 Example 3: Input: x = 2.00000; n = -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25 Constraints: -100.0 < x < 100.0 -231 <= n <= 231-1 n is an integer. Either x is not zero or n > 0. -104 <= xn <= 1041024Amazon,62,Unique Paths,Med,"Math, Dynamic Programming, Combinatorics",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. Example 1: Input: m = 3; n = 7 Output: 28 Example 2: Input: m = 3; n = 2 Output: 3 Explanation: From the top-left corner; there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down Constraints: 1 <= m; n <= 1001025Amazon,66,Plus One,Easy,"Array, Math",You are given a large integer represented as an integer array digits; where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. Increment the large integer by one and return the resulting array of digits. Example 1: Input: digits = [1;2;3] Output: [1;2;4] Explanation: The array represents the integer 123. Incrementing by one gives 123 + 1 = 124. Thus; the result should be [1;2;4]. Example 2: Input: digits = [4;3;2;1] Output: [4;3;2;2] Explanation: The array represents the integer 4321. Incrementing by one gives 4321 + 1 = 4322. Thus; the result should be [4;3;2;2]. Example 3: Input: digits = [9] Output: [1;0] Explanation: The array represents the integer 9. Incrementing by one gives 9 + 1 = 10. Thus; the result should be [1;0]. Constraints: 1 <= digits.length <= 100 0 <= digits[i] <= 9 digits does not contain any leading 0's.1026Amazon,74,Search a 2D Matrix,Med,"Array, Binary Search, Matrix",You are given an m x n integer matrix matrix with the following two properties: Each row is sorted in non-decreasing order. The first integer of each row is greater than the last integer of the previous row. Given an integer target; return true if target is in matrix or false otherwise. You must write a solution in O(log(m * n)) time complexity. Example 1: Input: matrix = [[1;3;5;7];[10;11;16;20];[23;30;34;60]]; target = 3 Output: true Example 2: Input: matrix = [[1;3;5;7];[10;11;16;20];[23;30;34;60]]; target = 13 Output: false Constraints: m == matrix.length n == matrix[i].length 1 <= m; n <= 100 -104 <= matrix[i][j]; target <= 1041027Amazon,100,Same Tree,Easy,"Tree, Depth-First Search, Breadth-First Search, Binary Tree",Given the roots of two binary trees p and q; write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical; and the nodes have the same value. Example 1: Input: p = [1;2;3]; q = [1;2;3] Output: true Example 2: Input: p = [1;2]; q = [1;null;2] Output: false Example 3: Input: p = [1;2;1]; q = [1;1;2] Output: false Constraints: The number of nodes in both trees is in the range [0; 100]. -104 <= Node.val <= 1041028Amazon,102,Binary Tree Level Order Traversal,Med,"Tree, Breadth-First Search, Binary Tree",Given the root of a binary tree; return the level order traversal of its nodes' values. (i.e.; from left to right; level by level). Example 1: Input: root = [3;9;20;null;null;15;7] Output: [[3];[9;20];[15;7]] Example 2: Input: root = [1] Output: [[1]] Example 3: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0; 2000]. -1000 <= Node.val <= 10001029Amazon,151,Reverse Words in a String,Med,"Two Pointers, 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. Example 1: Input: s = ""the sky is blue"" Output: ""blue is sky the"" Example 2: Input: s = "" hello world "" Output: ""world hello"" Explanation: Your reversed string should not contain leading or trailing spaces. Example 3: 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. Constraints: 1 <= s.length <= 104 s contains English letters (upper-case and lower-case); digits; and spaces ' '. There is at least one word in s. Follow-up: If the string data type is mutable in your language; can you solve it in-place with O(1) extra space?"1030Amazon,240,Search a 2D Matrix II,Med,"Array, Binary Search, Divide and Conquer, Matrix",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. Example 1: 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 Example 2: 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 = 20 Output: false Constraints: m == matrix.length n == matrix[i].length 1 <= n; m <= 300 -109 <= matrix[i][j] <= 109 All the integers in each row are sorted in ascending order. All the integers in each column are sorted in ascending order. -109 <= target <= 1091031Amazon,287,Find the Duplicate Number,Med,"Array, Two Pointers, Binary Search, Bit Manipulation",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 using only constant extra space. Example 1: Input: nums = [1;3;4;2;2] Output: 2 Example 2: Input: nums = [3;1;3;4;2] Output: 3 Example 3: Input: nums = [3;3;3;3;3] Output: 3 Constraints: 1 <= n <= 105 nums.length == n + 1 1 <= nums[i] <= n All the integers in nums appear only once except for precisely one integer which appears two or more times. Follow up: How can we prove that at least one duplicate number must exist in nums? Can you solve the problem in linear runtime complexity?1032Amazon,348,Design Tic-Tac-Toe,Med,"Array, Hash Table, Design, Matrix, Simulation",1033Amazon,437,Path Sum III,Med,"Tree, Depth-First Search, Binary Tree",Given the root of a binary tree and an integer targetSum; return the number of paths where the sum of the values along the path equals targetSum. The path does not need to start or end at the root or a leaf; but it must go downwards (i.e.; traveling only from parent nodes to child nodes). Example 1: Input: root = [10;5;-3;3;2;null;11;3;-2;null;1]; targetSum = 8 Output: 3 Explanation: The paths that sum to 8 are shown. Example 2: Input: root = [5;4;8;11;null;13;4;7;2;null;null;5;1]; targetSum = 22 Output: 3 Constraints: The number of nodes in the tree is in the range [0; 1000]. -109 <= Node.val <= 109 -1000 <= targetSum <= 10001034Amazon,443,String Compression,Med,"Two Pointers, String","Given an array of characters chars; compress it using the following algorithm: Begin with an empty string s. For each group of consecutive repeating characters in chars: If the group's length is 1; append the character to s. Otherwise; append the character followed by the group's length. The compressed string s should not be returned separately; but instead; be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars. After you are done modifying the input array; return the new length of the array. You must write an algorithm that uses only constant extra space. Example 1: Input: chars = [""a"";""a"";""b"";""b"";""c"";""c"";""c""] Output: Return 6; and the first 6 characters of the input array should be: [""a"";""2"";""b"";""2"";""c"";""3""] Explanation: The groups are ""aa""; ""bb""; and ""ccc"". This compresses to ""a2b2c3"". Example 2: Input: chars = [""a""] Output: Return 1; and the first character of the input array should be: [""a""] Explanation: The only group is ""a""; which remains uncompressed since it's a single character. Example 3: Input: chars = [""a"";""b"";""b"";""b"";""b"";""b"";""b"";""b"";""b"";""b"";""b"";""b"";""b""] Output: Return 4; and the first 4 characters of the input array should be: [""a"";""b"";""1"";""2""]. Explanation: The groups are ""a"" and ""bbbbbbbbbbbb"". This compresses to ""ab12"". Constraints: 1 <= chars.length <= 2000 chars[i] is a lowercase English letter; uppercase English letter; digit; or symbol."1035Amazon,460,LFU Cache,Hard,"Hash Table, Linked List, Design, Doubly-Linked List","Design and implement a data structure for a Least Frequently Used (LFU) cache. Implement the LFUCache class: LFUCache(int capacity) Initializes the object with the capacity of the data structure. int get(int key) Gets the value of the key if the key exists in the cache. Otherwise; returns -1. void put(int key; int value) Update the value of the key if present; or inserts the key if not already present. When the cache reaches its capacity; it should invalidate and remove the least frequently used key before inserting a new item. For this problem; when there is a tie (i.e.; two or more keys with the same frequency); the least recently used key would be invalidated. To determine the least frequently used key; a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key. When a key is first inserted into the cache; its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it. The functions get and put must each run in O(1) average time complexity. Example 1: Input [""LFUCache""; ""put""; ""put""; ""get""; ""put""; ""get""; ""get""; ""put""; ""get""; ""get""; ""get""] [[2]; [1; 1]; [2; 2]; [1]; [3; 3]; [2]; [3]; [4; 4]; [1]; [3]; [4]] Output [null; null; null; 1; null; -1; 3; null; -1; 3; 4] Explanation // cnt(x) = the use counter for key x // cache=[] will show the last used order for tiebreakers (leftmost element is most recent) LFUCache lfu = new LFUCache(2); lfu.put(1; 1); // cache=[1;_]; cnt(1)=1 lfu.put(2; 2); // cache=[2;1]; cnt(2)=1; cnt(1)=1 lfu.get(1); // return 1 // cache=[1;2]; cnt(2)=1; cnt(1)=2 lfu.put(3; 3); // 2 is the LFU key because cnt(2)=1 is the smallest; invalidate 2. // cache=[3;1]; cnt(3)=1; cnt(1)=2 lfu.get(2); // return -1 (not found) lfu.get(3); // return 3 // cache=[3;1]; cnt(3)=2; cnt(1)=2 lfu.put(4; 4); // Both 1 and 3 have the same cnt; but 1 is LRU; invalidate 1. // cache=[4;3]; cnt(4)=1; cnt(3)=2 lfu.get(1); // return -1 (not found) lfu.get(3); // return 3 // cache=[3;4]; cnt(4)=1; cnt(3)=3 lfu.get(4); // return 4 // cache=[4;3]; cnt(4)=2; cnt(3)=3 Constraints: 1 <= capacity <= 104 0 <= key <= 105 0 <= value <= 109 At most 2 * 105 calls will be made to get and put."1036Amazon,472,Concatenated Words,Hard,"Array, String, Dynamic Programming, Depth-First Search, Trie","Given an array of strings words (without duplicates); return all the concatenated words in the given list of words. A concatenated word is defined as a string that is comprised entirely of at least two shorter words (not necessarily distinct) in the given array. Example 1: Input: words = [""cat"";""cats"";""catsdogcats"";""dog"";""dogcatsdog"";""hippopotamuses"";""rat"";""ratcatdogcat""] Output: [""catsdogcats"";""dogcatsdog"";""ratcatdogcat""] Explanation: ""catsdogcats"" can be concatenated by ""cats""; ""dog"" and ""cats""; ""dogcatsdog"" can be concatenated by ""dog""; ""cats"" and ""dog""; ""ratcatdogcat"" can be concatenated by ""rat""; ""cat""; ""dog"" and ""cat"". Example 2: Input: words = [""cat"";""dog"";""catdog""] Output: [""catdog""] Constraints: 1 <= words.length <= 104 1 <= words[i].length <= 30 words[i] consists of only lowercase English letters. All the strings of words are unique. 1 <= sum(words[i].length) <= 105"1037Amazon,496,Next Greater Element I,Easy,"Array, Hash Table, Stack, Monotonic Stack",The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2; where nums1 is a subset of nums2. For each 0 <= i < nums1.length; find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element; then the answer for this query is -1. Return an array ans of length nums1.length such that ans[i] is the next greater element as described above. Example 1: Input: nums1 = [4;1;2]; nums2 = [1;3;4;2] Output: [-1;3;-1] Explanation: The next greater element for each value of nums1 is as follows: - 4 is underlined in nums2 = [1;3;4;2]. There is no next greater element; so the answer is -1. - 1 is underlined in nums2 = [1;3;4;2]. The next greater element is 3. - 2 is underlined in nums2 = [1;3;4;2]. There is no next greater element; so the answer is -1. Example 2: Input: nums1 = [2;4]; nums2 = [1;2;3;4] Output: [3;-1] Explanation: The next greater element for each value of nums1 is as follows: - 2 is underlined in nums2 = [1;2;3;4]. The next greater element is 3. - 4 is underlined in nums2 = [1;2;3;4]. There is no next greater element; so the answer is -1. Constraints: 1 <= nums1.length <= nums2.length <= 1000 0 <= nums1[i]; nums2[i] <= 104 All integers in nums1 and nums2 are unique. All the integers of nums1 also appear in nums2. Follow up: Could you find an O(nums1.length + nums2.length) solution?1038Amazon,588,Design In-Memory File System,Hard,"Hash Table, String, Design, Trie, Sorting",1039Amazon,632,Smallest Range Covering Elements from K Lists,Hard,"Array, Hash Table, Greedy, Sliding Window, Sorting, Heap (Priority Queue)",You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists. We define the range [a; b] is smaller than range [c; d] if b - a < d - c or a < c if b - a == d - c. Example 1: Input: nums = [[4;10;15;24;26];[0;9;12;20];[5;18;22;30]] Output: [20;24] Explanation: List 1: [4; 10; 15; 24;26]; 24 is in range [20;24]. List 2: [0; 9; 12; 20]; 20 is in range [20;24]. List 3: [5; 18; 22; 30]; 22 is in range [20;24]. Example 2: Input: nums = [[1;2;3];[1;2;3];[1;2;3]] Output: [1;1] Constraints: nums.length == k 1 <= k <= 3500 1 <= nums[i].length <= 50 -105 <= nums[i][j] <= 105 nums[i] is sorted in non-decreasing order.1040Amazon,509,Fibonacci Number,Easy,"Tree, Binary Search Tree, Binary Tree",1041Amazon,1233,Remove Sub-Folders from the Filesystem,Med,"Array, Divide and Conquer, Interactive",1042Amazon,35,Search Insert Position,Easy,"Array, Binary Search",Given a sorted array of distinct integers and a target value; return the index if the target is found. If not; return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [1;3;5;6]; target = 5 Output: 2 Example 2: Input: nums = [1;3;5;6]; target = 2 Output: 1 Example 3: Input: nums = [1;3;5;6]; target = 7 Output: 4 Constraints: 1 <= nums.length <= 104 -104 <= nums[i] <= 104 nums contains distinct values sorted in ascending order. -104 <= target <= 1041043Amazon,39,Combination Sum,Med,"Array, Backtracking",Given an array of distinct integers candidates and a target integer target; return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input. Example 1: Input: candidates = [2;3;6;7]; target = 7 Output: [[2;2;3];[7]] Explanation: 2 and 3 are candidates; and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate; and 7 = 7. These are the only two combinations. Example 2: Input: candidates = [2;3;5]; target = 8 Output: [[2;2;2;2];[2;3;3];[3;5]] Example 3: Input: candidates = [2]; target = 1 Output: [] Constraints: 1 <= candidates.length <= 30 2 <= candidates[i] <= 40 All elements of candidates are distinct. 1 <= target <= 401044Amazon,78,Subsets,Med,"Array, Backtracking, Bit Manipulation",Given an integer array nums of unique elements; return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. Example 1: Input: nums = [1;2;3] Output: [[];[1];[2];[1;2];[3];[1;3];[2;3];[1;2;3]] Example 2: Input: nums = [0] Output: [[];[0]] Constraints: 1 <= nums.length <= 10 -10 <= nums[i] <= 10 All the numbers of nums are unique.1045Amazon,92,Reverse Linked List II,Med,Linked List,Given the head of a singly linked list and two integers left and right where left <= right; reverse the nodes of the list from position left to position right; and return the reversed list. Example 1: Input: head = [1;2;3;4;5]; left = 2; right = 4 Output: [1;4;3;2;5] Example 2: Input: head = [5]; left = 1; right = 1 Output: [5] Constraints: The number of nodes in the list is n. 1 <= n <= 500 -500 <= Node.val <= 500 1 <= left <= right <= n Follow up: Could you do it in one pass?1046Amazon,103,Binary Tree Zigzag Level Order Traversal,Med,"Tree, Breadth-First Search, Binary Tree",Given the root of a binary tree; return the zigzag level order traversal of its nodes' values. (i.e.; from left to right; then right to left for the next level and alternate between). Example 1: Input: root = [3;9;20;null;null;15;7] Output: [[3];[20;9];[15;7]] Example 2: Input: root = [1] Output: [[1]] Example 3: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0; 2000]. -100 <= Node.val <= 1001047Amazon,118,Pascal's Triangle,Easy,"Array, Dynamic Programming",Given an integer numRows; return the first numRows of Pascal's triangle. In Pascal's triangle; each number is the sum of the two numbers directly above it as shown: Example 1: Input: numRows = 5 Output: [[1];[1;1];[1;2;1];[1;3;3;1];[1;4;6;4;1]] Example 2: Input: numRows = 1 Output: [[1]] Constraints: 1 <= numRows <= 301048Amazon,125,Valid Palindrome,Easy,"Two Pointers, String","A phrase is a palindrome if; after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters; it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s; return true if it is a palindrome; or false otherwise. Example 1: Input: s = ""A man; a plan; a canal: Panama"" Output: true Explanation: ""amanaplanacanalpanama"" is a palindrome. Example 2: Input: s = ""race a car"" Output: false Explanation: ""raceacar"" is not a palindrome. Example 3: Input: s = "" "" Output: true Explanation: s is an empty string """" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward; it is a palindrome. Constraints: 1 <= s.length <= 2 * 105 s consists only of printable ASCII characters."1049Amazon,150,Evaluate Reverse Polish Notation,Med,"Array, Math, Stack","You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation. Evaluate the expression. Return an integer that represents the value of the expression. Note that: The valid operators are '+'; '-'; '*'; and '/'. Each operand may be an integer or another expression. The division between two integers always truncates toward zero. There will not be any division by zero. The input represents a valid arithmetic expression in a reverse polish notation. The answer and all the intermediate calculations can be represented in a 32-bit integer. Example 1: Input: tokens = [""2"";""1"";""+"";""3"";""*""] Output: 9 Explanation: ((2 + 1) * 3) = 9 Example 2: Input: tokens = [""4"";""13"";""5"";""/"";""+""] Output: 6 Explanation: (4 + (13 / 5)) = 6 Example 3: Input: tokens = [""10"";""6"";""9"";""3"";""+"";""-11"";""*"";""/"";""*"";""17"";""+"";""5"";""+""] Output: 22 Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) + 17) + 5 = ((10 * (6 / -132)) + 17) + 5 = ((10 * 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22 Constraints: 1 <= tokens.length <= 104 tokens[i] is either an operator: ""+""; ""-""; ""*""; or ""/""; or an integer in the range [-200; 200]."1050Amazon,152,Maximum Product Subarray,Med,"Array, Dynamic Programming",Given an integer array nums; find a subarray that has the largest product; and return the product. The test cases are generated so that the answer will fit in a 32-bit integer. Example 1: Input: nums = [2;3;-2;4] Output: 6 Explanation: [2;3] has the largest product 6. Example 2: Input: nums = [-2;0;-1] Output: 0 Explanation: The result cannot be 2; because [-2;-1] is not a subarray. Constraints: 1 <= nums.length <= 2 * 104 -10 <= nums[i] <= 10 The product of any subarray of nums is guaranteed to fit in a 32-bit integer.1051Amazon,208,Implement Trie (Prefix Tree),Med,"Hash Table, String, Design, Trie","A trie (pronounced as ""try"") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure; such as autocomplete and spellchecker. Implement the Trie class: Trie() Initializes the trie object. void insert(String word) Inserts the string word into the trie. boolean search(String word) Returns true if the string word is in the trie (i.e.; was inserted before); and false otherwise. boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix; and false otherwise. Example 1: Input [""Trie""; ""insert""; ""search""; ""search""; ""startsWith""; ""insert""; ""search""] [[]; [""apple""]; [""apple""]; [""app""]; [""app""]; [""app""]; [""app""]] Output [null; null; true; false; true; null; true] Explanation Trie trie = new Trie(); trie.insert(""apple""); trie.search(""apple""); // return True trie.search(""app""); // return False trie.startsWith(""app""); // return True trie.insert(""app""); trie.search(""app""); // return True Constraints: 1 <= word.length; prefix.length <= 2000 word and prefix consist only of lowercase English letters. At most 3 * 104 calls in total will be made to insert; search; and startsWith."1052Amazon,219,Contains Duplicate II,Easy,"Array, Hash Table, Sliding Window",Given an integer array nums and an integer k; return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k. Example 1: Input: nums = [1;2;3;1]; k = 3 Output: true Example 2: Input: nums = [1;0;1;1]; k = 1 Output: true Example 3: Input: nums = [1;2;3;1;2;3]; k = 2 Output: false Constraints: 1 <= nums.length <= 105 -109 <= nums[i] <= 109 0 <= k <= 1051053Amazon,221,Maximal Square,Med,"Array, Dynamic Programming, Matrix","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. Example 1: Input: matrix = [[""1"";""0"";""1"";""0"";""0""];[""1"";""0"";""1"";""1"";""1""];[""1"";""1"";""1"";""1"";""1""];[""1"";""0"";""0"";""1"";""0""]] Output: 4 Example 2: Input: matrix = [[""0"";""1""];[""1"";""0""]] Output: 1 Example 3: Input: matrix = [[""0""]] Output: 0 Constraints: m == matrix.length n == matrix[i].length 1 <= m; n <= 300 matrix[i][j] is '0' or '1'."1054Amazon,241,Different Ways to Add Parentheses,Med,"Math, String, Dynamic Programming, Recursion, Memoization","Given a string expression of numbers and operators; return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order. The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 104. Example 1: Input: expression = ""2-1-1"" Output: [0;2] Explanation: ((2-1)-1) = 0 (2-(1-1)) = 2 Example 2: Input: expression = ""2*3-4*5"" Output: [-34;-14;-10;-10;10] Explanation: (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 Constraints: 1 <= expression.length <= 20 expression consists of digits and the operator '+'; '-'; and '*'. All the integer values in the input expression are in the range [0; 99]. The integer values in the input expression do not have a leading '-' or '+' denoting the sign."1055Amazon,269,Alien Dictionary,Hard,"Array, String, Depth-First Search, Breadth-First Search, Graph, Topological Sort",1056Amazon,485,Max Consecutive Ones,Easy,Array,Given a binary array nums; return the maximum number of consecutive 1's in the array. Example 1: Input: nums = [1;1;0;1;1;1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. Example 2: Input: nums = [1;0;1;1;0;1] Output: 2 Constraints: 1 <= nums.length <= 105 nums[i] is either 0 or 1.1057Amazon,584,Find Customer Referee,Easy,Database,Table: Customer +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | | referee_id | int | +-------------+---------+ In SQL; id is the primary key column for this table. Each row of this table indicates the id of a customer; their name; and the id of the customer who referred them. Find the names of the customer that are not referred by the customer with id = 2. Return the result table in any order. The result format is in the following example. Example 1: Input: Customer table: +----+------+------------+ | id | name | referee_id | +----+------+------------+ | 1 | Will | null | | 2 | Jane | null | | 3 | Alex | 2 | | 4 | Bill | null | | 5 | Zack | 1 | | 6 | Mark | 2 | +----+------+------------+ Output: +------+ | name | +------+ | Will | | Jane | | Bill | | Zack | +------+1058Amazon,735,Asteroid Collision,Med,"Array, Stack, Simulation",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. Example 1: Input: asteroids = [5;10;-5] Output: [5;10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide. Example 2: Input: asteroids = [8;-8] Output: [] Explanation: The 8 and -8 collide exploding each other. Example 3: Input: asteroids = [10;2;-5] Output: [10] Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. Constraints: 2 <= asteroids.length <= 104 -1000 <= asteroids[i] <= 1000 asteroids[i] != 01059Amazon,746,Min Cost Climbing Stairs,Easy,"Array, Hash Table, String, Design, Trie","Design a special dictionary that searches the words in it by a prefix and a suffix. Implement the WordFilter class: WordFilter(string[] words) Initializes the object with the words in the dictionary. f(string pref; string suff) Returns the index of the word in the dictionary; which has the prefix pref and the suffix suff. If there is more than one valid index; return the largest of them. If there is no such word in the dictionary; return -1. Example 1: Input [""WordFilter""; ""f""] [[[""apple""]]; [""a""; ""e""]] Output [null; 0] Explanation WordFilter wordFilter = new WordFilter([""apple""]); wordFilter.f(""a""; ""e""); // return 0; because the word at index 0 has prefix = ""a"" and suffix = ""e"". Constraints: 1 <= words.length <= 104 1 <= words[i].length <= 7 1 <= pref.length; suff.length <= 7 words[i]; pref and suff consist of lowercase English letters only. At most 104 calls will be made to the function f."1060Amazon,428,Serialize and Deserialize N-ary Tree,Hard,,1061Amazon,796,Rotate String,Easy,Math,Given four integers sx; sy; tx; and ty; return true if it is possible to convert the point (sx; sy) to the point (tx; ty) through some operations; or false otherwise. The allowed operation on some point (x; y) is to convert it to either (x; x + y) or (x + y; y). Example 1: Input: sx = 1; sy = 1; tx = 3; ty = 5 Output: true Explanation: One series of moves that transforms the starting point to the target is: (1; 1) -> (1; 2) (1; 2) -> (3; 2) (3; 2) -> (3; 5) Example 2: Input: sx = 1; sy = 1; tx = 2; ty = 2 Output: false Example 3: Input: sx = 1; sy = 1; tx = 1; ty = 1 Output: true Constraints: 1 <= sx; sy; tx; ty <= 1091062Amazon,706,Design HashMap,Easy,,1063Amazon,912,Sort an Array,Med,"Array, Math, Binary Search, Prefix Sum, Randomized","You are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index. You need to implement the function pickIndex(); which randomly picks an index in the range [0; w.length - 1] (inclusive) and returns it. The probability of picking an index i is w[i] / sum(w). For example; if w = [1; 3]; the probability of picking index 0 is 1 / (1 + 3) = 0.25 (i.e.; 25%); and the probability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e.; 75%). Example 1: Input [""Solution"";""pickIndex""] [[[1]];[]] Output [null;0] Explanation Solution solution = new Solution([1]); solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. Example 2: Input [""Solution"";""pickIndex"";""pickIndex"";""pickIndex"";""pickIndex"";""pickIndex""] [[[1;3]];[];[];[];[];[]] Output [null;1;1;1;1;0] Explanation Solution solution = new Solution([1; 3]); solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. Since this is a randomization problem; multiple answers are allowed. All of the following outputs can be considered correct: [null;1;1;1;1;0] [null;1;1;1;1;1] [null;1;1;1;0;0] [null;1;1;1;0;1] [null;1;0;1;0;0] ...... and so on. Constraints: 1 <= w.length <= 104 1 <= w[i] <= 105 pickIndex will be called at most 104 times."1064Amazon,921,Minimum Add to Make Parentheses Valid,Med,"Array, Matrix, Simulation",You start at the cell (rStart; cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid; and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary; we continue our walk outside the grid (but may return to the grid boundary later.). Eventually; we reach all rows * cols spaces of the grid. Return an array of coordinates representing the positions of the grid in the order you visited them. Example 1: Input: rows = 1; cols = 4; rStart = 0; cStart = 0 Output: [[0;0];[0;1];[0;2];[0;3]] Example 2: Input: rows = 5; cols = 6; rStart = 1; cStart = 4 Output: [[1;4];[1;5];[2;5];[2;4];[2;3];[1;3];[0;3];[0;4];[0;5];[3;5];[3;4];[3;3];[3;2];[2;2];[1;2];[0;2];[4;5];[4;4];[4;3];[4;2];[4;1];[3;1];[2;1];[1;1];[0;1];[4;0];[3;0];[2;0];[1;0];[0;0]] Constraints: 1 <= rows; cols <= 100 0 <= rStart < rows 0 <= cStart < cols1065Amazon,981,Time Based Key-Value Store,Med,"Array, String","You are given an array of n strings strs; all of the same length. The strings can be arranged such that there is one on each line; making a grid. For example; strs = [""abc""; ""bce""; ""cae""] can be arranged as follows: abc bce cae You want to delete the columns that are not sorted lexicographically. In the above example (0-indexed); columns 0 ('a'; 'b'; 'c') and 2 ('c'; 'e'; 'e') are sorted; while column 1 ('b'; 'c'; 'a') is not; so you would delete column 1. Return the number of columns that you will delete. Example 1: Input: strs = [""cba"";""daf"";""ghi""] Output: 1 Explanation: The grid looks as follows: cba daf ghi Columns 0 and 2 are sorted; but column 1 is not; so you only need to delete 1 column. Example 2: Input: strs = [""a"";""b""] Output: 0 Explanation: The grid looks as follows: a b Column 0 is the only column and is sorted; so you will not delete any columns. Example 3: Input: strs = [""zyx"";""wvu"";""tsr""] Output: 3 Explanation: The grid looks as follows: zyx wvu tsr All 3 columns are not sorted; so you will delete all 3. Constraints: n == strs.length 1 <= n <= 100 1 <= strs[i].length <= 1000 strs[i] consists of lowercase English letters."1066Amazon,1071,Greatest Common Divisor of Strings,Easy,"Array, Bit Manipulation",You are given a binary array nums (0-indexed). We define xi as the number whose binary representation is the subarray nums[0..i] (from most-significant-bit to least-significant-bit). For example; if nums = [1;0;1]; then x0 = 1; x1 = 2; and x2 = 5. Return an array of booleans answer where answer[i] is true if xi is divisible by 5. Example 1: Input: nums = [0;1;1] Output: [true;false;false] Explanation: The input numbers in binary are 0; 01; 011; which are 0; 1; and 3 in base-10. Only the first number is divisible by 5; so answer[0] is true. Example 2: Input: nums = [1;1;1] Output: [false;false;false] Constraints: 1 <= nums.length <= 105 nums[i] is either 0 or 1.1067Amazon,1405,Longest Happy String,Med,Database,1068Amazon,1193,Monthly Transactions I,Med,Database,1069Amazon,1431,Kids With the Greatest Number of Candies,Easy,"Depth-First Search, Breadth-First Search, Graph, Topological Sort",You are given a positive integer n representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1 (inclusive). You are also given a 2D integer array edges; where edges[i] = [fromi; toi] denotes that there is a unidirectional edge from fromi to toi in the graph. Return a list answer; where answer[i] is the list of ancestors of the ith node; sorted in ascending order. A node u is an ancestor of another node v if u can reach v via a set of edges. Example 1: Input: n = 8; edgeList = [[0;3];[0;4];[1;3];[2;4];[2;7];[3;5];[3;6];[3;7];[4;6]] Output: [[];[];[];[0;1];[0;2];[0;1;3];[0;1;2;3;4];[0;1;2;3]] Explanation: The above diagram represents the input graph. - Nodes 0; 1; and 2 do not have any ancestors. - Node 3 has two ancestors 0 and 1. - Node 4 has two ancestors 0 and 2. - Node 5 has three ancestors 0; 1; and 3. - Node 6 has five ancestors 0; 1; 2; 3; and 4. - Node 7 has four ancestors 0; 1; 2; and 3. Example 2: Input: n = 5; edgeList = [[0;1];[0;2];[0;3];[0;4];[1;2];[1;3];[1;4];[2;3];[2;4];[3;4]] Output: [[];[0];[0;1];[0;1;2];[0;1;2;3]] Explanation: The above diagram represents the input graph. - Node 0 does not have any ancestor. - Node 1 has one ancestor 0. - Node 2 has two ancestors 0 and 1. - Node 3 has three ancestors 0; 1; and 2. - Node 4 has four ancestors 0; 1; 2; and 3. Constraints: 1 <= n <= 1000 0 <= edges.length <= min(2000; n * (n - 1) / 2) edges[i].length == 2 0 <= fromi; toi <= n - 1 fromi != toi There are no duplicate edges. The graph is directed and acyclic.1070Amazon,1438,Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit,Med,Database,1071Amazon,1942,The Number of the Smallest Unoccupied Chair,Med,Database,Table: Employee +---------------+---------+ | Column Name | Type | +---------------+---------+ | employee_id | int | | department_id | int | | primary_flag | varchar | +---------------+---------+ (employee_id; department_id) is the primary key (combination of columns with unique values) for this table. employee_id is the id of the employee. department_id is the id of the department to which the employee belongs. primary_flag is an ENUM (category) of type ('Y'; 'N'). If the flag is 'Y'; the department is the primary department for the employee. If the flag is 'N'; the department is not the primary. Employees can belong to multiple departments. When the employee joins other departments; they need to decide which department is their primary department. Note that when an employee belongs to only one department; their primary column is 'N'. Write a solution to report all the employees with their primary department. For employees who belong to one department; report their only department. Return the result table in any order. The result format is in the following example. Example 1: Input: Employee table: +-------------+---------------+--------------+ | employee_id | department_id | primary_flag | +-------------+---------------+--------------+ | 1 | 1 | N | | 2 | 1 | Y | | 2 | 2 | N | | 3 | 3 | N | | 4 | 2 | N | | 4 | 3 | Y | | 4 | 4 | N | +-------------+---------------+--------------+ Output: +-------------+---------------+ | employee_id | department_id | +-------------+---------------+ | 1 | 1 | | 2 | 1 | | 3 | 3 | | 4 | 3 | +-------------+---------------+ Explanation: - The Primary department for employee 1 is 1. - The Primary department for employee 2 is 1. - The Primary department for employee 3 is 3. - The Primary department for employee 4 is 3.1072Amazon,2416,Sum of Prefix Scores of Strings,Hard,"Tree, Depth-First Search, Binary Tree",You are given the root of a full binary tree with the following properties: Leaf nodes have either the value 0 or 1; where 0 represents False and 1 represents True. Non-leaf nodes have either the value 2 or 3; where 2 represents the boolean OR and 3 represents the boolean AND. The evaluation of a node is as follows: If the node is a leaf node; the evaluation is the value of the node; i.e. True or False. Otherwise; evaluate the node's two children and apply the boolean operation of its value with the children's evaluations. Return the boolean result of evaluating the root node. A full binary tree is a binary tree where each node has either 0 or 2 children. A leaf node is a node that has zero children. Example 1: Input: root = [2;1;3;null;null;0;1] Output: true Explanation: The above diagram illustrates the evaluation process. The AND node evaluates to False AND True = False. The OR node evaluates to True OR False = True. The root node evaluates to True; so we return true. Example 2: Input: root = [0] Output: false Explanation: The root node is a leaf node and it evaluates to false; so we return false. Constraints: The number of nodes in the tree is in the range [1; 1000]. 0 <= Node.val <= 3 Every node has either 0 or 2 children. Leaf nodes have a value of 0 or 1. Non-leaf nodes have a value of 2 or 3.1073Amazon,2877,Create a DataFrame from List,Easy,"String, Greedy, Enumeration","Given three strings a; b; and c; your task is to find a string that has the minimum length and contains all three strings as substrings. If there are multiple such strings; return the lexicographically smallest one. Return a string denoting the answer to the problem. Notes A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ; string a has a letter that appears earlier in the alphabet than the corresponding letter in b. A substring is a contiguous sequence of characters within a string. Example 1: Input: a = ""abc""; b = ""bca""; c = ""aaa"" Output: ""aaabca"" Explanation: We show that ""aaabca"" contains all the given strings: a = ans[2...4]; b = ans[3..5]; c = ans[0..2]. It can be shown that the length of the resulting string would be at least 6 and ""aaabca"" is the lexicographically smallest one. Example 2: Input: a = ""ab""; b = ""ba""; c = ""aba"" Output: ""aba"" Explanation: We show that the string ""aba"" contains all the given strings: a = ans[0..1]; b = ans[1..2]; c = ans[0..2]. Since the length of c is 3; the length of the resulting string would be at least 3. It can be shown that ""aba"" is the lexicographically smallest one. Constraints: 1 <= a.length; b.length; c.length <= 100 a; b; c consist only of lowercase English letters."1074Amazon,18,4Sum,Med,"Array, Two Pointers, Sorting",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. Example 1: Input: nums = [1;0;-1;0;-2;2]; target = 0 Output: [[-2;-1;1;2];[-2;0;0;2];[-1;0;0;1]] Example 2: Input: nums = [2;2;2;2;2]; target = 8 Output: [[2;2;2;2]] Constraints: 1 <= nums.length <= 200 -109 <= nums[i] <= 109 -109 <= target <= 1091075Amazon,28,Find the Index of the First Occurrence in a String,Easy,"Two Pointers, String, String Matching","Given two strings needle and haystack; return the index of the first occurrence of needle in haystack; or -1 if needle is not part of haystack. Example 1: Input: haystack = ""sadbutsad""; needle = ""sad"" Output: 0 Explanation: ""sad"" occurs at index 0 and 6. The first occurrence is at index 0; so we return 0. Example 2: Input: haystack = ""leetcode""; needle = ""leeto"" Output: -1 Explanation: ""leeto"" did not occur in ""leetcode""; so we return -1. Constraints: 1 <= haystack.length; needle.length <= 104 haystack and needle consist of only lowercase English characters."1076Amazon,29,Divide Two Integers,Med,"Math, Bit Manipulation",Given two integers dividend and divisor; divide two integers without using multiplication; division; and mod operator. The integer division should truncate toward zero; which means losing its fractional part. For example; 8.345 would be truncated to 8; and -2.7335 would be truncated to -2. Return the quotient after dividing dividend by divisor. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231; 231 − 1]. For this problem; if the quotient is strictly greater than 231 - 1; then return 231 - 1; and if the quotient is strictly less than -231; then return -231. Example 1: Input: dividend = 10; divisor = 3 Output: 3 Explanation: 10/3 = 3.33333.. which is truncated to 3. Example 2: Input: dividend = 7; divisor = -3 Output: -2 Explanation: 7/-3 = -2.33333.. which is truncated to -2. Constraints: -231 <= dividend; divisor <= 231 - 1 divisor != 01077Amazon,32,Longest Valid Parentheses,Hard,"String, Dynamic Programming, Stack","Given a string containing just the characters '(' and ')'; return the length of the longest valid (well-formed) parentheses substring. Example 1: Input: s = ""(()"" Output: 2 Explanation: The longest valid parentheses substring is ""()"". Example 2: Input: s = "")()())"" Output: 4 Explanation: The longest valid parentheses substring is ""()()"". Example 3: Input: s = """" Output: 0 Constraints: 0 <= s.length <= 3 * 104 s[i] is '('; or ')'."1078Amazon,51,N-Queens,Hard,"Array, Backtracking","The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n; return all distinct solutions to the n-queens puzzle. You may return the answer in any order. Each solution contains a distinct board configuration of the n-queens' placement; where 'Q' and '.' both indicate a queen and an empty space; respectively. Example 1: Input: n = 4 Output: [["".Q.."";""...Q"";""Q..."";""..Q.""];[""..Q."";""Q..."";""...Q"";"".Q..""]] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above Example 2: Input: n = 1 Output: [[""Q""]] Constraints: 1 <= n <= 9"1079Amazon,75,Sort Colors,Med,"Array, Two Pointers, Sorting",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. Example 1: Input: nums = [2;0;2;1;1;0] Output: [0;0;1;1;2;2] Example 2: Input: nums = [2;0;1] Output: [0;1;2] Constraints: n == nums.length 1 <= n <= 300 nums[i] is either 0; 1; or 2. Follow up: Could you come up with a one-pass algorithm using only constant extra space?1080Amazon,81,Search in Rotated Sorted Array II,Med,"Array, Binary Search",There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function; nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k]; nums[k+1]; ...; nums[n-1]; nums[0]; nums[1]; ...; nums[k-1]] (0-indexed). For example; [0;1;2;4;4;4;5;6;6;7] might be rotated at pivot index 5 and become [4;5;6;6;7;0;1;2;4;4]. Given the array nums after the rotation and an integer target; return true if target is in nums; or false if it is not in nums. You must decrease the overall operation steps as much as possible. Example 1: Input: nums = [2;5;6;0;0;1;2]; target = 0 Output: true Example 2: Input: nums = [2;5;6;0;0;1;2]; target = 3 Output: false Constraints: 1 <= nums.length <= 5000 -104 <= nums[i] <= 104 nums is guaranteed to be rotated at some pivot. -104 <= target <= 104 Follow up: This problem is similar to Search in Rotated Sorted Array; but nums may contain duplicates. Would this affect the runtime complexity? How and why?1081Amazon,91,Decode Ways,Med,"String, Dynamic Programming","You have intercepted a secret message encoded as a string of numbers. The message is decoded via the following mapping: ""1"" -> 'A' ""2"" -> 'B' ... ""25"" -> 'Y' ""26"" -> 'Z' However; while decoding the message; you realize that there are many different ways you can decode the message because some codes are contained in other codes (""2"" and ""5"" vs ""25""). For example; ""11106"" can be decoded into: ""AAJF"" with the grouping (1; 1; 10; 6) ""KJF"" with the grouping (11; 10; 6) The grouping (1; 11; 06) is invalid because ""06"" is not a valid code (only ""6"" is valid). Note: there may be strings that are impossible to decode. Given a string s containing only digits; return the number of ways to decode it. If the entire string cannot be decoded in any valid way; return 0. The test cases are generated so that the answer fits in a 32-bit integer. Example 1: Input: s = ""12"" Output: 2 Explanation: ""12"" could be decoded as ""AB"" (1 2) or ""L"" (12). Example 2: Input: s = ""226"" Output: 3 Explanation: ""226"" could be decoded as ""BZ"" (2 26); ""VF"" (22 6); or ""BBF"" (2 2 6). Example 3: Input: s = ""06"" Output: 0 Explanation: ""06"" cannot be mapped to ""F"" because of the leading zero (""6"" is different from ""06""). In this case; the string is not a valid encoding; so return 0. Constraints: 1 <= s.length <= 100 s contains only digits and may contain leading zero(s)."1082Amazon,130,Surrounded Regions,Med,"Array, Depth-First Search, Breadth-First Search, Union Find, Matrix","You are given an m x n matrix board containing letters 'X' and 'O'; capture regions that are surrounded: Connect: A cell is connected to adjacent cells horizontally or vertically. Region: To form a region connect every 'O' cell. Surround: The region is surrounded with 'X' cells if you can connect the region with 'X' cells and none of the region cells are on the edge of the board. A surrounded region is captured by replacing all 'O's with 'X's in the input matrix board. Example 1: Input: 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""]] Explanation: In the above diagram; the bottom region is not captured because it is on the edge of the board and cannot be surrounded. Example 2: Input: board = [[""X""]] Output: [[""X""]] Constraints: m == board.length n == board[i].length 1 <= m; n <= 200 board[i][j] is 'X' or 'O'."1083Amazon,136,Single Number,Easy,"Array, Bit Manipulation",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. Example 1: Input: nums = [2;2;1] Output: 1 Example 2: Input: nums = [4;1;2;1;2] Output: 4 Example 3: Input: nums = [1] Output: 1 Constraints: 1 <= nums.length <= 3 * 104 -3 * 104 <= nums[i] <= 3 * 104 Each element in the array appears twice except for one element which appears only once.1084Amazon,145,Binary Tree Postorder Traversal,Easy,"Stack, Tree, Depth-First Search, Binary Tree",Given the root of a binary tree; return the postorder traversal of its nodes' values. Example 1: Input: root = [1;null;2;3] Output: [3;2;1] Explanation: Example 2: Input: root = [1;2;3;4;5;null;8;null;null;6;7;9] Output: [4;6;7;5;2;9;8;3;1] Explanation: Example 3: Input: root = [] Output: [] Example 4: Input: root = [1] Output: [1] Constraints: The number of the nodes in the tree is in the range [0; 100]. -100 <= Node.val <= 100 Follow up: Recursive solution is trivial; could you do it iteratively?1085Amazon,165,Compare Version Numbers,Med,"Two Pointers, String","Given two version strings; version1 and version2; compare them. A version string consists of revisions separated by dots '.'. The value of the revision is its integer conversion ignoring leading zeros. To compare version strings; compare their revision values in left-to-right order. If one of the version strings has fewer revisions; treat the missing revision values as 0. Return the following: If version1 < version2; return -1. If version1 > version2; return 1. Otherwise; return 0. Example 1: Input: version1 = ""1.2""; version2 = ""1.10"" Output: -1 Explanation: version1's second revision is ""2"" and version2's second revision is ""10"": 2 < 10; so version1 < version2. Example 2: Input: version1 = ""1.01""; version2 = ""1.001"" Output: 0 Explanation: Ignoring leading zeroes; both ""01"" and ""001"" represent the same integer ""1"". Example 3: Input: version1 = ""1.0""; version2 = ""1.0.0.0"" Output: 0 Explanation: version1 has less revisions; which means every missing revision are treated as ""0"". Constraints: 1 <= version1.length; version2.length <= 500 version1 and version2 only contain digits and '.'. version1 and version2 are valid version numbers. All the given revisions in version1 and version2 can be stored in a 32-bit integer."1086Amazon,176,Second Highest Salary,Med,Database,Table: Employee +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | salary | int | +-------------+------+ id is the primary key (column with unique values) for this table. Each row of this table contains information about the salary of an employee. Write a solution to find the second highest distinct salary from the Employee table. If there is no second highest salary; return null (return None in Pandas). The result format is in the following example. Example 1: Input: Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+ Output: +---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+ Example 2: Input: Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | +----+--------+ Output: +---------------------+ | SecondHighestSalary | +---------------------+ | null | +---------------------+1087Amazon,202,Happy Number,Easy,"Hash Table, Math, Two Pointers",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. Example 1: Input: n = 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 Example 2: Input: n = 2 Output: false Constraints: 1 <= n <= 231 - 11088Amazon,205,Isomorphic Strings,Easy,"Hash Table, String","Given two strings s and t; determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character; but a character may map to itself. Example 1: Input: s = ""egg""; t = ""add"" Output: true Explanation: The strings s and t can be made identical by: Mapping 'e' to 'a'. Mapping 'g' to 'd'. Example 2: Input: s = ""foo""; t = ""bar"" Output: false Explanation: The strings s and t can not be made identical as 'o' needs to be mapped to both 'a' and 'r'. Example 3: Input: s = ""paper""; t = ""title"" Output: true Constraints: 1 <= s.length <= 5 * 104 t.length == s.length s and t consist of any valid ascii character."1089Amazon,217,Contains Duplicate,Easy,"Array, Hash Table, Sorting",Given an integer array nums; return true if any value appears at least twice in the array; and return false if every element is distinct. Example 1: Input: nums = [1;2;3;1] Output: true Explanation: The element 1 occurs at the indices 0 and 3. Example 2: Input: nums = [1;2;3;4] Output: false Explanation: All elements are distinct. Example 3: Input: nums = [1;1;1;3;3;4;3;2;4;2] Output: true Constraints: 1 <= nums.length <= 105 -109 <= nums[i] <= 1091090Amazon,230,Kth Smallest Element in a BST,Med,"Tree, Depth-First Search, Binary Search Tree, Binary Tree",Given the root of a binary search tree; and an integer k; return the kth smallest value (1-indexed) of all the values of the nodes in the tree. Example 1: Input: root = [3;1;4;null;2]; k = 1 Output: 1 Example 2: Input: root = [5;3;6;2;4;null;null;1]; k = 3 Output: 3 Constraints: The number of nodes in the tree is n. 1 <= k <= n <= 104 0 <= Node.val <= 104 Follow up: If the BST is modified often (i.e.; we can do insert and delete operations) and you need to find the kth smallest frequently; how would you optimize?1091Amazon,232,Implement Queue using Stacks,Easy,"Stack, Design, Queue","Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push; peek; pop; and empty). Implement the MyQueue class: void push(int x) Pushes element x to the back of the queue. int pop() Removes the element from the front of the queue and returns it. int peek() Returns the element at the front of the queue. boolean empty() Returns true if the queue is empty; false otherwise. Notes: You must use only standard operations of a stack; which means only push to top; peek/pop from top; size; and is empty operations are valid. Depending on your language; the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations. Example 1: Input [""MyQueue""; ""push""; ""push""; ""peek""; ""pop""; ""empty""] [[]; [1]; [2]; []; []; []] Output [null; null; null; 1; 1; false] Explanation MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1; 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1; queue is [2] myQueue.empty(); // return false Constraints: 1 <= x <= 9 At most 100 calls will be made to push; pop; peek; and empty. All the calls to pop and peek are valid. Follow-up: Can you implement the queue such that each operation is amortized O(1) time complexity? In other words; performing n operations will take overall O(n) time even if one of those operations may take longer."1092Amazon,344,Reverse String,Easy,"Two Pointers, String","Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory. Example 1: Input: s = [""h"";""e"";""l"";""l"";""o""] Output: [""o"";""l"";""l"";""e"";""h""] Example 2: Input: s = [""H"";""a"";""n"";""n"";""a"";""h""] Output: [""h"";""a"";""n"";""n"";""a"";""H""] Constraints: 1 <= s.length <= 105 s[i] is a printable ascii character."1093Amazon,387,First Unique Character in a String,Easy,"Hash Table, String, Queue, Counting","Given a string s; find the first non-repeating character in it and return its index. If it does not exist; return -1. Example 1: Input: s = ""leetcode"" Output: 0 Explanation: The character 'l' at index 0 is the first character that does not occur at any other index. Example 2: Input: s = ""loveleetcode"" Output: 2 Example 3: Input: s = ""aabb"" Output: -1 Constraints: 1 <= s.length <= 105 s consists of only lowercase English letters."1094Amazon,417,Pacific Atlantic Water Flow,Med,"Array, Depth-First Search, Breadth-First Search, Matrix",There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges; and the Atlantic Ocean touches the island's right and bottom edges. The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r; c). The island receives a lot of rain; and the rain water can flow to neighboring cells directly north; south; east; and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. Return a 2D list of grid coordinates result where result[i] = [ri; ci] denotes that rain water can flow from cell (ri; ci) to both the Pacific and Atlantic oceans. Example 1: Input: heights = [[1;2;2;3;5];[3;2;3;4;4];[2;4;5;3;1];[6;7;1;4;5];[5;1;1;2;4]] Output: [[0;4];[1;3];[1;4];[2;2];[3;0];[3;1];[4;0]] Explanation: The following cells can flow to the Pacific and Atlantic oceans; as shown below: [0;4]: [0;4] -> Pacific Ocean [0;4] -> Atlantic Ocean [1;3]: [1;3] -> [0;3] -> Pacific Ocean [1;3] -> [1;4] -> Atlantic Ocean [1;4]: [1;4] -> [1;3] -> [0;3] -> Pacific Ocean [1;4] -> Atlantic Ocean [2;2]: [2;2] -> [1;2] -> [0;2] -> Pacific Ocean [2;2] -> [2;3] -> [2;4] -> Atlantic Ocean [3;0]: [3;0] -> Pacific Ocean [3;0] -> [4;0] -> Atlantic Ocean [3;1]: [3;1] -> [3;0] -> Pacific Ocean [3;1] -> [4;1] -> Atlantic Ocean [4;0]: [4;0] -> Pacific Ocean [4;0] -> Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. Example 2: Input: heights = [[1]] Output: [[0;0]] Explanation: The water can flow from the only cell to the Pacific and Atlantic oceans. Constraints: m == heights.length n == heights[r].length 1 <= m; n <= 200 0 <= heights[r][c] <= 1051095Amazon,438,Find All Anagrams in a String,Med,"Hash Table, String, Sliding Window","Given two strings s and p; return an array of all the start indices of p's anagrams in s. You may return the answer in any order. Example 1: Input: s = ""cbaebabacd""; p = ""abc"" Output: [0;6] Explanation: The substring with start index = 0 is ""cba""; which is an anagram of ""abc"". The substring with start index = 6 is ""bac""; which is an anagram of ""abc"". Example 2: Input: s = ""abab""; p = ""ab"" Output: [0;1;2] Explanation: The substring with start index = 0 is ""ab""; which is an anagram of ""ab"". The substring with start index = 1 is ""ba""; which is an anagram of ""ab"". The substring with start index = 2 is ""ab""; which is an anagram of ""ab"". Constraints: 1 <= s.length; p.length <= 3 * 104 s and p consist of lowercase English letters."1096Amazon,442,Find All Duplicates in an Array,Med,"Array, Hash Table",Given an integer array nums of length n where all the integers of nums are in the range [1; n] and each integer appears at most twice; return an array of all the integers that appears twice. You must write an algorithm that runs in O(n) time and uses only constant auxiliary space; excluding the space needed to store the output Example 1: Input: nums = [4;3;2;7;8;2;3;1] Output: [2;3] Example 2: Input: nums = [1;1;2] Output: [1] Example 3: Input: nums = [1] Output: [] Constraints: n == nums.length 1 <= n <= 105 1 <= nums[i] <= n Each element in nums appears once or twice.1097Amazon,503,Next Greater Element II,Med,"Array, Stack, Monotonic Stack",Given a circular integer array nums (i.e.; the next element of nums[nums.length - 1] is nums[0]); return the next greater number for every element in nums. The next greater number of a number x is the first greater number to its traversing-order next in the array; which means you could search circularly to find its next greater number. If it doesn't exist; return -1 for this number. Example 1: Input: nums = [1;2;1] Output: [2;-1;2] Explanation: The first 1's next greater number is 2; The number 2 can't find next greater number. The second 1's next greater number needs to search circularly; which is also 2. Example 2: Input: nums = [1;2;3;4;3] Output: [2;3;4;-1;4] Constraints: 1 <= nums.length <= 104 -109 <= nums[i] <= 1091098Amazon,539,Minimum Time Difference,Med,"Array, Math, String, Sorting","Given a list of 24-hour clock time points in ""HH:MM"" format; return the minimum minutes difference between any two time-points in the list. Example 1: Input: timePoints = [""23:59"";""00:00""] Output: 1 Example 2: Input: timePoints = [""00:00"";""23:59"";""00:00""] Output: 0 Constraints: 2 <= timePoints.length <= 2 * 104 timePoints[i] is in the format ""HH:MM""."1099Amazon,542,01 Matrix,Med,"Array, Dynamic Programming, Breadth-First Search, Matrix",Given an m x n binary matrix mat; return the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1. Example 1: Input: mat = [[0;0;0];[0;1;0];[0;0;0]] Output: [[0;0;0];[0;1;0];[0;0;0]] Example 2: Input: mat = [[0;0;0];[0;1;0];[1;1;1]] Output: [[0;0;0];[0;1;0];[1;2;1]] Constraints: m == mat.length n == mat[i].length 1 <= m; n <= 104 1 <= m * n <= 104 mat[i][j] is either 0 or 1. There is at least one 0 in mat.1100Amazon,547,Number of Provinces,Med,"Depth-First Search, Breadth-First Search, Union Find, Graph",There are n cities. Some of them are connected; while some are not. If city a is connected directly with city b; and city b is connected directly with city c; then city a is connected indirectly with city c. A province is a group of directly or indirectly connected cities and no other cities outside of the group. You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected; and isConnected[i][j] = 0 otherwise. Return the total number of provinces. Example 1: Input: isConnected = [[1;1;0];[1;1;0];[0;0;1]] Output: 2 Example 2: Input: isConnected = [[1;0;0];[0;1;0];[0;0;1]] Output: 3 Constraints: 1 <= n <= 200 n == isConnected.length n == isConnected[i].length isConnected[i][j] is 1 or 0. isConnected[i][i] == 1 isConnected[i][j] == isConnected[j][i]1101Amazon,670,Maximum Swap,Med,"Math, Greedy",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. Example 1: Input: num = 2736 Output: 7236 Explanation: Swap the number 2 and the number 7. Example 2: Input: num = 9973 Output: 9973 Explanation: No swap. Constraints: 0 <= num <= 1081102Amazon,729,My Calendar I,Med,"Array, Binary Search, Design, Segment Tree, Ordered Set","You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a double booking. A double booking happens when two events have some non-empty intersection (i.e.; some moment is common to both events.). The event can be represented as a pair of integers startTime and endTime that represents a booking on the half-open interval [startTime; endTime); the range of real numbers x such that startTime <= x < endTime. Implement the MyCalendar class: MyCalendar() Initializes the calendar object. boolean book(int startTime; int endTime) Returns true if the event can be added to the calendar successfully without causing a double booking. Otherwise; return false and do not add the event to the calendar. Example 1: Input [""MyCalendar""; ""book""; ""book""; ""book""] [[]; [10; 20]; [15; 25]; [20; 30]] Output [null; true; false; true] Explanation MyCalendar myCalendar = new MyCalendar(); myCalendar.book(10; 20); // return True myCalendar.book(15; 25); // return False; It can not be booked because time 15 is already booked by another event. myCalendar.book(20; 30); // return True; The event can be booked; as the first event takes every time less than 20; but not including 20. Constraints: 0 <= start < end <= 109 At most 1000 calls will be made to book."1103Amazon,787,Cheapest Flights Within K Stops,Med,"Array, Breadth-First Search, Matrix",On an 2 x 3 board; there are five tiles labeled from 1 to 5; and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. The state of the board is solved if and only if the board is [[1;2;3];[4;5;0]]. Given the puzzle board board; return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved; return -1. Example 1: Input: board = [[1;2;3];[4;0;5]] Output: 1 Explanation: Swap the 0 and the 5 in one move. Example 2: Input: board = [[1;2;3];[5;4;0]] Output: -1 Explanation: No number of moves will make the board solved. Example 3: Input: board = [[4;1;2];[5;0;3]] Output: 5 Explanation: 5 is the smallest number of moves that solves the board. An example path: After move 0: [[4;1;2];[5;0;3]] After move 1: [[4;1;2];[0;5;3]] After move 2: [[0;1;2];[4;5;3]] After move 3: [[1;0;2];[4;5;3]] After move 4: [[1;2;0];[4;5;3]] After move 5: [[1;2;3];[4;5;0]] Constraints: board.length == 2 board[i].length == 3 0 <= board[i][j] <= 5 Each value board[i][j] is unique.1104Amazon,794,Valid Tic-Tac-Toe State,Med,"Array, Binary Search, Depth-First Search, Breadth-First Search, Union Find, Heap (Priority Queue), Matrix",You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i; j). The rain starts to fall. At time t; the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distances in zero time. Of course; you must stay within the boundaries of the grid during your swim. Return the least time until you can reach the bottom right square (n - 1; n - 1) if you start at the top left square (0; 0). Example 1: Input: grid = [[0;2];[1;3]] Output: 3 Explanation: At time 0; you are in grid location (0; 0). You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. You cannot reach point (1; 1) until time 3. When the depth of water is 3; we can swim anywhere inside the grid. Example 2: Input: grid = [[0;1;2;3;4];[24;23;22;21;5];[12;13;14;15;16];[11;17;18;19;20];[10;9;8;7;6]] Output: 16 Explanation: The final route is shown. We need to wait until time 16 so that (0; 0) and (4; 4) are connected. Constraints: n == grid.length n == grid[i].length 1 <= n <= 50 0 <= grid[i][j] < n2 Each value grid[i][j] is unique.1105Amazon,528,Random Pick with Weight,Med,"Linked List, Two Pointers",You are given the head of a linked list; and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). Example 1: Input: head = [1;2;3;4;5]; k = 2 Output: [1;4;3;2;5] Example 2: Input: head = [7;9;6;6;7;8;3;0;9;5]; k = 5 Output: [7;9;6;6;8;7;3;0;9;5] Constraints: The number of nodes in the list is n. 1 <= k <= n <= 105 0 <= Node.val <= 1001106Amazon,909,Snakes and Ladders,Med,"Array, Math, Dynamic Programming, Game Theory",Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row; and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones. The total number of stones across all the piles is odd; so there are no ties. Alice and Bob take turns; with Alice starting first. Each turn; a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left; at which point the person with the most stones wins. Assuming Alice and Bob play optimally; return true if Alice wins the game; or false if Bob wins. Example 1: Input: piles = [5;3;4;5] Output: true Explanation: Alice starts first; and can only take the first 5 or the last 5. Say she takes the first 5; so that the row becomes [3; 4; 5]. If Bob takes 3; then the board is [4; 5]; and Alice takes 5 to win with 10 points. If Bob takes the last 5; then the board is [3; 4]; and Alice takes 4 to win with 9 points. This demonstrated that taking the first 5 was a winning move for Alice; so we return true. Example 2: Input: piles = [3;7;2;3] Output: true Constraints: 2 <= piles.length <= 500 piles.length is even. 1 <= piles[i] <= 500 sum(piles[i]) is odd.1107Amazon,937,Reorder Data in Log Files,Med,"Stack, Design, Monotonic Stack, Data Stream","Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day. The span of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day. For example; if the prices of the stock in the last four days is [7;2;1;2] and the price of the stock today is 2; then the span of today is 4 because starting from today; the price of the stock was less than or equal 2 for 4 consecutive days. Also; if the prices of the stock in the last four days is [7;34;1;2] and the price of the stock today is 8; then the span of today is 3 because starting from today; the price of the stock was less than or equal 8 for 3 consecutive days. Implement the StockSpanner class: StockSpanner() Initializes the object of the class. int next(int price) Returns the span of the stock's price given that today's price is price. Example 1: Input [""StockSpanner""; ""next""; ""next""; ""next""; ""next""; ""next""; ""next""; ""next""] [[]; [100]; [80]; [60]; [70]; [60]; [75]; [85]] Output [null; 1; 1; 1; 2; 1; 4; 6] Explanation StockSpanner stockSpanner = new StockSpanner(); stockSpanner.next(100); // return 1 stockSpanner.next(80); // return 1 stockSpanner.next(60); // return 1 stockSpanner.next(70); // return 2 stockSpanner.next(60); // return 1 stockSpanner.next(75); // return 4; because the last 4 prices (including today's price of 75) were less than or equal to today's price. stockSpanner.next(85); // return 6 Constraints: 1 <= price <= 105 At most 104 calls will be made to next."1108Amazon,977,Squares of a Sorted Array,Easy,"String, Dynamic Programming","Given a string s; return the number of distinct non-empty subsequences of s. Since the answer may be very large; return it modulo 109 + 7. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e.; ""ace"" is a subsequence of ""abcde"" while ""aec"" is not. Example 1: Input: s = ""abc"" Output: 7 Explanation: The 7 distinct subsequences are ""a""; ""b""; ""c""; ""ab""; ""ac""; ""bc""; and ""abc"". Example 2: Input: s = ""aba"" Output: 6 Explanation: The 6 distinct subsequences are ""a""; ""b""; ""ab""; ""aa""; ""ba""; and ""aba"". Example 3: Input: s = ""aaa"" Output: 3 Explanation: The 3 distinct subsequences are ""a""; ""aa"" and ""aaa"". Constraints: 1 <= s.length <= 2000 s consists of lowercase English letters."1109Amazon,1004,Max Consecutive Ones III,Med,"Math, Dynamic Programming, Memoization","Given a single positive integer x; we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1; op2; etc. is either addition; subtraction; multiplication; or division (+; -; *; or /). For example; with x = 3; we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression; we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happen before addition and subtraction. It is not allowed to use the unary negation operator (-). For example; ""x - x"" is a valid expression as it only uses subtraction; but ""-x + x"" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used. Example 1: Input: x = 3; target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5; target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100; target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations. Constraints: 2 <= x <= 100 1 <= target <= 2 * 108"1110Amazon,1010,Pairs of Songs With Total Durations Divisible by 60,Med,"Hash Table, Math, Enumeration",Given three integers x; y; and bound; return a list of all the powerful integers that have a value less than or equal to bound. An integer is powerful if it can be represented as xi + yj for some integers i >= 0 and j >= 0. You may return the answer in any order. In your answer; each value should occur at most once. Example 1: Input: x = 2; y = 3; bound = 10 Output: [2;3;4;5;7;9;10] Explanation: 2 = 20 + 30 3 = 21 + 30 4 = 20 + 31 5 = 21 + 31 7 = 22 + 31 9 = 23 + 30 10 = 20 + 32 Example 2: Input: x = 3; y = 5; bound = 15 Output: [2;4;6;8;10;14] Constraints: 1 <= x; y <= 100 0 <= bound <= 1061111Amazon,1091,Shortest Path in Binary Matrix,Med,"Tree, Depth-First Search, Binary Tree",1112Amazon,1331,Rank Transform of an Array,Easy,"Array, Backtracking, Matrix",In a gold mine grid of size m x n; each cell in this mine has an integer representing the amount of gold in that cell; 0 if it is empty. Return the maximum amount of gold you can collect under the conditions: Every time you are located in a cell you will collect all the gold in that cell. From your position; you can walk one step to the left; right; up; or down. You can't visit the same cell more than once. Never visit a cell with 0 gold. You can start and stop collecting gold from any position in the grid that has some gold. Example 1: Input: grid = [[0;6;0];[5;8;7];[0;9;0]] Output: 24 Explanation: [[0;6;0]; [5;8;7]; [0;9;0]] Path to get the maximum gold; 9 -> 8 -> 7. Example 2: Input: grid = [[1;0;7];[2;0;6];[3;4;5];[0;3;0];[9;0;20]] Output: 28 Explanation: [[1;0;7]; [2;0;6]; [3;4;5]; [0;3;0]; [9;0;20]] Path to get the maximum gold; 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. Constraints: m == grid.length n == grid[i].length 1 <= m; n <= 15 0 <= grid[i][j] <= 100 There are at most 25 cells containing gold.1113Amazon,1209,Remove All Adjacent Duplicates in String II,Med,Concurrency,1114Amazon,1482,Minimum Number of Days to Make m Bouquets,Med,"Array, Hash Table, Sorting, Counting",Given the array nums; for each nums[i] find out how many numbers in the array are smaller than it. That is; for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i]. Return the answer in an array. Example 1: Input: nums = [8;1;2;2;3] Output: [4;0;1;1;3] Explanation: For nums[0]=8 there exist four smaller numbers than it (1; 2; 2 and 3). For nums[1]=1 does not exist any smaller number than it. For nums[2]=2 there exist one smaller number than it (1). For nums[3]=2 there exist one smaller number than it (1). For nums[4]=3 there exist three smaller numbers than it (1; 2 and 2). Example 2: Input: nums = [6;5;4;8] Output: [2;1;0;3] Example 3: Input: nums = [7;7;7;7] Output: [0;0;0;0] Constraints: 2 <= nums.length <= 500 0 <= nums[i] <= 1001115Amazon,2696,Minimum String Length After Removing Substrings,Easy,"Array, Hash Table, Math, Dynamic Programming, Backtracking, Sorting, Combinatorics",You are given an array nums of positive integers and a positive integer k. A subset of nums is beautiful if it does not contain two integers with an absolute difference equal to k. Return the number of non-empty beautiful subsets of the array nums. A subset of nums is an array that can be obtained by deleting some (possibly none) elements from nums. Two subsets are different if and only if the chosen indices to delete are different. Example 1: Input: nums = [2;4;6]; k = 2 Output: 4 Explanation: The beautiful subsets of the array nums are: [2]; [4]; [6]; [2; 6]. It can be proved that there are only 4 beautiful subsets in the array [2;4;6]. Example 2: Input: nums = [1]; k = 1 Output: 1 Explanation: The beautiful subset of the array nums is [1]. It can be proved that there is only 1 beautiful subset in the array [1]. Constraints: 1 <= nums.length <= 20 1 <= nums[i]; k <= 10001116Amazon,2938,Separate Black and White Balls,Med,,1117Amazon,3163,String Compression III,Med,"Array, Hash Table",You are given a 0-indexed integer array nums. The distinct count of a subarray of nums is defined as: Let nums[i..j] be a subarray of nums consisting of all the indices from i to j such that 0 <= i <= j < nums.length. Then the number of distinct values in nums[i..j] is called the distinct count of nums[i..j]. Return the sum of the squares of distinct counts of all subarrays of nums. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: nums = [1;2;1] Output: 15 Explanation: Six possible subarrays are: [1]: 1 distinct value [2]: 1 distinct value [1]: 1 distinct value [1;2]: 2 distinct values [2;1]: 2 distinct values [1;2;1]: 2 distinct values The sum of the squares of the distinct counts in all subarrays is equal to 12 + 12 + 12 + 22 + 22 + 22 = 15. Example 2: Input: nums = [1;1] Output: 3 Explanation: Three possible subarrays are: [1]: 1 distinct value [1]: 1 distinct value [1;1]: 1 distinct value The sum of the squares of the distinct counts in all subarrays is equal to 12 + 12 + 12 = 3. Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 1001118Amazon,10,Regular Expression Matching,Hard,"String, Dynamic Programming, Recursion","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). Example 1: Input: s = ""aa""; p = ""a"" Output: false Explanation: ""a"" does not match the entire string ""aa"". Example 2: 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"". Example 3: Input: s = ""ab""; p = "".*"" Output: true Explanation: "".*"" means ""zero or more (*) of any character (.)"". Constraints: 1 <= s.length <= 20 1 <= p.length <= 20 s contains only lowercase English letters. p contains only lowercase English letters; '.'; and '*'. It is guaranteed for each appearance of the character '*'; there will be a previous valid character to match."1119Amazon,24,Swap Nodes in Pairs,Med,"Linked List, Recursion",Given a linked list; swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e.; only nodes themselves may be changed.) Example 1: Input: head = [1;2;3;4] Output: [2;1;4;3] Explanation: Example 2: Input: head = [] Output: [] Example 3: Input: head = [1] Output: [1] Example 4: Input: head = [1;2;3] Output: [2;1;3] Constraints: The number of nodes in the list is in the range [0; 100]. 0 <= Node.val <= 1001120Amazon,26,Remove Duplicates from Sorted Array,Easy,"Array, Two Pointers",Given an integer array nums sorted in non-decreasing order; remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums. Consider the number of unique elements of nums to be k; to get accepted; you need to do the following things: Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums. Return k. Custom Judge: The judge will test your solution with the following code: int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass; then your solution will be accepted. Example 1: Input: nums = [1;1;2] Output: 2; nums = [1;2;_] Explanation: Your function should return k = 2; with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). Example 2: Input: nums = [0;0;1;1;1;2;2;3;3;4] Output: 5; nums = [0;1;2;3;4;_;_;_;_;_] Explanation: Your function should return k = 5; with the first five elements of nums being 0; 1; 2; 3; and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). Constraints: 1 <= nums.length <= 3 * 104 -100 <= nums[i] <= 100 nums is sorted in non-decreasing order.1121Amazon,37,Sudoku Solver,Hard,"Array, Hash Table, Backtracking, Matrix","Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: Each of the digits 1-9 must occur exactly once in each row. Each of the digits 1-9 must occur exactly once in each column. Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. The '.' character indicates empty cells. Example 1: Input: board = [[""5"";""3"";""."";""."";""7"";""."";""."";""."";"".""];[""6"";""."";""."";""1"";""9"";""5"";""."";""."";"".""];[""."";""9"";""8"";""."";""."";""."";""."";""6"";"".""];[""8"";""."";""."";""."";""6"";""."";""."";""."";""3""];[""4"";""."";""."";""8"";""."";""3"";""."";""."";""1""];[""7"";""."";""."";""."";""2"";""."";""."";""."";""6""];[""."";""6"";""."";""."";""."";""."";""2"";""8"";"".""];[""."";""."";""."";""4"";""1"";""9"";""."";""."";""5""];[""."";""."";""."";""."";""8"";""."";""."";""7"";""9""]] Output: [[""5"";""3"";""4"";""6"";""7"";""8"";""9"";""1"";""2""];[""6"";""7"";""2"";""1"";""9"";""5"";""3"";""4"";""8""];[""1"";""9"";""8"";""3"";""4"";""2"";""5"";""6"";""7""];[""8"";""5"";""9"";""7"";""6"";""1"";""4"";""2"";""3""];[""4"";""2"";""6"";""8"";""5"";""3"";""7"";""9"";""1""];[""7"";""1"";""3"";""9"";""2"";""4"";""8"";""5"";""6""];[""9"";""6"";""1"";""5"";""3"";""7"";""2"";""8"";""4""];[""2"";""8"";""7"";""4"";""1"";""9"";""6"";""3"";""5""];[""3"";""4"";""5"";""2"";""8"";""6"";""1"";""7"";""9""]] Explanation: The input board is shown above and the only valid solution is shown below: Constraints: board.length == 9 board[i].length == 9 board[i][j] is a digit or '.'. It is guaranteed that the input board has only one solution."1122Amazon,38,Count and Say,Med,String,"The count-and-say sequence is a sequence of digit strings defined by the recursive formula: countAndSay(1) = ""1"" countAndSay(n) is the run-length encoding of countAndSay(n - 1). Run-length encoding (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example; to compress the string ""3322251"" we replace ""33"" with ""23""; replace ""222"" with ""32""; replace ""5"" with ""15"" and replace ""1"" with ""11"". Thus the compressed string becomes ""23321511"". Given a positive integer n; return the nth element of the count-and-say sequence. Example 1: Input: n = 4 Output: ""1211"" Explanation: countAndSay(1) = ""1"" countAndSay(2) = RLE of ""1"" = ""11"" countAndSay(3) = RLE of ""11"" = ""21"" countAndSay(4) = RLE of ""21"" = ""1211"" Example 2: Input: n = 1 Output: ""1"" Explanation: This is the base case. Constraints: 1 <= n <= 30 Follow up: Could you solve it iteratively?"1123Amazon,40,Combination Sum II,Med,"Array, Backtracking",Given a collection of candidate numbers (candidates) and a target number (target); find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations. Example 1: Input: candidates = [10;1;2;7;6;1;5]; target = 8 Output: [ [1;1;6]; [1;2;5]; [1;7]; [2;6] ] Example 2: Input: candidates = [2;5;2;1;2]; target = 5 Output: [ [1;2;2]; [5] ] Constraints: 1 <= candidates.length <= 100 1 <= candidates[i] <= 50 1 <= target <= 301124Amazon,44,Wildcard Matching,Hard,"String, Dynamic Programming, Greedy, Recursion","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). Example 1: Input: s = ""aa""; p = ""a"" Output: false Explanation: ""a"" does not match the entire string ""aa"". Example 2: Input: s = ""aa""; p = ""*"" Output: true Explanation: '*' matches any sequence. Example 3: Input: s = ""cb""; p = ""?a"" Output: false Explanation: '?' matches 'c'; but the second letter is 'a'; which does not match 'b'. Constraints: 0 <= s.length; p.length <= 2000 s contains only lowercase English letters. p contains only lowercase English letters; '?' or '*'."1125Amazon,61,Rotate List,Med,"Linked List, Two Pointers",Given the head of a linked list; rotate the list to the right by k places. Example 1: Input: head = [1;2;3;4;5]; k = 2 Output: [4;5;1;2;3] Example 2: Input: head = [0;1;2]; k = 4 Output: [2;0;1] Constraints: The number of nodes in the list is in the range [0; 500]. -100 <= Node.val <= 100 0 <= k <= 2 * 1091126Amazon,67,Add Binary,Easy,"Math, String, Bit Manipulation, Simulation","Given two binary strings a and b; return their sum as a binary string. Example 1: Input: a = ""11""; b = ""1"" Output: ""100"" Example 2: Input: a = ""1010""; b = ""1011"" Output: ""10101"" Constraints: 1 <= a.length; b.length <= 104 a and b consist only of '0' or '1' characters. Each string does not contain leading zeros except for the zero itself."1127Amazon,72,Edit Distance,Med,"String, Dynamic Programming","Given two strings word1 and word2; return the minimum number of operations required to convert word1 to word2. You have the following three operations permitted on a word: Insert a character Delete a character Replace a character Example 1: Input: word1 = ""horse""; word2 = ""ros"" Output: 3 Explanation: horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') Example 2: Input: word1 = ""intention""; word2 = ""execution"" Output: 5 Explanation: intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') Constraints: 0 <= word1.length; word2.length <= 500 word1 and word2 consist of lowercase English letters."1128Amazon,73,Set Matrix Zeroes,Med,"Array, Hash Table, Matrix",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. Example 1: Input: matrix = [[1;1;1];[1;0;1];[1;1;1]] Output: [[1;0;1];[0;0;0];[1;0;1]] Example 2: Input: matrix = [[0;1;2;0];[3;4;5;2];[1;3;1;5]] Output: [[0;0;0;0];[0;4;5;0];[0;3;1;0]] Constraints: m == matrix.length n == matrix[0].length 1 <= m; n <= 200 -231 <= matrix[i][j] <= 231 - 1 Follow up: A straightforward solution using O(mn) space is probably a bad idea. A simple improvement uses O(m + n) space; but still not the best solution. Could you devise a constant space solution?1129Amazon,76,Minimum Window Substring,Hard,"Hash Table, String, Sliding Window","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. Example 1: Input: s = ""ADOBECODEBANC""; t = ""ABC"" Output: ""BANC"" Explanation: The minimum window substring ""BANC"" includes 'A'; 'B'; and 'C' from string t. Example 2: Input: s = ""a""; t = ""a"" Output: ""a"" Explanation: The entire string s is the minimum window. Example 3: Input: s = ""a""; t = ""aa"" Output: """" Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has one 'a'; return empty string. Constraints: m == s.length n == t.length 1 <= m; n <= 105 s and t consist of uppercase and lowercase English letters. Follow up: Could you find an algorithm that runs in O(m + n) time?"1130Amazon,80,Remove Duplicates from Sorted Array II,Med,"Array, Two Pointers",Given an integer array nums sorted in non-decreasing order; remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages; you must instead have the result be placed in the first part of the array nums. More formally; if there are k elements after removing the duplicates; then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass; then your solution will be accepted. Example 1: Input: nums = [1;1;1;2;2;3] Output: 5; nums = [1;1;2;2;3;_] Explanation: Your function should return k = 5; with the first five elements of nums being 1; 1; 2; 2 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). Example 2: Input: nums = [0;0;1;1;1;1;2;3;3] Output: 7; nums = [0;0;1;1;2;3;3;_;_] Explanation: Your function should return k = 7; with the first seven elements of nums being 0; 0; 1; 1; 2; 3 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). Constraints: 1 <= nums.length <= 3 * 104 -104 <= nums[i] <= 104 nums is sorted in non-decreasing order.1131Amazon,83,Remove Duplicates from Sorted List,Easy,Linked List,Given the head of a sorted linked list; delete all duplicates such that each element appears only once. Return the linked list sorted as well. Example 1: Input: head = [1;1;2] Output: [1;2] Example 2: Input: head = [1;1;2;3;3] Output: [1;2;3] Constraints: The number of nodes in the list is in the range [0; 300]. -100 <= Node.val <= 100 The list is guaranteed to be sorted in ascending order.1132Amazon,95,Unique Binary Search Trees II,Med,"Dynamic Programming, Backtracking, Tree, Binary Search Tree, Binary Tree",Given an integer n; return all the structurally unique BST's (binary search trees); which has exactly n nodes of unique values from 1 to n. Return the answer in any order. Example 1: Input: n = 3 Output: [[1;null;2;null;3];[1;null;3;2];[2;1;3];[3;1;null;null;2];[3;2;null;1]] Example 2: Input: n = 1 Output: [[1]] Constraints: 1 <= n <= 81133Amazon,97,Interleaving String,Med,"String, Dynamic Programming","Given strings s1; s2; and s3; find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where s and t are divided into n and m substrings respectively; such that: s = s1 + s2 + ... + sn t = t1 + t2 + ... + tm |n - m| <= 1 The interleaving is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ... Note: a + b is the concatenation of strings a and b. Example 1: Input: s1 = ""aabcc""; s2 = ""dbbca""; s3 = ""aadbbcbcac"" Output: true Explanation: One way to obtain s3 is: Split s1 into s1 = ""aa"" + ""bc"" + ""c""; and s2 into s2 = ""dbbc"" + ""a"". Interleaving the two splits; we get ""aa"" + ""dbbc"" + ""bc"" + ""a"" + ""c"" = ""aadbbcbcac"". Since s3 can be obtained by interleaving s1 and s2; we return true. Example 2: Input: s1 = ""aabcc""; s2 = ""dbbca""; s3 = ""aadbbbaccc"" Output: false Explanation: Notice how it is impossible to interleave s2 with any other string to obtain s3. Example 3: Input: s1 = """"; s2 = """"; s3 = """" Output: true Constraints: 0 <= s1.length; s2.length <= 100 0 <= s3.length <= 200 s1; s2; and s3 consist of lowercase English letters. Follow up: Could you solve it using only O(s2.length) additional memory space?"1134Amazon,98,Validate Binary Search Tree,Med,"Tree, Depth-First Search, Binary Search Tree, Binary Tree",Given the root of a binary tree; determine if it is a valid binary search tree (BST). A valid BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: root = [2;1;3] Output: true Example 2: Input: root = [5;1;4;null;null;3;6] Output: false Explanation: The root node's value is 5 but its right child's value is 4. Constraints: The number of nodes in the tree is in the range [1; 104]. -231 <= Node.val <= 231 - 11135Amazon,101,Symmetric Tree,Easy,"Tree, Depth-First Search, Breadth-First Search, Binary Tree",Given the root of a binary tree; check whether it is a mirror of itself (i.e.; symmetric around its center). Example 1: Input: root = [1;2;2;3;4;4;3] Output: true Example 2: Input: root = [1;2;2;null;3;null;3] Output: false Constraints: The number of nodes in the tree is in the range [1; 1000]. -100 <= Node.val <= 100 Follow up: Could you solve it both recursively and iteratively?1136Amazon,107,Binary Tree Level Order Traversal II,Med,"Tree, Breadth-First Search, Binary Tree",Given the root of a binary tree; return the bottom-up level order traversal of its nodes' values. (i.e.; from left to right; level by level from leaf to root). Example 1: Input: root = [3;9;20;null;null;15;7] Output: [[15;7];[9;20];[3]] Example 2: Input: root = [1] Output: [[1]] Example 3: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0; 2000]. -1000 <= Node.val <= 10001137Amazon,110,Balanced Binary Tree,Easy,"Tree, Depth-First Search, Binary Tree",Given a binary tree; determine if it is height-balanced. Example 1: Input: root = [3;9;20;null;null;15;7] Output: true Example 2: Input: root = [1;2;2;3;3;null;null;4;4] Output: false Example 3: Input: root = [] Output: true Constraints: The number of nodes in the tree is in the range [0; 5000]. -104 <= Node.val <= 1041138Amazon,113,Path Sum II,Med,"Backtracking, Tree, Depth-First Search, Binary Tree",Given the root of a binary tree and an integer targetSum; return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values; not node references. A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children. Example 1: Input: root = [5;4;8;11;null;13;4;7;2;null;null;5;1]; targetSum = 22 Output: [[5;4;11;2];[5;8;4;5]] Explanation: There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 Example 2: Input: root = [1;2;3]; targetSum = 5 Output: [] Example 3: Input: root = [1;2]; targetSum = 0 Output: [] Constraints: The number of nodes in the tree is in the range [0; 5000]. -1000 <= Node.val <= 1000 -1000 <= targetSum <= 10001139Amazon,116,Populating Next Right Pointers in Each Node,Med,"Linked List, Tree, Depth-First Search, Breadth-First Search, Binary Tree",You are given a perfect binary tree where all leaves are on the same level; and every parent has two children. The binary tree has the following definition: struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node; the next pointer should be set to NULL. Initially; all next pointers are set to NULL. Example 1: Input: root = [1;2;3;4;5;6;7] Output: [1;#;2;3;#;4;5;6;7;#] Explanation: Given the above perfect binary tree (Figure A); your function should populate each next pointer to point to its next right node; just like in Figure B. The serialized output is in level order as connected by the next pointers; with '#' signifying the end of each level. Example 2: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0; 212 - 1]. -1000 <= Node.val <= 1000 Follow-up: You may only use constant extra space. The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.1140Amazon,120,Triangle,Med,"Array, Dynamic Programming",Given a triangle array; return the minimum path sum from top to bottom. For each step; you may move to an adjacent number of the row below. More formally; if you are on index i on the current row; you may move to either index i or index i + 1 on the next row. Example 1: Input: triangle = [[2];[3;4];[6;5;7];[4;1;8;3]] Output: 11 Explanation: The triangle looks like: 2 3 4 6 5 7 4 1 8 3 The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). Example 2: Input: triangle = [[-10]] Output: -10 Constraints: 1 <= triangle.length <= 200 triangle[0].length == 1 triangle[i].length == triangle[i - 1].length + 1 -104 <= triangle[i][j] <= 104 Follow up: Could you do this using only O(n) extra space; where n is the total number of rows in the triangle?1141Amazon,140,Word Break II,Hard,"Array, Hash Table, String, Dynamic Programming, Backtracking, Trie, Memoization","Given a string s and a dictionary of strings wordDict; add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order. Note that the same word in the dictionary may be reused multiple times in the segmentation. Example 1: Input: s = ""catsanddog""; wordDict = [""cat"";""cats"";""and"";""sand"";""dog""] Output: [""cats and dog"";""cat sand dog""] Example 2: Input: s = ""pineapplepenapple""; wordDict = [""apple"";""pen"";""applepen"";""pine"";""pineapple""] Output: [""pine apple pen apple"";""pineapple pen apple"";""pine applepen apple""] Explanation: Note that you are allowed to reuse a dictionary word. Example 3: Input: s = ""catsandog""; wordDict = [""cats"";""dog"";""sand"";""and"";""cat""] Output: [] Constraints: 1 <= s.length <= 20 1 <= wordDict.length <= 1000 1 <= wordDict[i].length <= 10 s and wordDict[i] consist of only lowercase English letters. All the strings of wordDict are unique. Input is generated in a way that the length of the answer doesn't exceed 105."1142Amazon,141,Linked List Cycle,Easy,"Hash Table, Linked List, Two Pointers",Given head; the head of a linked list; determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally; pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter. Return true if there is a cycle in the linked list. Otherwise; return false. Example 1: Input: head = [3;2;0;-4]; pos = 1 Output: true Explanation: There is a cycle in the linked list; where the tail connects to the 1st node (0-indexed). Example 2: Input: head = [1;2]; pos = 0 Output: true Explanation: There is a cycle in the linked list; where the tail connects to the 0th node. Example 3: Input: head = [1]; pos = -1 Output: false Explanation: There is no cycle in the linked list. Constraints: The number of the nodes in the list is in the range [0; 104]. -105 <= Node.val <= 105 pos is -1 or a valid index in the linked-list. Follow up: Can you solve it using O(1) (i.e. constant) memory?1143Amazon,148,Sort List,Med,"Linked List, Two Pointers, Divide and Conquer, Sorting, Merge Sort",Given the head of a linked list; return the list after sorting it in ascending order. Example 1: Input: head = [4;2;1;3] Output: [1;2;3;4] Example 2: Input: head = [-1;5;3;4;0] Output: [-1;0;3;4;5] Example 3: Input: head = [] Output: [] Constraints: The number of nodes in the list is in the range [0; 5 * 104]. -105 <= Node.val <= 105 Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?1144Amazon,153,Find Minimum in Rotated Sorted Array,Med,"Array, Binary Search",Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example; the array nums = [0;1;2;4;5;6;7] might become: [4;5;6;7;0;1;2] if it was rotated 4 times. [0;1;2;4;5;6;7] if it was rotated 7 times. Notice that rotating an array [a[0]; a[1]; a[2]; ...; a[n-1]] 1 time results in the array [a[n-1]; a[0]; a[1]; a[2]; ...; a[n-2]]. Given the sorted rotated array nums of unique elements; return the minimum element of this array. You must write an algorithm that runs in O(log n) time. Example 1: Input: nums = [3;4;5;1;2] Output: 1 Explanation: The original array was [1;2;3;4;5] rotated 3 times. Example 2: Input: nums = [4;5;6;7;0;1;2] Output: 0 Explanation: The original array was [0;1;2;4;5;6;7] and it was rotated 4 times. Example 3: Input: nums = [11;13;15;17] Output: 11 Explanation: The original array was [11;13;15;17] and it was rotated 4 times. Constraints: n == nums.length 1 <= n <= 5000 -5000 <= nums[i] <= 5000 All the integers of nums are unique. nums is sorted and rotated between 1 and n times.1145Amazon,160,Intersection of Two Linked Lists,Easy,"Hash Table, Linked List, Two Pointers",Given the heads of two singly linked-lists headA and headB; return the node at which the two lists intersect. If the two linked lists have no intersection at all; return null. For example; the following two linked lists begin to intersect at node c1: The test cases are generated such that there are no cycles anywhere in the entire linked structure. Note that the linked lists must retain their original structure after the function returns. Custom Judge: The inputs to the judge are given as follows (your program is not given these inputs): intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node. listA - The first linked list. listB - The second linked list. skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node. skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node. The judge will then create the linked structure based on these inputs and pass the two heads; headA and headB to your program. If you correctly return the intersected node; then your solution will be accepted. Example 1: Input: intersectVal = 8; listA = [4;1;8;4;5]; listB = [5;6;1;8;4;5]; skipA = 2; skipB = 3 Output: Intersected at '8' Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A; it reads as [4;1;8;4;5]. From the head of B; it reads as [5;6;1;8;4;5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words; they point to two different locations in memory; while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory. Example 2: Input: intersectVal = 2; listA = [1;9;1;2;4]; listB = [3;2;4]; skipA = 3; skipB = 1 Output: Intersected at '2' Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A; it reads as [1;9;1;2;4]. From the head of B; it reads as [3;2;4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. Example 3: Input: intersectVal = 0; listA = [2;6;4]; listB = [1;5]; skipA = 3; skipB = 2 Output: No intersection Explanation: From the head of A; it reads as [2;6;4]. From the head of B; it reads as [1;5]. Since the two lists do not intersect; intersectVal must be 0; while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect; so return null. Constraints: The number of nodes of listA is in the m. The number of nodes of listB is in the n. 1 <= m; n <= 3 * 104 1 <= Node.val <= 105 0 <= skipA <= m 0 <= skipB <= n intersectVal is 0 if listA and listB do not intersect. intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect. Follow up: Could you write a solution that runs in O(m + n) time and use only O(1) memory?1146Amazon,175,Combine Two Tables,Easy,Database,Table: Person +-------------+---------+ | Column Name | Type | +-------------+---------+ | personId | int | | lastName | varchar | | firstName | varchar | +-------------+---------+ personId is the primary key (column with unique values) for this table. This table contains information about the ID of some persons and their first and last names. Table: Address +-------------+---------+ | Column Name | Type | +-------------+---------+ | addressId | int | | personId | int | | city | varchar | | state | varchar | +-------------+---------+ addressId is the primary key (column with unique values) for this table. Each row of this table contains information about the city and state of one person with ID = PersonId. Write a solution to report the first name; last name; city; and state of each person in the Person table. If the address of a personId is not present in the Address table; report null instead. Return the result table in any order. The result format is in the following example. Example 1: Input: Person table: +----------+----------+-----------+ | personId | lastName | firstName | +----------+----------+-----------+ | 1 | Wang | Allen | | 2 | Alice | Bob | +----------+----------+-----------+ Address table: +-----------+----------+---------------+------------+ | addressId | personId | city | state | +-----------+----------+---------------+------------+ | 1 | 2 | New York City | New York | | 2 | 3 | Leetcode | California | +-----------+----------+---------------+------------+ Output: +-----------+----------+---------------+----------+ | firstName | lastName | city | state | +-----------+----------+---------------+----------+ | Allen | Wang | Null | Null | | Bob | Alice | New York City | New York | +-----------+----------+---------------+----------+ Explanation: There is no address in the address table for the personId = 1 so we return null in their city and state. addressId = 1 contains information about the address of personId = 2.1147Amazon,181,Employees Earning More Than Their Managers,Easy,Database,Table: Employee +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | | salary | int | | managerId | int | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table indicates the ID of an employee; their name; salary; and the ID of their manager. Write a solution to find the employees who earn more than their managers. Return the result table in any order. The result format is in the following example. Example 1: Input: Employee table: +----+-------+--------+-----------+ | id | name | salary | managerId | +----+-------+--------+-----------+ | 1 | Joe | 70000 | 3 | | 2 | Henry | 80000 | 4 | | 3 | Sam | 60000 | Null | | 4 | Max | 90000 | Null | +----+-------+--------+-----------+ Output: +----------+ | Employee | +----------+ | Joe | +----------+ Explanation: Joe is the only employee who earns more than his manager.1148Amazon,187,Repeated DNA Sequences,Med,"Hash Table, String, Bit Manipulation, Sliding Window, Rolling Hash, Hash Function","The DNA sequence is composed of a series of nucleotides abbreviated as 'A'; 'C'; 'G'; and 'T'. For example; ""ACGAATTCCG"" is a DNA sequence. When studying DNA; it is useful to identify repeated sequences within the DNA. Given a string s that represents a DNA sequence; return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order. Example 1: Input: s = ""AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"" Output: [""AAAAACCCCC"";""CCCCCAAAAA""] Example 2: Input: s = ""AAAAAAAAAAAAA"" Output: [""AAAAAAAAAA""] Constraints: 1 <= s.length <= 105 s[i] is either 'A'; 'C'; 'G'; or 'T'."1149Amazon,188,Best Time to Buy and Sell Stock IV,Hard,"Array, Dynamic Programming",You are given an integer array prices where prices[i] is the price of a given stock on the ith day; and an integer k. Find the maximum profit you can achieve. You may complete at most k transactions: i.e. you may buy at most k times and sell at most k times. Note: You may not engage in multiple transactions simultaneously (i.e.; you must sell the stock before you buy again). Example 1: Input: k = 2; prices = [2;4;1] Output: 2 Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4); profit = 4-2 = 2. Example 2: Input: k = 2; prices = [3;2;6;5;0;3] Output: 7 Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6); profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3); profit = 3-0 = 3. Constraints: 1 <= k <= 100 1 <= prices.length <= 1000 0 <= prices[i] <= 10001150Amazon,214,Shortest Palindrome,Hard,"String, Rolling Hash, String Matching, Hash Function","You are given a string s. You can convert s to a palindrome by adding characters in front of it. Return the shortest palindrome you can find by performing this transformation. Example 1: Input: s = ""aacecaaa"" Output: ""aaacecaaa"" Example 2: Input: s = ""abcd"" Output: ""dcbabcd"" Constraints: 0 <= s.length <= 5 * 104 s consists of lowercase English letters only."1151Amazon,225,Implement Stack using Queues,Easy,"Stack, Design, Queue","Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push; top; pop; and empty). Implement the MyStack class: void push(int x) Pushes element x to the top of the stack. int pop() Removes the element on the top of the stack and returns it. int top() Returns the element on the top of the stack. boolean empty() Returns true if the stack is empty; false otherwise. Notes: You must use only standard operations of a queue; which means that only push to back; peek/pop from front; size and is empty operations are valid. Depending on your language; the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations. Example 1: Input [""MyStack""; ""push""; ""push""; ""top""; ""pop""; ""empty""] [[]; [1]; [2]; []; []; []] Output [null; null; null; 2; 2; false] Explanation MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False Constraints: 1 <= x <= 9 At most 100 calls will be made to push; pop; top; and empty. All the calls to pop and top are valid. Follow-up: Can you implement the stack using only one queue?"1152Amazon,229,Majority Element II,Med,"Array, Hash Table, Sorting, Counting",Given an integer array of size n; find all elements that appear more than ⌊ n/3 ⌋ times. Example 1: Input: nums = [3;2;3] Output: [3] Example 2: Input: nums = [1] Output: [1] Example 3: Input: nums = [1;2] Output: [1;2] Constraints: 1 <= nums.length <= 5 * 104 -109 <= nums[i] <= 109 Follow up: Could you solve the problem in linear time and in O(1) space?1153Amazon,231,Power of Two,Easy,"Math, Bit Manipulation, Recursion",Given an integer n; return true if it is a power of two. Otherwise; return false. An integer n is a power of two; if there exists an integer x such that n == 2x. Example 1: Input: n = 1 Output: true Explanation: 20 = 1 Example 2: Input: n = 16 Output: true Explanation: 24 = 16 Example 3: Input: n = 3 Output: false Constraints: -231 <= n <= 231 - 1 Follow up: Could you solve it without loops/recursion?1154Amazon,234,Palindrome Linked List,Easy,"Linked List, Two Pointers, Stack, Recursion",Given the head of a singly linked list; return true if it is a palindrome or false otherwise. Example 1: Input: head = [1;2;2;1] Output: true Example 2: Input: head = [1;2] Output: false Constraints: The number of nodes in the list is in the range [1; 105]. 0 <= Node.val <= 9 Follow up: Could you do it in O(n) time and O(1) space?1155Amazon,235,Lowest Common Ancestor of a Binary Search Tree,Med,"Tree, Depth-First Search, Binary Search Tree, Binary Tree",Given a binary search tree (BST); find the lowest common ancestor (LCA) node of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Example 1: Input: root = [6;2;8;0;4;7;9;null;null;3;5]; p = 2; q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6. Example 2: Input: root = [6;2;8;0;4;7;9;null;null;3;5]; p = 2; q = 4 Output: 2 Explanation: The LCA of nodes 2 and 4 is 2; since a node can be a descendant of itself according to the LCA definition. Example 3: Input: root = [2;1]; p = 2; q = 1 Output: 2 Constraints: The number of nodes in the tree is in the range [2; 105]. -109 <= Node.val <= 109 All Node.val are unique. p != q p and q will exist in the BST.1156Amazon,261,Graph Valid Tree,Med,"Depth-First Search, Breadth-First Search, Union Find, Graph",1157Amazon,274,H-Index,Med,"Array, Sorting, Counting Sort",Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper; return the researcher's h-index. According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times. Example 1: Input: citations = [3;0;6;1;5] Output: 3 Explanation: [3;0;6;1;5] means the researcher has 5 papers in total and each of them had received 3; 0; 6; 1; 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each; their h-index is 3. Example 2: Input: citations = [1;3;1] Output: 1 Constraints: n == citations.length 1 <= n <= 5000 0 <= citations[i] <= 10001158Amazon,279,Perfect Squares,Med,"Math, Dynamic Programming, Breadth-First Search",Given an integer n; return the least number of perfect square numbers that sum to n. A perfect square is an integer that is the square of an integer; in other words; it is the product of some integer with itself. For example; 1; 4; 9; and 16 are perfect squares while 3 and 11 are not. Example 1: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. Example 2: Input: n = 13 Output: 2 Explanation: 13 = 4 + 9. Constraints: 1 <= n <= 1041159Amazon,303,Range Sum Query - Immutable,Easy,"Array, Design, Prefix Sum","Given an integer array nums; handle multiple queries of the following type: Calculate the sum of the elements of nums between indices left and right inclusive where left <= right. Implement the NumArray class: NumArray(int[] nums) Initializes the object with the integer array nums. int sumRange(int left; int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]). Example 1: Input [""NumArray""; ""sumRange""; ""sumRange""; ""sumRange""] [[[-2; 0; 3; -5; 2; -1]]; [0; 2]; [2; 5]; [0; 5]] Output [null; 1; -1; -3] Explanation NumArray numArray = new NumArray([-2; 0; 3; -5; 2; -1]); numArray.sumRange(0; 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2; 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0; 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 Constraints: 1 <= nums.length <= 104 -105 <= nums[i] <= 105 0 <= left <= right < nums.length At most 104 calls will be made to sumRange."1160Amazon,327,Count of Range Sum,Hard,"Array, Binary Search, Divide and Conquer, Binary Indexed Tree, Segment Tree, Merge Sort, Ordered Set",Given an integer array nums and two integers lower and upper; return the number of range sums that lie in [lower; upper] inclusive. Range sum S(i; j) is defined as the sum of the elements in nums between indices i and j inclusive; where i <= j. Example 1: Input: nums = [-2;5;-1]; lower = -2; upper = 2 Output: 3 Explanation: The three ranges are: [0;0]; [2;2]; and [0;2] and their respective sums are: -2; -1; 2. Example 2: Input: nums = [0]; lower = 0; upper = 0 Output: 1 Constraints: 1 <= nums.length <= 105 -231 <= nums[i] <= 231 - 1 -105 <= lower <= upper <= 105 The answer is guaranteed to fit in a 32-bit integer.1161Amazon,332,Reconstruct Itinerary,Hard,"Depth-First Search, Graph, Eulerian Circuit","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. Example 1: Input: tickets = [[""MUC"";""LHR""];[""JFK"";""MUC""];[""SFO"";""SJC""];[""LHR"";""SFO""]] Output: [""JFK"";""MUC"";""LHR"";""SFO"";""SJC""] Example 2: 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. Constraints: 1 <= tickets.length <= 300 tickets[i].length == 2 fromi.length == 3 toi.length == 3 fromi and toi consist of uppercase English letters. fromi != toi"1162Amazon,339,Nested List Weight Sum,Med,"Depth-First Search, Breadth-First Search",1163Amazon,340,Longest Substring with At Most K Distinct Characters,Med,"Hash Table, String, Sliding Window",1164Amazon,383,Ransom Note,Easy,"Hash Table, String, Counting","Given two strings ransomNote and magazine; return true if ransomNote can be constructed by using the letters from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote. Example 1: Input: ransomNote = ""a""; magazine = ""b"" Output: false Example 2: Input: ransomNote = ""aa""; magazine = ""ab"" Output: false Example 3: Input: ransomNote = ""aa""; magazine = ""aab"" Output: true Constraints: 1 <= ransomNote.length; magazine.length <= 105 ransomNote and magazine consist of lowercase English letters."1165Amazon,386,Lexicographical Numbers,Med,"Depth-First Search, Trie",Given an integer n; return all the numbers in the range [1; n] sorted in lexicographical order. You must write an algorithm that runs in O(n) time and uses O(1) extra space. Example 1: Input: n = 13 Output: [1;10;11;12;13;2;3;4;5;6;7;8;9] Example 2: Input: n = 2 Output: [1;2] Constraints: 1 <= n <= 5 * 1041166Amazon,412,Fizz Buzz,Easy,"Math, String, Simulation","Given an integer n; return a string array answer (1-indexed) where: answer[i] == ""FizzBuzz"" if i is divisible by 3 and 5. answer[i] == ""Fizz"" if i is divisible by 3. answer[i] == ""Buzz"" if i is divisible by 5. answer[i] == i (as a string) if none of the above conditions are true. Example 1: Input: n = 3 Output: [""1"";""2"";""Fizz""] Example 2: Input: n = 5 Output: [""1"";""2"";""Fizz"";""4"";""Buzz""] Example 3: Input: n = 15 Output: [""1"";""2"";""Fizz"";""4"";""Buzz"";""Fizz"";""7"";""8"";""Fizz"";""Buzz"";""11"";""Fizz"";""13"";""14"";""FizzBuzz""] Constraints: 1 <= n <= 104"1167Amazon,416,Partition Equal Subset Sum,Med,"Array, Dynamic Programming",Given an integer array nums; return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise. Example 1: Input: nums = [1;5;11;5] Output: true Explanation: The array can be partitioned as [1; 5; 5] and [11]. Example 2: Input: nums = [1;2;3;5] Output: false Explanation: The array cannot be partitioned into equal sum subsets. Constraints: 1 <= nums.length <= 200 1 <= nums[i] <= 1001168Amazon,424,Longest Repeating Character Replacement,Med,"Hash Table, String, Sliding Window","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. Example 1: Input: s = ""ABAB""; k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa. Example 2: Input: s = ""AABABBA""; k = 1 Output: 4 Explanation: Replace the one 'A' in the middle with 'B' and form ""AABBBBA"". The substring ""BBBB"" has the longest repeating letters; which is 4. There may exists other ways to achieve this answer too. Constraints: 1 <= s.length <= 105 s consists of only uppercase English letters. 0 <= k <= s.length"1169Amazon,493,Reverse Pairs,Hard,"Array, Binary Search, Divide and Conquer, Binary Indexed Tree, Segment Tree, Merge Sort, Ordered Set",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]. Example 1: 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 Example 2: Input: nums = [2;4;3;5;1] Output: 3 Explanation: The reverse pairs are: (1; 4) --> nums[1] = 4; nums[4] = 1; 4 > 2 * 1 (2; 4) --> nums[2] = 3; nums[4] = 1; 3 > 2 * 1 (3; 4) --> nums[3] = 5; nums[4] = 1; 5 > 2 * 1 Constraints: 1 <= nums.length <= 5 * 104 -231 <= nums[i] <= 231 - 11170Amazon,1721,Swapping Nodes in a Linked List,Med,"Array, Simulation",You are the operator of a Centennial Wheel that has four gondolas; and each gondola has room for up to four people. You have the ability to rotate the gondolas counterclockwise; which costs you runningCost dollars. You are given an array customers of length n where customers[i] is the number of new customers arriving just before the ith rotation (0-indexed). This means you must rotate the wheel i times before the customers[i] customers arrive. You cannot make customers wait if there is room in the gondola. Each customer pays boardingCost dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again. You can stop the wheel at any time; including before serving all customers. If you decide to stop serving customers; all subsequent rotations are free in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel; only four will board the gondola; and the rest will wait for the next rotation. Return the minimum number of rotations you need to perform to maximize your profit. If there is no scenario where the profit is positive; return -1. Example 1: Input: customers = [8;3]; boardingCost = 5; runningCost = 6 Output: 3 Explanation: The numbers written on the gondolas are the number of people currently there. 1. 8 customers arrive; 4 board and 4 wait for the next gondola; the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14. 2. 3 customers arrive; the 4 waiting board the wheel and the other 3 wait; the wheel rotates. Current profit is 8 * $5 - 2 * $6 = $28. 3. The final 3 customers board the gondola; the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37. The highest profit was $37 after rotating the wheel 3 times. Example 2: Input: customers = [10;9;6]; boardingCost = 6; runningCost = 4 Output: 7 Explanation: 1. 10 customers arrive; 4 board and 6 wait for the next gondola; the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20. 2. 9 customers arrive; 4 board and 11 wait (2 originally waiting; 9 newly waiting); the wheel rotates. Current profit is 8 * $6 - 2 * $4 = $40. 3. The final 6 customers arrive; 4 board and 13 wait; the wheel rotates. Current profit is 12 * $6 - 3 * $4 = $60. 4. 4 board and 9 wait; the wheel rotates. Current profit is 16 * $6 - 4 * $4 = $80. 5. 4 board and 5 wait; the wheel rotates. Current profit is 20 * $6 - 5 * $4 = $100. 6. 4 board and 1 waits; the wheel rotates. Current profit is 24 * $6 - 6 * $4 = $120. 7. 1 boards; the wheel rotates. Current profit is 25 * $6 - 7 * $4 = $122. The highest profit was $122 after rotating the wheel 7 times. Example 3: Input: customers = [3;4;0;5;1]; boardingCost = 1; runningCost = 92 Output: -1 Explanation: 1. 3 customers arrive; 3 board and 0 wait; the wheel rotates. Current profit is 3 * $1 - 1 * $92 = -$89. 2. 4 customers arrive; 4 board and 0 wait; the wheel rotates. Current profit is 7 * $1 - 2 * $92 = -$177. 3. 0 customers arrive; 0 board and 0 wait; the wheel rotates. Current profit is 7 * $1 - 3 * $92 = -$269. 4. 5 customers arrive; 4 board and 1 waits; the wheel rotates. Current profit is 11 * $1 - 4 * $92 = -$357. 5. 1 customer arrives; 2 board and 0 wait; the wheel rotates. Current profit is 13 * $1 - 5 * $92 = -$447. The profit was never positive; so return -1. Constraints: n == customers.length 1 <= n <= 105 0 <= customers[i] <= 50 1 <= boardingCost; runningCost <= 1001171Amazon,543,Diameter of Binary Tree,Easy,"Tree, Depth-First Search, Binary Tree",Given the root of a binary tree; return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them. Example 1: Input: root = [1;2;3;4;5] Output: 3 Explanation: 3 is the length of the path [4;2;1;3] or [5;2;1;3]. Example 2: Input: root = [1;2] Output: 1 Constraints: The number of nodes in the tree is in the range [1; 104]. -100 <= Node.val <= 1001172Amazon,556,Next Greater Element III,Med,"Math, Two Pointers, String",Given a positive integer n; find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists; return -1. Note that the returned integer should fit in 32-bit integer; if there is a valid answer but it does not fit in 32-bit integer; return -1. Example 1: Input: n = 12 Output: 21 Example 2: Input: n = 21 Output: -1 Constraints: 1 <= n <= 231 - 11173Amazon,564,Find the Closest Palindrome,Hard,"Math, String","Given a string n representing an integer; return the closest integer (not including itself); which is a palindrome. If there is a tie; return the smaller one. The closest is defined as the absolute difference minimized between two integers. Example 1: Input: n = ""123"" Output: ""121"" Example 2: Input: n = ""1"" Output: ""0"" Explanation: 0 and 2 are the closest palindromes but we return the smallest which is 0. Constraints: 1 <= n.length <= 18 n consists of only digits. n does not have leading zeros. n is representing an integer in the range [1; 1018 - 1]."1174Amazon,570,Managers with at Least 5 Direct Reports,Med,Database,Table: Employee +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | | department | varchar | | managerId | int | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table indicates the name of an employee; their department; and the id of their manager. If managerId is null; then the employee does not have a manager. No employee will be the manager of themself. Write a solution to find managers with at least five direct reports. Return the result table in any order. The result format is in the following example. Example 1: Input: Employee table: +-----+-------+------------+-----------+ | id | name | department | managerId | +-----+-------+------------+-----------+ | 101 | John | A | null | | 102 | Dan | A | 101 | | 103 | James | A | 101 | | 104 | Amy | A | 101 | | 105 | Anne | A | 101 | | 106 | Ron | B | 101 | +-----+-------+------------+-----------+ Output: +------+ | name | +------+ | John | +------+1175Amazon,572,Subtree of Another Tree,Easy,"Tree, Depth-First Search, String Matching, Binary Tree, Hash Function",Given the roots of two binary trees root and subRoot; return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise. A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself. Example 1: Input: root = [3;4;5;1;2]; subRoot = [4;1;2] Output: true Example 2: Input: root = [3;4;5;1;2;null;null;null;null;0]; subRoot = [4;1;2] Output: false Constraints: The number of nodes in the root tree is in the range [1; 2000]. The number of nodes in the subRoot tree is in the range [1; 1000]. -104 <= root.val <= 104 -104 <= subRoot.val <= 1041176Amazon,636,Exclusive Time of Functions,Med,"Array, Stack","On a single-threaded CPU; we execute a program containing n functions. Each function has a unique ID between 0 and n-1. Function calls are stored in a call stack: when a function call starts; its ID is pushed onto the stack; and when a function call ends; its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed. Each time a function starts or ends; we write a log with the ID; whether it started or ended; and the timestamp. You are given a list logs; where logs[i] represents the ith log message formatted as a string ""{function_id}:{""start"" | ""end""}:{timestamp}"". For example; ""0:start:3"" means a function call with function ID 0 started at the beginning of timestamp 3; and ""1:end:2"" means a function call with function ID 1 ended at the end of timestamp 2. Note that a function can be called multiple times; possibly recursively. A function's exclusive time is the sum of execution times for all function calls in the program. For example; if a function is called twice; one call executing for 2 time units and another call executing for 1 time unit; the exclusive time is 2 + 1 = 3. Return the exclusive time of each function in an array; where the value at the ith index represents the exclusive time for the function with ID i. Example 1: Input: n = 2; logs = [""0:start:0"";""1:start:2"";""1:end:5"";""0:end:6""] Output: [3;4] Explanation: Function 0 starts at the beginning of time 0; then it executes 2 for units of time and reaches the end of time 1. Function 1 starts at the beginning of time 2; executes for 4 units of time; and ends at the end of time 5. Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time. So function 0 spends 2 + 1 = 3 units of total time executing; and function 1 spends 4 units of total time executing. Example 2: Input: n = 1; logs = [""0:start:0"";""0:start:2"";""0:end:5"";""0:start:6"";""0:end:6"";""0:end:7""] Output: [8] Explanation: Function 0 starts at the beginning of time 0; executes for 2 units of time; and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls itself again. Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time. Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time. So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing. Example 3: Input: n = 2; logs = [""0:start:0"";""0:start:2"";""0:end:5"";""1:start:6"";""1:end:6"";""0:end:7""] Output: [7;1] Explanation: Function 0 starts at the beginning of time 0; executes for 2 units of time; and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls function 1. Function 1 starts at the beginning of time 6; executes 1 unit of time; and ends at the end of time 6. Function 0 resumes execution at the beginning of time 6 and executes for 2 units of time. So function 0 spends 2 + 4 + 1 = 7 units of total time executing; and function 1 spends 1 unit of total time executing. Constraints: 1 <= n <= 100 1 <= logs.length <= 500 0 <= function_id < n 0 <= timestamp <= 109 No two start events will happen at the same timestamp. No two end events will happen at the same timestamp. Each function has an ""end"" log for each ""start"" log."1177Amazon,680,Valid Palindrome II,Easy,"Two Pointers, String, Greedy","Given a string s; return true if the s can be palindrome after deleting at most one character from it. Example 1: Input: s = ""aba"" Output: true Example 2: Input: s = ""abca"" Output: true Explanation: You could delete the character 'c'. Example 3: Input: s = ""abc"" Output: false Constraints: 1 <= s.length <= 105 s consists of lowercase English letters."1178Amazon,695,Max Area of Island,Med,"Array, Depth-First Search, Breadth-First Search, Union Find, Matrix",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. Example 1: Input: grid = [[0;0;1;0;0;0;0;1;0;0;0;0;0];[0;0;0;0;0;0;0;1;1;1;0;0;0];[0;1;1;0;1;0;0;0;0;0;0;0;0];[0;1;0;0;1;1;0;0;1;0;1;0;0];[0;1;0;0;1;1;0;0;1;1;1;0;0];[0;0;0;0;0;0;0;0;0;0;1;0;0];[0;0;0;0;0;0;0;1;1;1;0;0;0];[0;0;0;0;0;0;0;1;1;0;0;0;0]] Output: 6 Explanation: The answer is not 11; because the island must be connected 4-directionally. Example 2: Input: grid = [[0;0;0;0;0;0;0;0]] Output: 0 Constraints: m == grid.length n == grid[i].length 1 <= m; n <= 50 grid[i][j] is either 0 or 1.1179Amazon,752,Open the Lock,Med,"String, Bit Manipulation",1180Amazon,827,Making A Large Island,Hard,"Array, Two Pointers, String","Sometimes people repeat letters to represent extra feeling. For example: ""hello"" -> ""heeellooo"" ""hi"" -> ""hiiii"" In these strings like ""heeellooo""; we have groups of adjacent letters that are all the same: ""h""; ""eee""; ""ll""; ""ooo"". You are given a string s and an array of query strings words. A query word is stretchy if it can be made to be equal to s by any number of applications of the following extension operation: choose a group consisting of characters c; and add some number of characters c to the group so that the size of the group is three or more. For example; starting with ""hello""; we could do an extension on the group ""o"" to get ""hellooo""; but we cannot get ""helloo"" since the group ""oo"" has a size less than three. Also; we could do another extension like ""ll"" -> ""lllll"" to get ""helllllooo"". If s = ""helllllooo""; then the query word ""hello"" would be stretchy because of these two extension operations: query = ""hello"" -> ""hellooo"" -> ""helllllooo"" = s. Return the number of query strings that are stretchy. Example 1: Input: s = ""heeellooo""; words = [""hello""; ""hi""; ""helo""] Output: 1 Explanation: We can extend ""e"" and ""o"" in the word ""hello"" to get ""heeellooo"". We can't extend ""helo"" to get ""heeellooo"" because the group ""ll"" is not size 3 or more. Example 2: Input: s = ""zzzzzyyyyy""; words = [""zzyy"";""zy"";""zyy""] Output: 3 Constraints: 1 <= s.length; words.length <= 100 1 <= words[i].length <= 100 s and words[i] consist of lowercase letters."1181Amazon,622,Design Circular Queue,Med,,1182Amazon,862,Shortest Subarray with Sum at Least K,Hard,"Array, Hash Table, String, Sorting","You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays; indices; sources; and targets; all of length k. To complete the ith replacement operation: Check if the substring sources[i] occurs at index indices[i] in the original string s. If it does not occur; do nothing. Otherwise if it does occur; replace that substring with targets[i]. For example; if s = ""abcd""; indices[i] = 0; sources[i] = ""ab""; and targets[i] = ""eee""; then the result of this replacement will be ""eeecd"". All replacement operations must occur simultaneously; meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap. For example; a testcase with s = ""abc""; indices = [0; 1]; and sources = [""ab"";""bc""] will not be generated because the ""ab"" and ""bc"" replacements overlap. Return the resulting string after performing all replacement operations on s. A substring is a contiguous sequence of characters in a string. Example 1: Input: s = ""abcd""; indices = [0; 2]; sources = [""a""; ""cd""]; targets = [""eee""; ""ffff""] Output: ""eeebffff"" Explanation: ""a"" occurs at index 0 in s; so we replace it with ""eee"". ""cd"" occurs at index 2 in s; so we replace it with ""ffff"". Example 2: Input: s = ""abcd""; indices = [0; 2]; sources = [""ab"";""ec""]; targets = [""eee"";""ffff""] Output: ""eeecd"" Explanation: ""ab"" occurs at index 0 in s; so we replace it with ""eee"". ""ec"" does not occur at index 2 in s; so we do nothing. Constraints: 1 <= s.length <= 1000 k == indices.length == sources.length == targets.length 1 <= k <= 100 0 <= indexes[i] < s.length 1 <= sources[i].length; targets[i].length <= 50 s consists of only lowercase English letters. sources[i] and targets[i] consist of only lowercase English letters."1183Amazon,871,Minimum Number of Refueling Stops,Hard,"Depth-First Search, Breadth-First Search, Graph",There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However; you cannot enter a locked room without having its key. When you visit a room; you may find a set of distinct keys in it. Each key has a number on it; denoting which room it unlocks; and you can take all of them with you to unlock the other rooms. Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i; return true if you can visit all the rooms; or false otherwise. Example 1: Input: rooms = [[1];[2];[3];[]] Output: true Explanation: We visit room 0 and pick up key 1. We then visit room 1 and pick up key 2. We then visit room 2 and pick up key 3. We then visit room 3. Since we were able to visit every room; we return true. Example 2: Input: rooms = [[1;3];[3;0;1];[2];[0]] Output: false Explanation: We can not enter room number 2 since the only key that unlocks it is in that room. Constraints: n == rooms.length 2 <= n <= 1000 0 <= rooms[i].length <= 1000 1 <= sum(rooms[i].length) <= 3000 0 <= rooms[i][j] < n All the values of rooms[i] are unique.1184Amazon,904,Fruit Into Baskets,Med,"Tree, Depth-First Search, Binary Tree",Consider all the leaves of a binary tree; from left to right order; the values of those leaves form a leaf value sequence. For example; in the given tree above; the leaf value sequence is (6; 7; 4; 9; 8). Two binary trees are considered leaf-similar if their leaf value sequence is the same. Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar. Example 1: Input: root1 = [3;5;1;6;2;9;8;null;null;7;4]; root2 = [3;5;1;6;7;4;2;null;null;null;null;null;null;9;8] Output: true Example 2: Input: root1 = [1;2;3]; root2 = [1;3;2] Output: false Constraints: The number of nodes in each tree will be in the range [1; 200]. Both of the given trees will have values in the range [0; 200].1185Amazon,934,Shortest Bridge,Med,"Array, Dynamic Programming, Bit Manipulation",Given an integer array arr; return the number of distinct bitwise ORs of all the non-empty subarrays of arr. The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: arr = [0] Output: 1 Explanation: There is only one possible result: 0. Example 2: Input: arr = [1;1;2] Output: 3 Explanation: The possible subarrays are [1]; [1]; [2]; [1; 1]; [1; 2]; [1; 1; 2]. These yield the results 1; 1; 2; 1; 3; 3. There are 3 unique values; so the answer is 3. Example 3: Input: arr = [1;2;4] Output: 6 Explanation: The possible results are 1; 2; 3; 4; 6; and 7. Constraints: 1 <= arr.length <= 5 * 104 0 <= arr[i] <= 1091186Amazon,953,Verifying an Alien Dictionary,Easy,"Two Pointers, String","Given a string s; reverse the string according to the following rules: All the characters that are not English letters remain in the same position. All the English letters (lowercase or uppercase) should be reversed. Return s after reversing it. Example 1: Input: s = ""ab-cd"" Output: ""dc-ba"" Example 2: Input: s = ""a-bC-dEf-ghIj"" Output: ""j-Ih-gfE-dCba"" Example 3: Input: s = ""Test1ng-Leet=code-Q!"" Output: ""Qedo1ct-eeLg=ntse-T!"" Constraints: 1 <= s.length <= 100 s consists of characters with ASCII values in the range [33; 122]. s does not contain '\""' or '\\'."1187Amazon,968,Binary Tree Cameras,Hard,"Array, Math, Divide and Conquer",An array nums of length n is beautiful if: nums is a permutation of the integers in the range [1; n]. For every 0 <= i < j < n; there is no index k with i < k < j where 2 * nums[k] == nums[i] + nums[j]. Given the integer n; return any beautiful array nums of length n. There will be at least one valid answer for the given n. Example 1: Input: n = 4 Output: [2;1;4;3] Example 2: Input: n = 5 Output: [3;1;2;5;4] Constraints: 1 <= n <= 10001188Amazon,1143,Longest Common Subsequence,Med,"Array, Hash Table, Binary Search, Matrix, Counting",1189Amazon,1148,Article Views I,Easy,"Array, Math",Given two numbers arr1 and arr2 in base -2; return the result of adding them together. Each number is given in array format: as an array of 0s and 1s; from most significant bit to least significant bit. For example; arr = [1;1;0;1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3. A number arr in array; format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1. Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros. Example 1: Input: arr1 = [1;1;1;1;1]; arr2 = [1;0;1] Output: [1;0;0;0;0] Explanation: arr1 represents 11; arr2 represents 5; the output represents 16. Example 2: Input: arr1 = [0]; arr2 = [0] Output: [0] Example 3: Input: arr1 = [0]; arr2 = [1] Output: [1] Constraints: 1 <= arr1.length; arr2.length <= 1000 arr1[i] and arr2[i] are 0 or 1 arr1 and arr2 have no leading zeros1190Amazon,1174,Immediate Food Delivery II,Med,Database,Table: Product +--------------+---------+ | Column Name | Type | +--------------+---------+ | product_id | int | | product_name | varchar | | unit_price | int | +--------------+---------+ product_id is the primary key (column with unique values) of this table. Each row of this table indicates the name and the price of each product. Table: Sales +-------------+---------+ | Column Name | Type | +-------------+---------+ | seller_id | int | | product_id | int | | buyer_id | int | | sale_date | date | | quantity | int | | price | int | +-------------+---------+ This table can have duplicate rows. product_id is a foreign key (reference column) to the Product table. Each row of this table contains some information about one sale. Write a solution to report the products that were only sold in the first quarter of 2019. That is; between 2019-01-01 and 2019-03-31 inclusive. Return the result table in any order. The result format is in the following example. Example 1: Input: Product table: +------------+--------------+------------+ | product_id | product_name | unit_price | +------------+--------------+------------+ | 1 | S8 | 1000 | | 2 | G4 | 800 | | 3 | iPhone | 1400 | +------------+--------------+------------+ Sales table: +-----------+------------+----------+------------+----------+-------+ | seller_id | product_id | buyer_id | sale_date | quantity | price | +-----------+------------+----------+------------+----------+-------+ | 1 | 1 | 1 | 2019-01-21 | 2 | 2000 | | 1 | 2 | 2 | 2019-02-17 | 1 | 800 | | 2 | 2 | 3 | 2019-06-02 | 1 | 800 | | 3 | 3 | 4 | 2019-05-13 | 2 | 2800 | +-----------+------------+----------+------------+----------+-------+ Output: +-------------+--------------+ | product_id | product_name | +-------------+--------------+ | 1 | S8 | +-------------+--------------+ Explanation: The product with id 1 was only sold in the spring of 2019. The product with id 2 was sold in the spring of 2019 but was also sold after the spring of 2019. The product with id 3 was sold after spring 2019. We return only product 1 as it is the product that was only sold in the spring of 2019.1191Amazon,1429,First Unique Number,Med,"Array, Math, String, Backtracking","Given an equation; represented by words on the left side and the result on the right side. You need to check if the equation is solvable under the following rules: Each character is decoded as one digit (0 - 9). No two characters can map to the same digit. Each words[i] and result are decoded as one number without leading zeros. Sum of numbers on the left side (words) will equal to the number on the right side (result). Return true if the equation is solvable; otherwise return false. Example 1: Input: words = [""SEND"";""MORE""]; result = ""MONEY"" Output: true Explanation: Map 'S'-> 9; 'E'->5; 'N'->6; 'D'->7; 'M'->1; 'O'->0; 'R'->8; 'Y'->'2' Such that: ""SEND"" + ""MORE"" = ""MONEY"" ; 9567 + 1085 = 10652 Example 2: Input: words = [""SIX"";""SEVEN"";""SEVEN""]; result = ""TWENTY"" Output: true Explanation: Map 'S'-> 6; 'I'->5; 'X'->0; 'E'->8; 'V'->7; 'N'->2; 'T'->1; 'W'->'3'; 'Y'->4 Such that: ""SIX"" + ""SEVEN"" + ""SEVEN"" = ""TWENTY"" ; 650 + 68782 + 68782 = 138214 Example 3: Input: words = [""LEET"";""CODE""]; result = ""POINT"" Output: false Explanation: There is no possible mapping to satisfy the equation; so we return false. Note that two different characters cannot map to the same digit. Constraints: 2 <= words.length <= 5 1 <= words[i].length; result.length <= 7 words[i]; result contain only uppercase English letters. The number of different characters used in the expression is at most 10."1192Amazon,1497,Check If Array Pairs Are Divisible by k,Med,"Array, Stack, Design","Design a stack that supports increment operations on its elements. Implement the CustomStack class: CustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack. void push(int x) Adds x to the top of the stack if the stack has not reached the maxSize. int pop() Pops and returns the top of the stack or -1 if the stack is empty. void inc(int k; int val) Increments the bottom k elements of the stack by val. If there are less than k elements in the stack; increment all the elements in the stack. Example 1: Input [""CustomStack"";""push"";""push"";""pop"";""push"";""push"";""push"";""increment"";""increment"";""pop"";""pop"";""pop"";""pop""] [[3];[1];[2];[];[2];[3];[4];[5;100];[2;100];[];[];[];[]] Output [null;null;null;2;null;null;null;null;null;103;202;201;-1] Explanation CustomStack stk = new CustomStack(3); // Stack is Empty [] stk.push(1); // stack becomes [1] stk.push(2); // stack becomes [1; 2] stk.pop(); // return 2 --> Return top of the stack 2; stack becomes [1] stk.push(2); // stack becomes [1; 2] stk.push(3); // stack becomes [1; 2; 3] stk.push(4); // stack still [1; 2; 3]; Do not add another elements as size is 4 stk.increment(5; 100); // stack becomes [101; 102; 103] stk.increment(2; 100); // stack becomes [201; 202; 103] stk.pop(); // return 103 --> Return top of the stack 103; stack becomes [201; 202] stk.pop(); // return 202 --> Return top of the stack 202; stack becomes [201] stk.pop(); // return 201 --> Return top of the stack 201; stack becomes [] stk.pop(); // return -1 --> Stack is empty return -1. Constraints: 1 <= maxSize; x; k <= 1000 0 <= val <= 100 At most 1000 calls will be made to each method of increment; push and pop each separately."1193Amazon,1552,Magnetic Force Between Two Balls,Med,"Array, Stack, Simulation","You are given an integer array target and an integer n. You have an empty stack with the two following operations: ""Push"": pushes an integer to the top of the stack. ""Pop"": removes the integer on the top of the stack. You also have a stream of the integers in the range [1; n]. Use the two stack operations to make the numbers in the stack (from the bottom to the top) equal to target. You should follow the following rules: If the stream of the integers is not empty; pick the next integer from the stream and push it to the top of the stack. If the stack is not empty; pop the integer at the top of the stack. If; at any moment; the elements in the stack (from the bottom to the top) are equal to target; do not read new integers from the stream and do not do more operations on the stack. Return the stack operations needed to build target following the mentioned rules. If there are multiple valid answers; return any of them. Example 1: Input: target = [1;3]; n = 3 Output: [""Push"";""Push"";""Pop"";""Push""] Explanation: Initially the stack s is empty. The last element is the top of the stack. Read 1 from the stream and push it to the stack. s = [1]. Read 2 from the stream and push it to the stack. s = [1;2]. Pop the integer on the top of the stack. s = [1]. Read 3 from the stream and push it to the stack. s = [1;3]. Example 2: Input: target = [1;2;3]; n = 3 Output: [""Push"";""Push"";""Push""] Explanation: Initially the stack s is empty. The last element is the top of the stack. Read 1 from the stream and push it to the stack. s = [1]. Read 2 from the stream and push it to the stack. s = [1;2]. Read 3 from the stream and push it to the stack. s = [1;2;3]. Example 3: Input: target = [1;2]; n = 4 Output: [""Push"";""Push""] Explanation: Initially the stack s is empty. The last element is the top of the stack. Read 1 from the stream and push it to the stack. s = [1]. Read 2 from the stream and push it to the stack. s = [1;2]. Since the stack (from the bottom to the top) is equal to target; we stop the stack operations. The answers that read integer 3 from the stream are not accepted. Constraints: 1 <= target.length <= 100 1 <= n <= 100 1 <= target[i] <= n target is strictly increasing."1194Amazon,1590,Make Sum Divisible by P,Med,,1195Amazon,1603,Design Parking System,Easy,"Array, Prefix Sum",Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums. Example 1: Input: nums = [1;2;3;4] Output: [1;3;6;10] Explanation: Running sum is obtained as follows: [1; 1+2; 1+2+3; 1+2+3+4]. Example 2: Input: nums = [1;1;1;1;1] Output: [1;2;3;4;5] Explanation: Running sum is obtained as follows: [1; 1+1; 1+1+1; 1+1+1+1; 1+1+1+1+1]. Example 3: Input: nums = [3;1;2;10;1] Output: [3;4;6;16;17] Constraints: 1 <= nums.length <= 1000 -10^6 <= nums[i] <= 10^61196Amazon,1731,The Number of Employees Which Report to Each Employee,Easy,"Tree, Breadth-First Search, Binary Tree",A binary tree is named Even-Odd if it meets the following conditions: The root of the binary tree is at level index 0; its children are at level index 1; their children are at level index 2; etc. For every even-indexed level; all nodes at the level have odd integer values in strictly increasing order (from left to right). For every odd-indexed level; all nodes at the level have even integer values in strictly decreasing order (from left to right). Given the root of a binary tree; return true if the binary tree is Even-Odd; otherwise return false. Example 1: Input: root = [1;10;4;3;null;7;9;12;8;6;null;null;2] Output: true Explanation: The node values on each level are: Level 0: [1] Level 1: [10;4] Level 2: [3;7;9] Level 3: [12;8;6;2] Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing; the tree is Even-Odd. Example 2: Input: root = [5;4;2;3;3;7] Output: false Explanation: The node values on each level are: Level 0: [5] Level 1: [4;2] Level 2: [3;3;7] Node values in level 2 must be in strictly increasing order; so the tree is not Even-Odd. Example 3: Input: root = [5;9;1;3;5;7] Output: false Explanation: Node values in the level 1 should be even integers. Constraints: The number of nodes in the tree is in the range [1; 105]. 1 <= Node.val <= 1061197Amazon,2275,Largest Combination With Bitwise AND Greater Than Zero,Med,"String, Sliding Window, Rolling Hash, Hash Function","The hash of a 0-indexed string s of length k; given integers p and m; is computed using the following function: hash(s; p; m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m. Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26. You are given a string s and the integers power; modulo; k; and hashValue. Return sub; the first substring of s of length k such that hash(sub; power; modulo) == hashValue. The test cases will be generated such that an answer always exists. A substring is a contiguous non-empty sequence of characters within a string. Example 1: Input: s = ""leetcode""; power = 7; modulo = 20; k = 2; hashValue = 0 Output: ""ee"" Explanation: The hash of ""ee"" can be computed to be hash(""ee""; 7; 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0. ""ee"" is the first substring of length 2 with hashValue 0. Hence; we return ""ee"". Example 2: Input: s = ""fbxzaad""; power = 31; modulo = 100; k = 3; hashValue = 32 Output: ""fbx"" Explanation: The hash of ""fbx"" can be computed to be hash(""fbx""; 31; 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32. The hash of ""bxz"" can be computed to be hash(""bxz""; 31; 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32. ""fbx"" is the first substring of length 3 with hashValue 32. Hence; we return ""fbx"". Note that ""bxz"" also has a hash of 32 but it appears later than ""fbx"". Constraints: 1 <= k <= s.length <= 2 * 104 1 <= power; modulo <= 109 0 <= hashValue < modulo s consists of lowercase English letters only. The test cases are generated such that an answer always exists."1198Amazon,2491,Divide Players Into Teams of Equal Skill,Med,"Math, Number Theory",Given a positive integer n; return the smallest positive integer that is a multiple of both 2 and n. Example 1: Input: n = 5 Output: 10 Explanation: The smallest multiple of both 5 and 2 is 10. Example 2: Input: n = 6 Output: 6 Explanation: The smallest multiple of both 6 and 2 is 6. Note that a number is a multiple of itself. Constraints: 1 <= n <= 1501199Amazon,2530,Maximal Score After Applying K Operations,Med,"Array, Binary Search, Dynamic Programming, Greedy, Prefix Sum",You are given a 0-indexed array nums comprising of n non-negative integers. In one operation; you must: Choose an integer i such that 1 <= i < n and nums[i] > 0. Decrease nums[i] by 1. Increase nums[i - 1] by 1. Return the minimum possible value of the maximum integer of nums after performing any number of operations. Example 1: Input: nums = [3;7;1;6] Output: 5 Explanation: One set of optimal operations is as follows: 1. Choose i = 1; and nums becomes [4;6;1;6]. 2. Choose i = 3; and nums becomes [4;6;2;5]. 3. Choose i = 1; and nums becomes [5;5;2;5]. The maximum integer of nums is 5. It can be shown that the maximum number cannot be less than 5. Therefore; we return 5. Example 2: Input: nums = [10;1] Output: 10 Explanation: It is optimal to leave nums as is; and since 10 is the maximum value; we return 10. Constraints: n == nums.length 2 <= n <= 105 0 <= nums[i] <= 1091200Amazon,2707,Extra Characters in a String,Med,"Array, Hash Table, Two Pointers",You are given two 2D integer arrays nums1 and nums2. nums1[i] = [idi; vali] indicate that the number with the id idi has a value equal to vali. nums2[i] = [idi; vali] indicate that the number with the id idi has a value equal to vali. Each array contains unique ids and is sorted in ascending order by id. Merge the two arrays into one array that is sorted in ascending order by id; respecting the following conditions: Only ids that appear in at least one of the two arrays should be included in the resulting array. Each id should be included only once and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays then its value in that array is considered to be 0. Return the resulting array. The returned array must be sorted in ascending order by id. Example 1: Input: nums1 = [[1;2];[2;3];[4;5]]; nums2 = [[1;4];[3;2];[4;1]] Output: [[1;6];[2;3];[3;2];[4;6]] Explanation: The resulting array contains the following: - id = 1; the value of this id is 2 + 4 = 6. - id = 2; the value of this id is 3. - id = 3; the value of this id is 2. - id = 4; the value of this id is 5 + 1 = 6. Example 2: Input: nums1 = [[2;4];[3;6];[5;5]]; nums2 = [[1;3];[4;3]] Output: [[1;3];[2;4];[3;6];[4;3];[5;5]] Explanation: There are no common ids; so we just include each id with its value in the resulting list. Constraints: 1 <= nums1.length; nums2.length <= 200 nums1[i].length == nums2[j].length == 2 1 <= idi; vali <= 1000 Both arrays contain unique ids. Both arrays are in strictly ascending order by id.

Showing the first 1,200 of 4079 lines. Download the file for the rest.