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:
+ +[1, 100].0 <= Node.val <= 9Given 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 * 104s consists of English letters, digits, symbols and spaces.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 <= 1000s consist of only digits and English letters.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 <= 1000s consists of English letters (lower-case and upper-case), ',' and '.'.1 <= numRows <= 1000Given 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 - 1Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).
The algorithm for myAtoi(string s) is as follows:
'-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present."123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).[-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.Note:
+ +' ' is considered a whitespace character.+
Example 1:
+ +Input: s = "42"
+Output: 42
+Explanation: The underlined characters are what is read in, 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)
+ ^
+The parsed integer is 42.
+Since 42 is in the range [-231, 231 - 1], the final result is 42.
+
+
+Example 2:
+ +Input: s = " -42"
+Output: -42
+Explanation:
+Step 1: " -42" (leading whitespace is read and ignored)
+ ^
+Step 2: " -42" ('-' is read, so the result should be negative)
+ ^
+Step 3: " -42" ("42" is read in)
+ ^
+The parsed integer is -42.
+Since -42 is in the range [-231, 231 - 1], the final result is -42.
+
+
+Example 3:
+ +Input: s = "4193 with words"
+Output: 4193
+Explanation:
+Step 1: "4193 with words" (no characters read because there is no leading whitespace)
+ ^
+Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+')
+ ^
+Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit)
+ ^
+The parsed integer is 4193.
+Since 4193 is in the range [-231, 231 - 1], the final result is 4193.
+
+
++
Constraints:
+ +0 <= s.length <= 200s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.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.length2 <= n <= 1050 <= height[i] <= 104Roman 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 one's 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 an integer, convert it to a roman numeral.
+ ++
Example 1:
+ +Input: num = 3 +Output: "III" +Explanation: 3 is represented as 3 ones. ++ +
Example 2:
+ +Input: num = 58 +Output: "LVIII" +Explanation: L = 50, V = 5, III = 3. ++ +
Example 3:
+ +Input: num = 1994 +Output: "MCMXCIV" +Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. ++ +
+
Constraints:
+ +1 <= num <= 3999Given 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] <= 105Given 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 <= 104Given 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 <= 4digits[i] is a digit in the range ['2', '9'].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 < na, b, c, and d are distinct.nums[a] + nums[b] + nums[c] + nums[d] == targetYou 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 <= 109Given 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:
+ +sz.1 <= sz <= 300 <= Node.val <= 1001 <= n <= sz+
Follow up: Could you do this in one pass?
+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 <= 8Given 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] ++ +
Example 2:
+ +Input: head = [] +Output: [] ++ +
Example 3:
+ +Input: head = [1] +Output: [1] ++ +
+
Constraints:
+ +[0, 100].0 <= Node.val <= 100Given 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 - 1divisor != 0A permutation of an array of integers is an arrangement of its members into a sequence or linear order.
+ +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).
+ +arr = [1,2,3] is [1,3,2].arr = [2,3,1] is [3,1,2].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 <= 1000 <= nums[i] <= 100There 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] <= 104nums are unique.nums is an ascending array that is possibly rotated.-104 <= target <= 104Given 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] <= 109nums is a non-decreasing array.-109 <= target <= 109Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
1-9 without repetition.1-9 without repetition.3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.Note:
+ ++
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 == 9board[i].length == 9board[i][j] is a digit 1-9 or '.'.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 <= 302 <= candidates[i] <= 40candidates are distinct.1 <= target <= 40Given 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 <= 1001 <= candidates[i] <= 501 <= target <= 30You 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] andi + j < nReturn 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 <= 1040 <= nums[i] <= 1000nums[n - 1].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] <= 10nums are unique.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].length1 <= n <= 20-1000 <= matrix[i][j] <= 1000Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
+ ++
Example 1:
+Input: strs = ["eat","tea","tan","ate","nat","bat"] +Output: [["bat"],["nat","tan"],["ate","eat","tea"]] +
Example 2:
+Input: strs = [""] +Output: [[""]] +
Example 3:
+Input: strs = ["a"] +Output: [["a"]] ++
+
Constraints:
+ +1 <= strs.length <= 1040 <= strs[i].length <= 100strs[i] consists of lowercase English letters.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-1n is an integer.x is not zero or n > 0.-104 <= xn <= 104Given 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.
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.lengthn == matrix[i].length1 <= m, n <= 10-100 <= matrix[i][j] <= 100Given 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 <= 104intervals[i].length == 20 <= starti <= endi <= 104You 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.
+
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 <= 104intervals[i].length == 20 <= starti <= endi <= 105intervals is sorted by starti in ascending order.newInterval.length == 20 <= start <= end <= 105Given 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:
+ +[0, 500].-100 <= Node.val <= 1000 <= k <= 2 * 109There 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 <= 100Given 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.lengthn == grid[i].length1 <= m, n <= 2000 <= grid[i][j] <= 200Given 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.lengthn == matrix[0].length1 <= m, n <= 200-231 <= matrix[i][j] <= 231 - 1+
Follow up:
+ +O(mn) space is probably a bad idea.O(m + n) space, but still not the best solution.You are given an m x n integer matrix matrix with the following two properties:
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.lengthn == matrix[i].length1 <= m, n <= 100-104 <= matrix[i][j], target <= 104Given 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.length1 <= n <= 300nums[i] is either 0, 1, or 2.+
Follow up: Could you come up with a one-pass algorithm using only constant extra space?
+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 <= 201 <= k <= nGiven 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] <= 10nums are unique.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.lengthn = board[i].length1 <= m, n <= 61 <= word.length <= 15board 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?
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] <= 104nums 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?
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:
+ +[0, 200].-100 <= Node.val <= 100-200 <= x <= 200Given 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] <= 10A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1" +'B' -> "2" +... +'Z' -> "26" ++ +
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
"AAJF" with the grouping (1 1 10 6)"KJF" with the grouping (11 10 6)Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
Given a string s containing only digits, return the number of ways to decode it.
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").
+
+
++
Constraints:
+ +1 <= s.length <= 100s contains only digits and may contain leading zero(s).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:
+ +n.1 <= n <= 500-500 <= Node.val <= 5001 <= left <= right <= n+Follow up: Could you do it in one pass?
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
+ ++
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:
+ +[1, 104].-231 <= Node.val <= 231 - 1Given 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:
+ +[0, 2000].-1000 <= Node.val <= 1000Given 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 <= 3000inorder.length == preorder.length-3000 <= preorder[i], inorder[i] <= 3000preorder and inorder consist of unique values.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.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 <= 200triangle[0].length == 1triangle[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?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] <= 109You 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.
+ +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->2represents the number12. +The root-to-leaf path1->3represents the number13. +Therefore, sum = 12 + 13 =25. +
Example 2:
+
+Input: root = [4,9,0,5,1] +Output: 1026 +Explanation: +The root-to-leaf path+ +4->9->5represents the number 495. +The root-to-leaf path4->9->1represents the number 491. +The root-to-leaf path4->0represents the number 40. +Therefore, sum = 495 + 491 + 40 =1026. +
+
Constraints:
+ +[1, 1000].0 <= Node.val <= 910.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 <= 16s contains only lowercase English letters.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:
+ +[0, 100].1 <= Node.val <= 100Node.val is unique for each node.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 - 1nums appears exactly three times except for one element which appears once.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.valrandom_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 <= 104Node.random is null or is pointing to some node in the linked list.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 <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20s and wordDict[i] consist of only lowercase English letters.wordDict are unique.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:
+ +[1, 5 * 104].1 <= Node.val <= 1000Design 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 <= 30000 <= key <= 1040 <= value <= 1052 * 105 calls will be made to get and put.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:
+ +[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)?
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:
+ +'+', '-', '*', and '/'.+
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 <= 104tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].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.length1 <= n <= 5000-5000 <= nums[i] <= 5000nums are unique.nums is sorted and rotated between 1 and n times.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 - 1pop, top and getMin operations will always be called on non-empty stacks.3 * 104 calls will be made to push, pop, top, and getMin.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 - 1nums[i] != nums[i + 1] for all valid i.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] <= 1000numbers is sorted in non-decreasing order.-1000 <= target <= 1000Given 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 - 10 <= k <= 105+
Follow up:
+ +O(1) extra space?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 <= 1000 <= nums[i] <= 400Given 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.lengthn == grid[i].length1 <= m, n <= 300grid[i][j] is '0' or '1'.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.
[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 <= 20000 <= prerequisites.length <= 5000prerequisites[i].length == 20 <= ai, bi < numCoursesA 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 <= 2000word and prefix consist only of lowercase English letters.3 * 104 calls in total will be made to insert, search, and startsWith.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] <= 104Given 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?
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:
+ +n.1 <= k <= n <= 1040 <= 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?
+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:
+ +[2, 105].-109 <= Node.val <= 109Node.val are unique.p != qp and q will exist in the BST.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:
+ +[2, 105].-109 <= Node.val <= 109Node.val are unique.p != qp and q will exist in the tree.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:
+ +node should be in the same order.node should be in the same order.Custom testing:
+ +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.+
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:
+ +[2, 1000].-1000 <= Node.val <= 1000node to be deleted is in the list and is not a tail node.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] <= 30nums 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.)
Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.
+
Example 1:
+Input: intervals = [[0,30],[5,10],[15,20]] +Output: 2 +
Example 2:
+Input: intervals = [[7,10],[2,4]] +Output: 1 ++
+
Constraints:
+ +1 <= intervals.length <= 1040 <= starti < endi <= 106Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.
You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.
+ ++
Example 1:
+ +Input: nums = [1,2,1,3,2,5] +Output: [3,5] +Explanation: [5, 3] is also a valid answer. ++ +
Example 2:
+ +Input: nums = [-1,0] +Output: [-1,0] ++ +
Example 3:
+ +Input: nums = [0,1] +Output: [1,0] ++ +
+
Constraints:
+ +2 <= nums.length <= 3 * 104-231 <= nums[i] <= 231 - 1nums will appear twice, only two integers will appear once.An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
Given an integer n, return the nth ugly number.
+
Example 1:
+ +Input: n = 10 +Output: 12 +Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers. ++ +
Example 2:
+ +Input: n = 1 +Output: 1 +Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. ++ +
+
Constraints:
+ +1 <= n <= 1690Given 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 <= 104Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
There is only one repeated number in nums, return this repeated number.
You must solve the problem without modifying the array nums and uses only constant extra space.
+
Example 1:
+ +Input: nums = [1,3,4,2,2] +Output: 2 ++ +
Example 2:
+ +Input: nums = [3,1,3,4,2] +Output: 3 ++ +
+
Constraints:
+ +1 <= n <= 105nums.length == n + 11 <= nums[i] <= nnums appear only once except for precisely one integer which appears two or more times.+
Follow up:
+ +nums?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?
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 * 104edges.length == n - 10 <= ai, bi < nai != bi(ai, bi) are distinct.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 <= 104s consists of lowercase English letters.+
Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
+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 <= 121 <= coins[i] <= 231 - 10 <= amount <= 104Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.
+
Example 1:
+ +Input: s = "eceba", k = 2 +Output: 3 +Explanation: The substring is "ece" with length 3.+ +
Example 2:
+ +Input: s = "aa", k = 1 +Output: 2 +Explanation: The substring is "aa" with length 2. ++ +
+
Constraints:
+ +1 <= s.length <= 5 * 1040 <= k <= 50Given 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] <= 104k is in the range [1, the number of unique elements in the array].+
Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:
answer[i] % answer[j] == 0, oranswer[j] % answer[i] == 0If there are multiple solutions, return any of them.
+ ++
Example 1:
+ +Input: nums = [1,2,3] +Output: [1,2] +Explanation: [1,3] is also accepted. ++ +
Example 2:
+ +Input: nums = [1,2,4,8] +Output: [1,2,4,8] ++ +
+
Constraints:
+ +1 <= nums.length <= 10001 <= nums[i] <= 2 * 109nums are unique.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 - 12 * 105 calls will be made to insert, remove, and getRandom.getRandom is called.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 <= 105num consists of only digits.num does not have any leading zeros except for the zero itself.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 <= 2001 <= nums[i] <= 100Given 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.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
+ ++
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 * 104s and p consist of lowercase English letters.Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or 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 extra space.
+
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.length1 <= n <= 1051 <= nums[i] <= nnums appears once or twice.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 * 105s consists of uppercase and lowercase English letters and digits.Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].
Return true if there is a 132 pattern in nums, otherwise, return false.
+
Example 1:
+ +Input: nums = [1,2,3,4] +Output: false +Explanation: There is no 132 pattern in the sequence. ++ +
Example 2:
+ +Input: nums = [3,1,4,2] +Output: true +Explanation: There is a 132 pattern in the sequence: [1, 4, 2]. ++ +
Example 3:
+ +Input: nums = [-1,3,2,0] +Output: true +Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. ++ +
+
Constraints:
+ +n == nums.length1 <= n <= 2 * 105-109 <= nums[i] <= 109You 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 <= 3001 <= coins[i] <= 5000coins are unique.0 <= amount <= 5000Given 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:
+ +k.Note that:
+ +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 <= 1050 <= nums[i] <= 1090 <= sum(nums[i]) <= 231 - 11 <= k <= 231 - 1Given 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 <= 105nums[i] is either 0 or 1.Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array.
A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:
0 <= i, j < nums.lengthi != j|nums[i] - nums[j]| == kNotice that |val| denotes the absolute value of val.
+
Example 1:
+ +Input: nums = [3,1,4,1,5], k = 2 +Output: 2 +Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). +Although we have two 1s in the input, we should only return the number of unique pairs. ++ +
Example 2:
+ +Input: nums = [1,2,3,4,5], k = 1 +Output: 4 +Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). ++ +
Example 3:
+ +Input: nums = [1,3,1,5,4], k = 0 +Output: 1 +Explanation: There is one 0-diff pair in the array, (1, 1). ++ +
+
Constraints:
+ +1 <= nums.length <= 104-107 <= nums[i] <= 1070 <= k <= 107You 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 <= 1050 <= nums[i] <= 105Given 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.lengthn == mat[i].length1 <= m, n <= 1041 <= m * n <= 104mat[i][j] is either 0 or 1.0 in mat.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 <= 104s1 and s2 consist of lowercase English letters.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:
+ +'0' to '9', '/', '+' and '-'. So does the output.±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.[1, 10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.[1, 10].Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.
Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.
+ ++
Example 1:
+
+Input: root = [1,2,3,4] +Output: "1(2(4))(3)" +Explanation: Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3)" ++ +
Example 2:
+
+Input: root = [1,2,3,null,4] +Output: "1(2()(4))(3)" +Explanation: Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output. ++ +
+
Constraints:
+ +[1, 104].-1000 <= Node.val <= 1000You are given an array of CPU tasks, each represented by letters A to Z, and a cooling time, n. Each cycle or interval allows the completion of one task. Tasks can be completed in any order, but there's a constraint: identical tasks must be separated by at least n intervals due to cooling time.
Return the minimum number of 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 cycles 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 cycle, 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 <= 104tasks[i] is an uppercase English letter.0 <= n <= 100You are given m arrays, where each array is sorted in ascending order.
You can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers a and b to be their absolute difference |a - b|.
Return the maximum distance.
+ ++
Example 1:
+ +Input: arrays = [[1,2,3],[4,5],[1,2,3]] +Output: 4 +Explanation: One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array. ++ +
Example 2:
+ +Input: arrays = [[1],[1]] +Output: 0 ++ +
+
Constraints:
+ +m == arrays.length2 <= m <= 1051 <= arrays[i].length <= 500-104 <= arrays[i][j] <= 104arrays[i] is sorted in ascending order.105 integers in all the arrays.Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.
+
Example 1:
+ +Input: c = 5 +Output: true +Explanation: 1 * 1 + 2 * 2 = 5 ++ +
Example 2:
+ +Input: c = 3 +Output: false ++ +
+
Constraints:
+ +0 <= c <= 231 - 1You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.
A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.
Return the length longest chain which can be formed.
+ +You do not need to use up all the given intervals. You can select pairs in any order.
+ ++
Example 1:
+ +Input: pairs = [[1,2],[2,3],[3,4]] +Output: 2 +Explanation: The longest chain is [1,2] -> [3,4]. ++ +
Example 2:
+ +Input: pairs = [[1,2],[7,8],[4,5]] +Output: 3 +Explanation: The longest chain is [1,2] -> [4,5] -> [7,8]. ++ +
+
Constraints:
+ +n == pairs.length1 <= n <= 1000-1000 <= lefti < righti <= 1000Given 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 <= 1000s consists of lowercase English letters.In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word derivative. For example, when the root "help" is followed by the word "ful", we can form a derivative "helpful".
Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the derivatives in the sentence with the root forming it. If a derivative can be replaced by more than one root, replace it with the root that has the shortest length.
Return the sentence after the replacement.
+
Example 1:
+ +Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery" +Output: "the cat was rat by the bat" ++ +
Example 2:
+ +Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs" +Output: "a a b c" ++ +
+
Constraints:
+ +1 <= dictionary.length <= 10001 <= dictionary[i].length <= 100dictionary[i] consists of only lower-case letters.1 <= sentence.length <= 106sentence consists of only lower-case letters and spaces.sentence is in the range [1, 1000]sentence is in the range [1, 1000]sentence will be separated by exactly one space.sentence does not have leading or trailing spaces.There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step:
Given an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen.
+
Example 1:
+ +Input: n = 3 +Output: 3 +Explanation: Initially, we have one character 'A'. +In step 1, we use Copy All operation. +In step 2, we use Paste operation to get 'AA'. +In step 3, we use Paste operation to get 'AAA'. ++ +
Example 2:
+ +Input: n = 1 +Output: 0 ++ +
+
Constraints:
+ +1 <= n <= 1000Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.
The following rules define a valid string:
+ +'(' must have a corresponding right parenthesis ')'.')' must have a corresponding left parenthesis '('.'(' must go before the corresponding right parenthesis ')'.'*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".+
Example 1:
+Input: s = "()" +Output: true +
Example 2:
+Input: s = "(*)" +Output: true +
Example 3:
+Input: s = "(*))" +Output: true ++
+
Constraints:
+ +1 <= s.length <= 100s[i] is '(', ')' or '*'.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.lengthn == grid[i].length1 <= m, n <= 50grid[i][j] is either 0 or 1.You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.
+ ++
Example 1:
+
+Input: root = [4,2,7,1,3], val = 5 +Output: [4,2,7,1,3,5] +Explanation: Another accepted tree is: ++ ++
Example 2:
+ +Input: root = [40,20,60,10,30,50,70], val = 25 +Output: [40,20,60,10,30,50,70,null,null,25] ++ +
Example 3:
+ +Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5 +Output: [4,2,7,1,3,5] ++ +
+
Constraints:
+ +[0, 104].-108 <= Node.val <= 108Node.val are unique.-108 <= val <= 108val does not exist in the original BST.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 <= 10002 <= accounts[i].length <= 101 <= accounts[i][j].length <= 30accounts[i][0] consists of English letters.accounts[i][j] (for j > 0) is a valid email.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:
+ +[0, 1000].0 <= Node.val <= 10001 <= k <= 50Given 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 <= 10530 <= temperatures[i] <= 100You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.
The lock initially starts at '0000', a string representing the state of the 4 wheels.
You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
+
Example 1:
+ +Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202" +Output: 6 +Explanation: +A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202". +Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid, +because the wheels of the lock become stuck after the display becomes the dead end "0102". ++ +
Example 2:
+ +Input: deadends = ["8888"], target = "0009" +Output: 1 +Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009". ++ +
Example 3:
+ +Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888" +Output: -1 +Explanation: We cannot reach the target without getting stuck. ++ +
+
Constraints:
+ +1 <= deadends.length <= 500deadends[i].length == 4target.length == 4deadends.target and deadends[i] consist of digits only.Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.
Return any possible rearrangement of s or return "" if not possible.
+
Example 1:
+Input: s = "aab" +Output: "aba" +
Example 2:
+Input: s = "aaab" +Output: "" ++
+
Constraints:
+ +1 <= s.length <= 500s consists of lowercase English letters.Given the root of a binary search tree (BST) and an integer target, split the tree into two subtrees where the first subtree has nodes that are all smaller or equal to the target value, while the second subtree has all nodes that are greater than the target value. It is not necessarily the case that the tree contains a node with the value target.
Additionally, most of the structure of the original tree should remain. Formally, for any child c with parent p in the original tree, if they are both in the same subtree after the split, then node c should still have the parent p.
Return an array of the two roots of the two subtrees in order.
+ ++
Example 1:
+
+Input: root = [4,2,6,1,3,5,7], target = 2 +Output: [[2,1],[4,3,6,null,null,5,7]] ++ +
Example 2:
+ +Input: root = [1], target = 1 +Output: [[1],[]] ++ +
+
Constraints:
+ +[1, 50].0 <= Node.val, target <= 1000We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.
n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows.
+
Example 1:
+ +Input: n = 1, k = 1 +Output: 0 +Explanation: row 1: 0 ++ +
Example 2:
+ +Input: n = 2, k = 1 +Output: 0 +Explanation: +row 1: 0 +row 2: 01 ++ +
Example 3:
+ +Input: n = 2, k = 2 +Output: 1 +Explanation: +row 1: 0 +row 2: 01 ++ +
+
Constraints:
+ +1 <= n <= 301 <= k <= 2n - 1You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k.
For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].
Return the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j].
+
Example 1:
+ +Input: arr = [1,2,3,5], k = 3 +Output: [2,5] +Explanation: The fractions to be considered in sorted order are: +1/5, 1/3, 2/5, 1/2, 3/5, and 2/3. +The third fraction is 2/5. ++ +
Example 2:
+ +Input: arr = [1,7], k = 1 +Output: [1,7] ++ +
+
Constraints:
+ +2 <= arr.length <= 10001 <= arr[i] <= 3 * 104arr[0] == 1arr[i] is a prime number for i > 0.arr are unique and sorted in strictly increasing order.1 <= k <= arr.length * (arr.length - 1) / 2+Follow up: Can you solve the problem with better than
O(n2) complexity?There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.
You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.
+
Example 1:
+
+Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 +Output: 700 +Explanation: +The graph is shown above. +The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. +Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops. ++ +
Example 2:
+
+Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 +Output: 200 +Explanation: +The graph is shown above. +The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. ++ +
Example 3:
+
+Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0 +Output: 500 +Explanation: +The graph is shown above. +The optimal path with no stops from city 0 to 2 is marked in red and has cost 500. ++ +
+
Constraints:
+ +1 <= n <= 1000 <= flights.length <= (n * (n - 1) / 2)flights[i].length == 30 <= fromi, toi < nfromi != toi1 <= pricei <= 1040 <= src, dst, k < nsrc != dstYou are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.
Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.
Return any permutation of s that satisfies this property.
+
Example 1:
+ +Input: order = "cba", s = "abcd"
+ +Output: "cbad"
+ +Explanation: "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a".
Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.
Example 2:
+ +Input: order = "bcafg", s = "abcd"
+ +Output: "bcad"
+ +Explanation: The characters "b", "c", and "a" from order dictate the order for the characters in s. The character "d" in s does not appear in order, so its position is flexible.
Following the order of appearance in order, "b", "c", and "a" from s should be arranged as "b", "c", "a". "d" can be placed at any position since it's not in order. The output "bcad" correctly follows this rule. Other arrangements like "bacd" or "bcda" would also be valid, as long as "b", "c", "a" maintain their order.
+
Constraints:
+ +1 <= order.length <= 261 <= s.length <= 200order and s consist of lowercase English letters.order are unique.You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where:
difficulty[i] and profit[i] are the difficulty and the profit of the ith job, andworker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]).Every worker can be assigned at most one job, but one job can be completed multiple times.
+ +$1, then the total profit will be $3. If a worker cannot complete any job, their profit is $0.Return the maximum profit we can achieve after assigning the workers to the jobs.
+ ++
Example 1:
+ +Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7] +Output: 100 +Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately. ++ +
Example 2:
+ +Input: difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25] +Output: 0 ++ +
+
Constraints:
+ +n == difficulty.lengthn == profit.lengthm == worker.length1 <= n, m <= 1041 <= difficulty[i], profit[i], worker[i] <= 105A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
Given a row x col grid of integers, how many 3 x 3 contiguous magic square subgrids are there?
Note: while a magic square can only contain numbers from 1 to 9, grid may contain numbers up to 15.
+
Example 1:
+
+Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]] +Output: 1 +Explanation: +The following subgrid is a 3 x 3 magic square: ++ ++while this one is not: +
+In total, there is only one magic square inside the given grid. +
Example 2:
+ +Input: grid = [[8]] +Output: 0 ++ +
+
Constraints:
+ +row == grid.lengthcol == grid[i].length1 <= row, col <= 100 <= grid[i][j] <= 15An array arr a mountain if the following properties hold:
arr.length >= 3i 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 arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1].
You must solve it in O(log(arr.length)) time complexity.
+
Example 1:
+ +Input: arr = [0,1,0] +Output: 1 ++ +
Example 2:
+ +Input: arr = [0,2,1,0] +Output: 1 ++ +
Example 3:
+ +Input: arr = [0,10,5,2] +Output: 1 ++ +
+
Constraints:
+ +3 <= arr.length <= 1050 <= arr[i] <= 106arr is guaranteed to be a mountain array.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 <= 104piles.length <= h <= 1091 <= piles[i] <= 109You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.
Return the minimum number of boats to carry every given person.
+ ++
Example 1:
+ +Input: people = [1,2], limit = 3 +Output: 1 +Explanation: 1 boat (1, 2) ++ +
Example 2:
+ +Input: people = [3,2,2,1], limit = 3 +Output: 3 +Explanation: 3 boats (1, 2), (2) and (3) ++ +
Example 3:
+ +Input: people = [3,5,3,4], limit = 5 +Output: 4 +Explanation: 4 boats (3), (3), (4), (5) ++ +
+
Constraints:
+ +1 <= people.length <= 5 * 1041 <= people[i] <= limit <= 3 * 104You 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 <= 1000 <= rStart < rows0 <= cStart < colsGiven 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 <= 20Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.
+
Example 1:
+ +Input: arr = [3,1,2,4] +Output: 17 +Explanation: +Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. +Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. +Sum is 17. ++ +
Example 2:
+ +Input: arr = [11,81,94,43,3] +Output: 444 ++ +
+
Constraints:
+ +1 <= arr.length <= 3 * 1041 <= arr[i] <= 3 * 104Given an array of integers nums, sort the array in ascending order and return it.
You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible.
+
Example 1:
+ +Input: nums = [5,2,3,1] +Output: [1,2,3,5] +Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5). ++ +
Example 2:
+ +Input: nums = [5,1,1,2,0,0] +Output: [0,0,1,1,2,5] +Explanation: Note that the values of nums are not necessairly unique. ++ +
+
Constraints:
+ +1 <= nums.length <= 5 * 104-5 * 104 <= nums[i] <= 5 * 104Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal.
A subarray is a contiguous part of the array.
+ ++
Example 1:
+ +Input: nums = [1,0,1,0,1], goal = 2 +Output: 4 +Explanation: The 4 subarrays are bolded and underlined below: +[1,0,1,0,1] +[1,0,1,0,1] +[1,0,1,0,1] +[1,0,1,0,1] ++ +
Example 2:
+ +Input: nums = [0,0,0,0,0], goal = 0 +Output: 15 ++ +
+
Constraints:
+ +1 <= nums.length <= 3 * 104nums[i] is either 0 or 1.0 <= goal <= nums.lengthYou are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1.
Return the minimum number of moves to make every value in nums unique.
The test cases are generated so that the answer fits in a 32-bit integer.
+ ++
Example 1:
+ +Input: nums = [1,2,2] +Output: 1 +Explanation: After 1 move, the array could be [1, 2, 3]. ++ +
Example 2:
+ +Input: nums = [3,2,1,2,1,7] +Output: 6 +Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7]. +It can be shown with 5 or less moves that it is impossible for the array to have all unique values. ++ +
+
Constraints:
+ +1 <= nums.length <= 1050 <= nums[i] <= 105You start with an initial power of power, an initial score of 0, and a bag of tokens given as an integer array tokens, where each tokens[i] donates the value of tokeni.
Your goal is to maximize the total score by strategically playing these tokens. In one move, you can play an unplayed token in one of the two ways (but not both for the same token):
+ +tokens[i], you may play tokeni, losing tokens[i] power and gaining 1 score.1, you may play tokeni, gaining tokens[i] power and losing 1 score.Return the maximum possible score you can achieve after playing any number of tokens.
+ ++
Example 1:
+ +Input: tokens = [100], power = 50
+ +Output: 0
+ +Explanation: Since your score is 0 initially, you cannot play the token face-down. You also cannot play it face-up since your power (50) is less than tokens[0] (100).
Example 2:
+ +Input: tokens = [200,100], power = 150
+ +Output: 1
+ +Explanation: Play token1 (100) face-up, reducing your power to 50 and increasing your score to 1.
There is no need to play token0, since you cannot play it face-up to add to your score. The maximum score achievable is 1.
Example 3:
+ +Input: tokens = [100,200,300,400], power = 200
+ +Output: 2
+ +Explanation: Play the tokens in this order to get a score of 2:
100) face-up, reducing power to 100 and increasing score to 1.400) face-down, increasing power to 500 and reducing score to 0.200) face-up, reducing power to 300 and increasing score to 1.300) face-up, reducing power to 0 and increasing score to 2.The maximum score achievable is 2.
+
Constraints:
+ +0 <= tokens.length <= 10000 <= tokens[i], power < 104You 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:
+ +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 <= 10001 <= deck[i] <= 106deck are unique.An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\', or blank space ' '. These characters divide the square into contiguous regions.
Given the grid grid represented as a string array, return the number of regions.
Note that backslash characters are escaped, so a '\' is represented as '\\'.
+
Example 1:
+
+Input: grid = [" /","/ "] +Output: 2 ++ +
Example 2:
+
+Input: grid = [" /"," "] +Output: 1 ++ +
Example 3:
+
+Input: grid = ["/\\","\\/"] +Output: 5 +Explanation: Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\. ++ +
+
Constraints:
+ +n == grid.length == grid[i].length1 <= n <= 30grid[i][j] is either '/', '\', or ' '.Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).
The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).
+ ++
Example 1:
+
+Input: points = [[1,3],[-2,2]], k = 1 +Output: [[-2,2]] +Explanation: +The distance between (1, 3) and the origin is sqrt(10). +The distance between (-2, 2) and the origin is sqrt(8). +Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. +We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. ++ +
Example 2:
+ +Input: points = [[3,3],[5,-1],[-2,4]], k = 2 +Output: [[3,3],[-2,4]] +Explanation: The answer [[-2,4],[3,3]] would also be accepted. ++ +
+
Constraints:
+ +1 <= k <= points.length <= 104-104 < xi, yi < 104Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k.
A subarray is a contiguous part of an array.
+ ++
Example 1:
+ +Input: nums = [4,5,0,-2,-3,1], k = 5 +Output: 7 +Explanation: There are 7 subarrays with a sum divisible by k = 5: +[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3] ++ +
Example 2:
+ +Input: nums = [5], k = 9 +Output: 0 ++ +
+
Constraints:
+ +1 <= nums.length <= 3 * 104-104 <= nums[i] <= 1042 <= k <= 104You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree.
In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.
+ +Return the minimum number of moves required to make every node have exactly one coin.
+ ++
Example 1:
+
+Input: root = [3,0,0] +Output: 2 +Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child. ++ +
Example 2:
+
+Input: root = [0,3,0] +Output: 3 +Explanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child. ++ +
+
Constraints:
+ +n.1 <= n <= 1000 <= Node.val <= nNode.val is n.Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.
+ +Implement the TimeMap class:
TimeMap() Initializes the object of the data structure.void set(String key, String value, int timestamp) Stores the key key with the value value at the given time timestamp.String get(String key, int timestamp) Returns a value such that set was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the value associated with the largest timestamp_prev. If there are no values, it returns "".+
Example 1:
+ +Input
+["TimeMap", "set", "get", "get", "set", "get", "get"]
+[[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]]
+Output
+[null, null, "bar", "bar", null, "bar2", "bar2"]
+
+Explanation
+TimeMap timeMap = new TimeMap();
+timeMap.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1.
+timeMap.get("foo", 1); // return "bar"
+timeMap.get("foo", 3); // return "bar", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar".
+timeMap.set("foo", "bar2", 4); // store the key "foo" and value "bar2" along with timestamp = 4.
+timeMap.get("foo", 4); // return "bar2"
+timeMap.get("foo", 5); // return "bar2"
+
+
++
Constraints:
+ +1 <= key.length, value.length <= 100key and value consist of lowercase English letters and digits.1 <= timestamp <= 107timestamp of set are strictly increasing.2 * 105 calls will be made to set and get.You are given an m x n grid where each cell can have one of three values:
0 representing an empty cell,1 representing a fresh orange, or2 representing a rotten orange.Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.
+ +Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.
+
Example 1:
+
+Input: grid = [[2,1,1],[1,1,0],[0,1,1]] +Output: 4 ++ +
Example 2:
+ +Input: grid = [[2,1,1],[0,1,1],[1,0,1]] +Output: -1 +Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. ++ +
Example 3:
+ +Input: grid = [[0,2]] +Output: 0 +Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0. ++ +
+
Constraints:
+ +m == grid.lengthn == grid[i].length1 <= m, n <= 10grid[i][j] is 0, 1, or 2.Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b.
A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b.
+
Example 1:
+
+Input: root = [8,3,10,1,6,null,14,null,null,4,7,13] +Output: 7 +Explanation: We have various ancestor-node differences, some of which are given below : +|8 - 3| = 5 +|3 - 7| = 4 +|8 - 1| = 7 +|10 - 13| = 3 +Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.+ +
Example 2:
+
+Input: root = [1,null,2,null,0,3] +Output: 3 ++ +
+
Constraints:
+ +[2, 5000].0 <= Node.val <= 105There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the ith minute and all those customers leave after the end of that minute.
On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the ith minute, and is 0 otherwise.
When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied.
+ +The bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once.
Return the maximum number of customers that can be satisfied throughout the day.
+ ++
Example 1:
+ +Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3 +Output: 16 +Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes. +The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16. ++ +
Example 2:
+ +Input: customers = [1], grumpy = [0], minutes = 1 +Output: 1 ++ +
+
Constraints:
+ +n == customers.length == grumpy.length1 <= minutes <= n <= 2 * 1040 <= customers[i] <= 1000grumpy[i] is either 0 or 1.Given an integer array nums which is sorted in ascending order and all of its elements are unique and given also an integer k, return the kth missing number starting from the leftmost number of the array.
+
Example 1:
+ +Input: nums = [4,7,9,10], k = 1 +Output: 5 +Explanation: The first missing number is 5. ++ +
Example 2:
+ +Input: nums = [4,7,9,10], k = 3 +Output: 8 +Explanation: The missing numbers are [5,6,8,...], hence the third missing number is 8. ++ +
Example 3:
+ +Input: nums = [1,2,4], k = 3 +Output: 6 +Explanation: The missing numbers are [3,5,6,7,...], hence the third missing number is 6. ++ +
+
Constraints:
+ +1 <= nums.length <= 5 * 1041 <= nums[i] <= 107nums is sorted in ascending order, and all the elements are unique.1 <= k <= 108+Follow up: Can you find a logarithmic time complexity (i.e.,
O(log(n))) solution?Given a string s, return the length of the longest repeating substrings. If no repeating substring exists, return 0.
+
Example 1:
+ +Input: s = "abcd" +Output: 0 +Explanation: There is no repeating substring. ++ +
Example 2:
+ +Input: s = "abbaba" +Output: 2 +Explanation: The longest repeating substrings are "ab" and "ba", each of which occurs twice. ++ +
Example 3:
+ +Input: s = "aabcaabdaab"
+Output: 3
+Explanation: The longest repeating substring is "aab", which occurs 3 times.
+
+
++
Constraints:
+ +1 <= s.length <= 2000s consists of lowercase English letters.You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth.
We want to place these books in order onto bookcase shelves that have a total width shelfWidth.
We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place.
Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books.
+ +5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf.Return the minimum possible height that the total bookshelf can be after placing shelves in this manner.
+ ++
Example 1:
+
+Input: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4 +Output: 6 +Explanation: +The sum of the heights of the 3 shelves is 1 + 3 + 2 = 6. +Notice that book number 2 does not have to be on the first shelf. ++ +
Example 2:
+ +Input: books = [[1,3],[2,4],[3,2]], shelfWidth = 6 +Output: 4 ++ +
+
Constraints:
+ +1 <= books.length <= 10001 <= thicknessi <= shelfWidth <= 10001 <= heighti <= 1000Given the root of a binary tree, return the maximum average value of a subtree of that tree. Answers within 10-5 of the actual answer will be accepted.
A subtree of a tree is any node of that tree plus all its descendants.
+ +The average value of a tree is the sum of its values, divided by the number of nodes.
+ ++
Example 1:
+
+Input: root = [5,6,1] +Output: 6.00000 +Explanation: +For the node with value = 5 we have an average of (5 + 6 + 1) / 3 = 4. +For the node with value = 6 we have an average of 6 / 1 = 6. +For the node with value = 1 we have an average of 1 / 1 = 1. +So the answer is 6 which is the maximum. ++ +
Example 2:
+ +Input: root = [0,null,1] +Output: 1.00000 ++ +
+
Constraints:
+ +[1, 104].0 <= Node.val <= 105Alice and Bob continue their games with piles of stones. There are a 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.
Alice and Bob take turns, with Alice starting first. Initially, M = 1.
On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M. Then, we set M = max(M, X).
The game continues until all the stones have been taken.
+ +Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get.
+ ++
Example 1:
+ +Input: piles = [2,7,9,4,4] +Output: 10 +Explanation: If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger. ++ +
Example 2:
+ +Input: piles = [1,2,3,4,5,100] +Output: 104 ++ +
+
Constraints:
+ +1 <= piles.length <= 1001 <= piles[i] <= 104Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
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.
+ +"ace" is a subsequence of "abcde".A common subsequence of two strings is a subsequence that is common to both strings.
+ ++
Example 1:
+ +Input: text1 = "abcde", text2 = "ace" +Output: 3 +Explanation: The longest common subsequence is "ace" and its length is 3. ++ +
Example 2:
+ +Input: text1 = "abc", text2 = "abc" +Output: 3 +Explanation: The longest common subsequence is "abc" and its length is 3. ++ +
Example 3:
+ +Input: text1 = "abc", text2 = "def" +Output: 0 +Explanation: There is no such common subsequence, so the result is 0. ++ +
+
Constraints:
+ +1 <= text1.length, text2.length <= 1000text1 and text2 consist of only lowercase English characters.You have n dice, and each die has k faces numbered from 1 to k.
Given three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice, so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7.
+
Example 1:
+ +Input: n = 1, k = 6, target = 3 +Output: 1 +Explanation: You throw one die with 6 faces. +There is only one way to get a sum of 3. ++ +
Example 2:
+ +Input: n = 2, k = 6, target = 7 +Output: 6 +Explanation: You throw two dice, each with 6 faces. +There are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1. ++ +
Example 3:
+ +Input: n = 30, k = 30, target = 500 +Output: 222616187 +Explanation: The answer must be returned modulo 109 + 7. ++ +
+
Constraints:
+ +1 <= n, k <= 301 <= target <= 1000Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
+ ++
(Note that in the examples below, all sequences are serializations of ListNode objects.)
Example 1:
+ +Input: head = [1,2,-3,3,1] +Output: [3,1] +Note: The answer [1,2,1] would also be accepted. ++ +
Example 2:
+ +Input: head = [1,2,3,-3,4] +Output: [1,2,4] ++ +
Example 3:
+ +Input: head = [1,2,3,-3,-2] +Output: [1] ++ +
+
Constraints:
+ +1 and 1000 nodes.-1000 <= node.val <= 1000.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:
+ +0 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.lengthn == grid[i].length1 <= m, n <= 150 <= grid[i][j] <= 100Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
+ ++
Example 1:
+ +Input: nums = [1,1,2,1,1], k = 3 +Output: 2 +Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1]. ++ +
Example 2:
+ +Input: nums = [2,4,6], k = 1 +Output: 0 +Explanation: There are no odd numbers in the array. ++ +
Example 3:
+ +Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2 +Output: 16 ++ +
+
Constraints:
+ +1 <= nums.length <= 500001 <= nums[i] <= 10^51 <= k <= nums.lengthGiven 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:
+ +AB (A concatenated with B), where A and B are valid strings, or(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 <= 105s[i] is either'(' , ')', or lowercase English letter.There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.
You are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3.
Return a list of groups such that each person i is in a group of size groupSizes[i].
Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.
+ ++
Example 1:
+ +Input: groupSizes = [3,3,3,3,3,1,3] +Output: [[5],[0,1,2],[3,4,6]] +Explanation: +The first group is [5]. The size is 1, and groupSizes[5] = 1. +The second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3. +The third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3. +Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]]. ++ +
Example 2:
+ +Input: groupSizes = [2,1,3,3,3,2] +Output: [[1],[0,5],[2,3,4]] ++ +
+
Constraints:
+ +groupSizes.length == n1 <= n <= 5001 <= groupSizes[i] <= nGiven a binary tree root and an integer target, delete all the leaf nodes with value target.
Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot).
+
Example 1:
+ +
Input: root = [1,2,3,2,null,2,4], target = 2 +Output: [1,null,3,null,4] +Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). +After removing, new nodes become leaf nodes with value (target = 2) (Picture in center). ++ +
Example 2:
+ +
Input: root = [1,3,3,3,2], target = 3 +Output: [1,3,null,null,2] ++ +
Example 3:
+ +
Input: root = [1,2,null,2,null,2], target = 2 +Output: [1] +Explanation: Leaf nodes in green with value (target = 2) are removed at each step. ++ +
+
Constraints:
+ +[1, 3000].1 <= Node.val, target <= 1000There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.
Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number.
Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.
+ ++
Example 1:
+
+Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4 +Output: 3 +Explanation: The figure above describes the graph. +The neighboring cities at a distanceThreshold = 4 for each city are: +City 0 -> [City 1, City 2] +City 1 -> [City 0, City 2, City 3] +City 2 -> [City 0, City 1, City 3] +City 3 -> [City 1, City 2] +Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number. ++ +
Example 2:
+
+Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2 +Output: 0 +Explanation: The figure above describes the graph. +The neighboring cities at a distanceThreshold = 2 for each city are: +City 0 -> [City 1] +City 1 -> [City 0, City 4] +City 2 -> [City 3, City 4] +City 3 -> [City 2, City 4] +City 4 -> [City 1, City 2, City 3] +The city 0 has 1 neighboring city at a distanceThreshold = 2. ++ +
+
Constraints:
+ +2 <= n <= 1001 <= edges.length <= n * (n - 1) / 2edges[i].length == 30 <= fromi < toi < n1 <= weighti, distanceThreshold <= 10^4(fromi, toi) are distinct.There are n soldiers standing in a line. Each soldier is assigned a unique rating value.
You have to form a team of 3 soldiers amongst them under the following rules:
+ +i, j, k) with rating (rating[i], rating[j], rating[k]).rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n).Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).
+ ++
Example 1:
+ +Input: rating = [2,5,3,4,1] +Output: 3 +Explanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). ++ +
Example 2:
+ +Input: rating = [2,1,3] +Output: 0 +Explanation: We can't form any team given the conditions. ++ +
Example 3:
+ +Input: rating = [1,2,3,4] +Output: 4 ++ +
+
Constraints:
+ +n == rating.length3 <= n <= 10001 <= rating[i] <= 105rating are unique.Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules:
If the current number is even, you have to divide it by 2.
If the current number is odd, you have to add 1 to it.
It is guaranteed that you can always reach one for all test cases.
+ ++
Example 1:
+ +Input: s = "1101" +Output: 6 +Explanation: "1101" corressponds to number 13 in their decimal representation. +Step 1) 13 is odd, add 1 and obtain 14. +Step 2) 14 is even, divide by 2 and obtain 7. +Step 3) 7 is odd, add 1 and obtain 8. +Step 4) 8 is even, divide by 2 and obtain 4. +Step 5) 4 is even, divide by 2 and obtain 2. +Step 6) 2 is even, divide by 2 and obtain 1. ++ +
Example 2:
+ +Input: s = "10" +Output: 1 +Explanation: "10" corressponds to number 2 in their decimal representation. +Step 1) 2 is even, divide by 2 and obtain 1. ++ +
Example 3:
+ +Input: s = "1" +Output: 0 ++ +
+
Constraints:
+ +1 <= s.length <= 500s consists of characters '0' or '1's[0] == '1'Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.
+
Example 1:
+ +Input: nums = [8,2,4,7], limit = 4 +Output: 2 +Explanation: All subarrays are: +[8] with maximum absolute diff |8-8| = 0 <= 4. +[8,2] with maximum absolute diff |8-2| = 6 > 4. +[8,2,4] with maximum absolute diff |8-2| = 6 > 4. +[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. +[2] with maximum absolute diff |2-2| = 0 <= 4. +[2,4] with maximum absolute diff |2-4| = 2 <= 4. +[2,4,7] with maximum absolute diff |2-7| = 5 > 4. +[4] with maximum absolute diff |4-4| = 0 <= 4. +[4,7] with maximum absolute diff |4-7| = 3 <= 4. +[7] with maximum absolute diff |7-7| = 0 <= 4. +Therefore, the size of the longest subarray is 2. ++ +
Example 2:
+ +Input: nums = [10,1,2,4,7,2], limit = 5 +Output: 4 +Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. ++ +
Example 3:
+ +Input: nums = [4,2,2,2,4,4,2,2], limit = 0 +Output: 3 ++ +
+
Constraints:
+ +1 <= nums.length <= 1051 <= nums[i] <= 1090 <= limit <= 109Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.
+ +Return the number of pseudo-palindromic paths going from the root node to leaf nodes.
+ ++
Example 1:
+ +
Input: root = [2,3,1,3,1,null,1] +Output: 2 +Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome). ++ +
Example 2:
+ +
Input: root = [2,1,1,1,3,null,null,null,null,null,1] +Output: 1 +Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome). ++ +
Example 3:
+ +Input: root = [9] +Output: 1 ++ +
+
Constraints:
+ +[1, 105].1 <= Node.val <= 9You are given an integer array bloomDay, an integer m and an integer k.
You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
+
Example 1:
+ +Input: bloomDay = [1,10,3,10,2], m = 3, k = 1 +Output: 3 +Explanation: Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden. +We need 3 bouquets each should contain 1 flower. +After day 1: [x, _, _, _, _] // we can only make one bouquet. +After day 2: [x, _, _, _, x] // we can only make two bouquets. +After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3. ++ +
Example 2:
+ +Input: bloomDay = [1,10,3,10,2], m = 3, k = 2 +Output: -1 +Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1. ++ +
Example 3:
+ +Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3 +Output: 12 +Explanation: We need 2 bouquets each should have 3 flowers. +Here is the garden after the 7 and 12 days: +After day 7: [x, x, x, x, _, x, x] +We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent. +After day 12: [x, x, x, x, x, x, x] +It is obvious that we can make two bouquets in different ways. ++ +
+
Constraints:
+ +bloomDay.length == n1 <= n <= 1051 <= bloomDay[i] <= 1091 <= m <= 1061 <= k <= nYou are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.
Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 109 + 7.
+
Example 1:
+ +Input: nums = [1,2,3,4], n = 4, left = 1, right = 5 +Output: 13 +Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13. ++ +
Example 2:
+ +Input: nums = [1,2,3,4], n = 4, left = 3, right = 4 +Output: 6 +Explanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6. ++ +
Example 3:
+ +Input: nums = [1,2,3,4], n = 4, left = 1, right = 10 +Output: 50 ++ +
+
Constraints:
+ +n == nums.length1 <= nums.length <= 10001 <= nums[i] <= 1001 <= left <= right <= n * (n + 1) / 2You are given an integer array nums.
In one move, you can choose one element of nums and change it to any value.
Return the minimum difference between the largest and smallest value of nums after performing at most three moves.
+
Example 1:
+ +Input: nums = [5,3,2,4] +Output: 0 +Explanation: We can make at most 3 moves. +In the first move, change 2 to 3. nums becomes [5,3,3,4]. +In the second move, change 4 to 3. nums becomes [5,3,3,3]. +In the third move, change 5 to 3. nums becomes [3,3,3,3]. +After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0. ++ +
Example 2:
+ +Input: nums = [1,5,0,10,14] +Output: 1 +Explanation: We can make at most 3 moves. +In the first move, change 5 to 0. nums becomes [1,0,0,10,14]. +In the second move, change 10 to 0. nums becomes [1,0,0,0,14]. +In the third move, change 14 to 1. nums becomes [1,0,0,0,1]. +After performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 1. +It can be shown that there is no way to make the difference 0 in 3 moves.+ +
Example 3:
+ +Input: nums = [3,100,20] +Output: 0 +Explanation: We can make at most 3 moves. +In the first move, change 100 to 7. nums becomes [3,7,20]. +In the second move, change 20 to 7. nums becomes [3,7,7]. +In the third move, change 3 to 7. nums becomes [7,7,7]. +After performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0. ++ +
+
Constraints:
+ +1 <= nums.length <= 105-109 <= nums[i] <= 109You are given a string s consisting only of characters 'a' and 'b'.
You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'.
Return the minimum number of deletions needed to make s balanced.
+
Example 1:
+ +Input: s = "aababbab"
+Output: 2
+Explanation: You can either:
+Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or
+Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb").
+
+
+Example 2:
+ +Input: s = "bbaaaaabb" +Output: 2 +Explanation: The only solution is to delete the first two characters. ++ +
+
Constraints:
+ +1 <= s.length <= 105s[i] is 'a' or 'b'.You are given two linked lists: list1 and list2 of sizes n and m respectively.
Remove list1's nodes from the ath node to the bth node, and put list2 in their place.
The blue edges and nodes in the following figure indicate the result:
+
+Build the result list and return its head.
+ ++
Example 1:
+
+Input: list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002] +Output: [10,1,13,1000000,1000001,1000002,5] +Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. ++ +
Example 2:
+
+Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004] +Output: [0,1,1000000,1000001,1000002,1000003,1000004,6] +Explanation: The blue edges and nodes in the above figure indicate the result. ++ +
+
Constraints:
+ +3 <= list1.length <= 1041 <= a <= b < list1.length - 11 <= list2.length <= 104There is a restaurant with a single chef. You are given an array customers, where customers[i] = [arrivali, timei]:
arrivali is the arrival time of the ith customer. The arrival times are sorted in non-decreasing order.timei is the time needed to prepare the order of the ith customer.When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers in the order they were given in the input.
+ +Return the average waiting time of all customers. Solutions within 10-5 from the actual answer are considered accepted.
+
Example 1:
+ +Input: customers = [[1,2],[2,5],[4,3]] +Output: 5.00000 +Explanation: +1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. +2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. +3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. +So the average waiting time = (2 + 6 + 7) / 3 = 5. ++ +
Example 2:
+ +Input: customers = [[5,2],[5,4],[10,3],[20,1]] +Output: 3.25000 +Explanation: +1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. +2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. +3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. +4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. +So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. ++ +
+
Constraints:
+ +1 <= customers.length <= 1051 <= arrivali, timei <= 104arrivali <= arrivali+1Given the root of a binary tree and two integers p and q, return the distance between the nodes of value p and value q in the tree.
The distance between two nodes is the number of edges on the path from one to the other.
+ ++
Example 1:
+
+Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 0 +Output: 3 +Explanation: There are 3 edges between 5 and 0: 5-3-1-0.+ +
Example 2:
+
+Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 7 +Output: 2 +Explanation: There are 2 edges between 5 and 7: 5-2-7.+ +
Example 3:
+
+Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 5 +Output: 0 +Explanation: The distance between a node and itself is 0.+ +
+
Constraints:
+ +[1, 104].0 <= Node.val <= 109Node.val are unique.p and q are values in the tree.Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times:
s where all the characters in the prefix are equal.s where all the characters in this suffix are equal.Return the minimum length of s after performing the above operation any number of times (possibly zero times).
+
Example 1:
+ +Input: s = "ca" +Output: 2 +Explanation: You can't remove any characters, so the string stays as is. ++ +
Example 2:
+ +Input: s = "cabaabac" +Output: 0 +Explanation: An optimal sequence of operations is: +- Take prefix = "c" and suffix = "c" and remove them, s = "abaaba". +- Take prefix = "a" and suffix = "a" and remove them, s = "baab". +- Take prefix = "b" and suffix = "b" and remove them, s = "aa". +- Take prefix = "a" and suffix = "a" and remove them, s = "".+ +
Example 3:
+ +Input: s = "aabccabba" +Output: 3 +Explanation: An optimal sequence of operations is: +- Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb". +- Take prefix = "b" and suffix = "bb" and remove them, s = "cca". ++ +
+
Constraints:
+ +1 <= s.length <= 105s only consists of characters 'a', 'b', and 'c'.The frequency of an element is the number of times it occurs in an array.
+ +You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.
Return the maximum possible frequency of an element after performing at most k operations.
+
Example 1:
+ +Input: nums = [1,2,4], k = 5 +Output: 3 +Explanation: Increment the first element three times and the second element two times to make nums = [4,4,4]. +4 has a frequency of 3.+ +
Example 2:
+ +Input: nums = [1,4,8,13], k = 5 +Output: 2 +Explanation: There are multiple optimal solutions: +- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2. +- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2. +- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2. ++ +
Example 3:
+ +Input: nums = [3,9,6], k = 2 +Output: 1 ++ +
+
Constraints:
+ +1 <= nums.length <= 1051 <= nums[i] <= 1051 <= k <= 105You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
arr must be 1.1. In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length (0-indexed). abs(x) is the absolute value of x.There are 2 types of operations that you can perform any number of times:
+ +arr to a smaller positive integer.arr to be in any order.Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions.
+
Example 1:
+ +Input: arr = [2,2,1,2,1] +Output: 2 +Explanation: +We can satisfy the conditions by rearranging+ +arrso it becomes[1,2,2,2,1]. +The largest element inarris 2. +
Example 2:
+ +Input: arr = [100,1,1000] +Output: 3 +Explanation: +One possible way to satisfy the conditions is by doing the following: +1. Rearrange+ +arrso it becomes[1,100,1000]. +2. Decrease the value of the second element to 2. +3. Decrease the value of the third element to 3. +Nowarr = [1,2,3], whichsatisfies the conditions. +The largest element inarr is 3.+
Example 3:
+ +Input: arr = [1,2,3,4,5] +Output: 5 +Explanation: The array already satisfies the conditions, and the largest element is 5. ++ +
+
Constraints:
+ +1 <= arr.length <= 1051 <= arr[i] <= 109A wonderful string is a string where at most one letter appears an odd number of times.
+ +"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 <= 105word consists of lowercase English letters from 'a' to 'j'.You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix.
To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score.
However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score.
Return the maximum number of points you can achieve.
+ +abs(x) is defined as:
x for x >= 0.-x for x < 0.+
Example 1:
+
+Input: points = [[1,2,3],[1,5,1],[3,1,1]] +Output: 9 +Explanation: +The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0). +You add 3 + 5 + 3 = 11 to your score. +However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score. +Your final score is 11 - 2 = 9. ++ +
Example 2:
+
+Input: points = [[1,5],[2,3],[4,2]] +Output: 11 +Explanation: +The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0). +You add 5 + 3 + 4 = 12 to your score. +However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score. +Your final score is 12 - 1 = 11. ++ +
+
Constraints:
+ +m == points.lengthn == points[r].length1 <= m, n <= 1051 <= m * n <= 1050 <= points[r][c] <= 105A critical point in a linked list is defined as either a local maxima or a local minima.
+ +A node is a local maxima if the current node has a value strictly greater than the previous node and the next node.
+ +A node is a local minima if the current node has a value strictly smaller than the previous node and the next node.
+ +Note that a node can only be a local maxima/minima if there exists both a previous node and a next node.
+ +Given a linked list head, return an array of length 2 containing [minDistance, maxDistance] where minDistance is the minimum distance between any two distinct critical points and maxDistance is the maximum distance between any two distinct critical points. If there are fewer than two critical points, return [-1, -1].
+
Example 1:
+
+Input: head = [3,1] +Output: [-1,-1] +Explanation: There are no critical points in [3,1]. ++ +
Example 2:
+
+Input: head = [5,3,1,2,5,1,2] +Output: [1,3] +Explanation: There are three critical points: +- [5,3,1,2,5,1,2]: The third node is a local minima because 1 is less than 3 and 2. +- [5,3,1,2,5,1,2]: The fifth node is a local maxima because 5 is greater than 2 and 1. +- [5,3,1,2,5,1,2]: The sixth node is a local minima because 1 is less than 5 and 2. +The minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1. +The maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3. ++ +
Example 3:
+
+Input: head = [1,3,2,2,3,2,2,2,7] +Output: [3,3] +Explanation: There are two critical points: +- [1,3,2,2,3,2,2,2,7]: The second node is a local maxima because 3 is greater than 1 and 2. +- [1,3,2,2,3,2,2,2,7]: The fifth node is a local maxima because 3 is greater than 2 and 2. +Both the minimum and maximum distances are between the second and the fifth node. +Thus, minDistance and maxDistance is 5 - 2 = 3. +Note that the last node is not considered a local maxima because it does not have a next node. ++ +
+
Constraints:
+ +[2, 105].1 <= Node.val <= 105Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device.
There is one laser beam between any two security devices if both conditions are met:
+ +r1 and r2, where r1 < r2.i where r1 < i < r2, there are no security devices in the ith row.Laser beams are independent, i.e., one beam does not interfere nor join with another.
+ +Return the total number of laser beams in the bank.
+ ++
Example 1:
+
+Input: bank = ["011001","000000","010100","001000"] +Output: 8 +Explanation: Between each of the following device pairs, there is one beam. In total, there are 8 beams: + * bank[0][1] -- bank[2][1] + * bank[0][1] -- bank[2][3] + * bank[0][2] -- bank[2][1] + * bank[0][2] -- bank[2][3] + * bank[0][5] -- bank[2][1] + * bank[0][5] -- bank[2][3] + * bank[2][1] -- bank[3][2] + * bank[2][3] -- bank[3][2] +Note that there is no beam between any device on the 0th row with any on the 3rd row. +This is because the 2nd row contains security devices, which breaks the second condition. ++ +
Example 2:
+
+Input: bank = ["000","111","000"] +Output: 0 +Explanation: There does not exist two devices located on two different rows. ++ +
+
Constraints:
+ +m == bank.lengthn == bank[i].length1 <= m, n <= 500bank[i][j] is either '0' or '1'.A swap is defined as taking two distinct positions in an array and swapping the values in them.
+ +A circular array is defined as an array where we consider the first element and the last element to be adjacent.
+ +Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location.
+
Example 1:
+ +Input: nums = [0,1,0,1,1,0,0] +Output: 1 +Explanation: Here are a few of the ways to group all the 1's together: +[0,0,1,1,1,0,0] using 1 swap. +[0,1,1,1,0,0,0] using 1 swap. +[1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array). +There is no way to group all 1's together with 0 swaps. +Thus, the minimum number of swaps required is 1. ++ +
Example 2:
+ +Input: nums = [0,1,1,1,0,0,1,1,0] +Output: 2 +Explanation: Here are a few of the ways to group all the 1's together: +[1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array). +[1,1,1,1,1,0,0,0,0] using 2 swaps. +There is no way to group all 1's together with 0 or 1 swaps. +Thus, the minimum number of swaps required is 2. ++ +
Example 3:
+ +Input: nums = [1,1,0,0,1] +Output: 0 +Explanation: All the 1's are already grouped together due to the circular property of the array. +Thus, the minimum number of swaps required is 0. ++ +
+
Constraints:
+ +1 <= nums.length <= 105nums[i] is either 0 or 1.You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.
You should rearrange the elements of nums such that the modified array follows the given conditions:
nums is preserved.Return the modified array after rearranging the elements to satisfy the aforementioned conditions.
+ ++
Example 1:
+ +Input: nums = [3,1,-2,-5,2,-4] +Output: [3,-2,1,-5,2,-4] +Explanation: +The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4]. +The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4]. +Other ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions. ++ +
Example 2:
+ +Input: nums = [-1,1] +Output: [1,-1] +Explanation: +1 is the only positive integer and -1 the only negative integer in nums. +So nums is rearranged to [1,-1]. ++ +
+
Constraints:
+ +2 <= nums.length <= 2 * 105nums.length is even1 <= |nums[i]| <= 105nums consists of equal number of positive and negative integers.You are given a 0-indexed integer array mapping which represents the mapping rule of a shuffled decimal system. mapping[i] = j means digit i should be mapped to digit j in this system.
The mapped value of an integer is the new integer obtained by replacing each occurrence of digit i in the integer with mapping[i] for all 0 <= i <= 9.
You are also given another integer array nums. Return the array nums sorted in non-decreasing order based on the mapped values of its elements.
Notes:
+ +nums should only be sorted based on their mapped values and not be replaced by them.+
Example 1:
+ +Input: mapping = [8,9,4,0,2,1,3,5,7,6], nums = [991,338,38] +Output: [338,38,991] +Explanation: +Map the number 991 as follows: +1. mapping[9] = 6, so all occurrences of the digit 9 will become 6. +2. mapping[1] = 9, so all occurrences of the digit 1 will become 9. +Therefore, the mapped value of 991 is 669. +338 maps to 007, or 7 after removing the leading zeros. +38 maps to 07, which is also 7 after removing leading zeros. +Since 338 and 38 share the same mapped value, they should remain in the same relative order, so 338 comes before 38. +Thus, the sorted array is [338,38,991]. ++ +
Example 2:
+ +Input: mapping = [0,1,2,3,4,5,6,7,8,9], nums = [789,456,123] +Output: [123,456,789] +Explanation: 789 maps to 789, 456 maps to 456, and 123 maps to 123. Thus, the sorted array is [123,456,789]. ++ +
+
Constraints:
+ +mapping.length == 100 <= mapping[i] <= 9mapping[i] are unique.1 <= nums.length <= 3 * 1040 <= nums[i] < 109You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore,
isLefti == 1, then childi is the left child of parenti.isLefti == 0, then childi is the right child of parenti.Construct the binary tree described by descriptions and return its root.
The test cases will be generated such that the binary tree is valid.
+ ++
Example 1:
+
+Input: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]] +Output: [50,20,80,15,17,19] +Explanation: The root node is the node with value 50 since it has no parent. +The resulting binary tree is shown in the diagram. ++ +
Example 2:
+
+Input: descriptions = [[1,2,1],[2,3,0],[3,4,1]] +Output: [1,2,null,null,3,4] +Explanation: The root node is the node with value 1 since it has no parent. +The resulting binary tree is shown in the diagram. ++ +
+
Constraints:
+ +1 <= descriptions.length <= 104descriptions[i].length == 31 <= parenti, childi <= 1050 <= isLefti <= 1descriptions is valid.Design a food rating system that can do the following:
+ +Implement the FoodRatings class:
FoodRatings(String[] foods, String[] cuisines, int[] ratings) Initializes the system. The food items are described by foods, cuisines and ratings, all of which have a length of n.
+
+ foods[i] is the name of the ith food,cuisines[i] is the type of cuisine of the ith food, andratings[i] is the initial rating of the ith food.void changeRating(String food, int newRating) Changes the rating of the food item with the name food.String highestRated(String cuisine) Returns the name of the food item that has the highest rating for the given type of cuisine. If there is a tie, return the item with the lexicographically smaller name.Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order.
+
Example 1:
+ +Input
+["FoodRatings", "highestRated", "highestRated", "changeRating", "highestRated", "changeRating", "highestRated"]
+[[["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]], ["korean"], ["japanese"], ["sushi", 16], ["japanese"], ["ramen", 16], ["japanese"]]
+Output
+[null, "kimchi", "ramen", null, "sushi", null, "ramen"]
+
+Explanation
+FoodRatings foodRatings = new FoodRatings(["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]);
+foodRatings.highestRated("korean"); // return "kimchi"
+ // "kimchi" is the highest rated korean food with a rating of 9.
+foodRatings.highestRated("japanese"); // return "ramen"
+ // "ramen" is the highest rated japanese food with a rating of 14.
+foodRatings.changeRating("sushi", 16); // "sushi" now has a rating of 16.
+foodRatings.highestRated("japanese"); // return "sushi"
+ // "sushi" is the highest rated japanese food with a rating of 16.
+foodRatings.changeRating("ramen", 16); // "ramen" now has a rating of 16.
+foodRatings.highestRated("japanese"); // return "ramen"
+ // Both "sushi" and "ramen" have a rating of 16.
+ // However, "ramen" is lexicographically smaller than "sushi".
+
+
++
Constraints:
+ +1 <= n <= 2 * 104n == foods.length == cuisines.length == ratings.length1 <= foods[i].length, cuisines[i].length <= 10foods[i], cuisines[i] consist of lowercase English letters.1 <= ratings[i] <= 108foods are distinct.food will be the name of a food item in the system across all calls to changeRating.cuisine will be a type of cuisine of at least one food item in the system across all calls to highestRated.2 * 104 calls in total will be made to changeRating and highestRated.You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if the following conditions are satisfied:
t is a subsequence of the string s.t is less than or equal to k.Return the length of the longest ideal string.
+ +A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
+ +Note that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25, not 1.
+
Example 1:
+ +Input: s = "acfgbd", k = 2 +Output: 4 +Explanation: The longest ideal string is "acbd". The length of this string is 4, so 4 is returned. +Note that "acfgbd" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order.+ +
Example 2:
+ +Input: s = "abcd", k = 3 +Output: 4 +Explanation: The longest ideal string is "abcd". The length of this string is 4, so 4 is returned. ++ +
+
Constraints:
+ +1 <= s.length <= 1050 <= k <= 25s consists of lowercase English letters.You are given the root of a binary tree with unique values, and an integer start. At minute 0, an infection starts from the node with value start.
Each minute, a node becomes infected if:
+ +Return the number of minutes needed for the entire tree to be infected.
+ ++
Example 1:
+
+Input: root = [1,5,3,null,4,10,6,9,2], start = 3 +Output: 4 +Explanation: The following nodes are infected during: +- Minute 0: Node 3 +- Minute 1: Nodes 1, 10 and 6 +- Minute 2: Node 5 +- Minute 3: Node 4 +- Minute 4: Nodes 9 and 2 +It takes 4 minutes for the whole tree to be infected so we return 4. ++ +
Example 2:
+
+Input: root = [1], start = 1 +Output: 0 +Explanation: At minute 0, the only node in the tree is infected so we return 0. ++ +
+
Constraints:
+ +[1, 105].1 <= Node.val <= 105start exists in the tree.You are given a 0-indexed array of strings garbage where garbage[i] represents the assortment of garbage at the ith house. garbage[i] consists only of the characters 'M', 'P' and 'G' representing one unit of metal, paper and glass garbage respectively. Picking up one unit of any type of garbage takes 1 minute.
You are also given a 0-indexed integer array travel where travel[i] is the number of minutes needed to go from house i to house i + 1.
There are three garbage trucks in the city, each responsible for picking up one type of garbage. Each garbage truck starts at house 0 and must visit each house in order; however, they do not need to visit every house.
Only one garbage truck may be used at any given moment. While one truck is driving or picking up garbage, the other two trucks cannot do anything.
+ +Return the minimum number of minutes needed to pick up all the garbage.
+ ++
Example 1:
+ +Input: garbage = ["G","P","GP","GG"], travel = [2,4,3] +Output: 21 +Explanation: +The paper garbage truck: +1. Travels from house 0 to house 1 +2. Collects the paper garbage at house 1 +3. Travels from house 1 to house 2 +4. Collects the paper garbage at house 2 +Altogether, it takes 8 minutes to pick up all the paper garbage. +The glass garbage truck: +1. Collects the glass garbage at house 0 +2. Travels from house 0 to house 1 +3. Travels from house 1 to house 2 +4. Collects the glass garbage at house 2 +5. Travels from house 2 to house 3 +6. Collects the glass garbage at house 3 +Altogether, it takes 13 minutes to pick up all the glass garbage. +Since there is no metal garbage, we do not need to consider the metal garbage truck. +Therefore, it takes a total of 8 + 13 = 21 minutes to collect all the garbage. ++ +
Example 2:
+ +Input: garbage = ["MMM","PGM","GP"], travel = [3,10] +Output: 37 +Explanation: +The metal garbage truck takes 7 minutes to pick up all the metal garbage. +The paper garbage truck takes 15 minutes to pick up all the paper garbage. +The glass garbage truck takes 15 minutes to pick up all the glass garbage. +It takes a total of 7 + 15 + 15 = 37 minutes to collect all the garbage. ++ +
+
Constraints:
+ +2 <= garbage.length <= 105garbage[i] consists of only the letters 'M', 'P', and 'G'.1 <= garbage[i].length <= 10travel.length == garbage.length - 11 <= travel[i] <= 100You are given an integer array pref of size n. Find and return the array arr of size n that satisfies:
pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].Note that ^ denotes the bitwise-xor operation.
It can be proven that the answer is unique.
+ ++
Example 1:
+ +Input: pref = [5,2,0,3,1] +Output: [5,7,2,3,2] +Explanation: From the array [5,7,2,3,2] we have the following: +- pref[0] = 5. +- pref[1] = 5 ^ 7 = 2. +- pref[2] = 5 ^ 7 ^ 2 = 0. +- pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3. +- pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1. ++ +
Example 2:
+ +Input: pref = [13] +Output: [13] +Explanation: We have pref[0] = arr[0] = 13. ++ +
+
Constraints:
+ +1 <= pref.length <= 1050 <= pref[i] <= 106You are given a 0-indexed m x n binary matrix grid.
A 0-indexed m x n difference matrix diff is created with the following procedure:
ith row be onesRowi.jth column be onesColj.ith row be zerosRowi.jth column be zerosColj.diff[i][j] = onesRowi + onesColj - zerosRowi - zerosColjReturn the difference matrix diff.
+
Example 1:
+
+Input: grid = [[0,1,1],[1,0,1],[0,0,1]] +Output: [[0,0,4],[0,0,4],[-2,-2,2]] +Explanation: +- diff[0][0] =+ +onesRow0 + onesCol0 - zerosRow0 - zerosCol0= 2 + 1 - 1 - 2 = 0 +- diff[0][1] =onesRow0 + onesCol1 - zerosRow0 - zerosCol1= 2 + 1 - 1 - 2 = 0 +- diff[0][2] =onesRow0 + onesCol2 - zerosRow0 - zerosCol2= 2 + 3 - 1 - 0 = 4 +- diff[1][0] =onesRow1 + onesCol0 - zerosRow1 - zerosCol0= 2 + 1 - 1 - 2 = 0 +- diff[1][1] =onesRow1 + onesCol1 - zerosRow1 - zerosCol1= 2 + 1 - 1 - 2 = 0 +- diff[1][2] =onesRow1 + onesCol2 - zerosRow1 - zerosCol2= 2 + 3 - 1 - 0 = 4 +- diff[2][0] =onesRow2 + onesCol0 - zerosRow2 - zerosCol0= 1 + 1 - 2 - 2 = -2 +- diff[2][1] =onesRow2 + onesCol1 - zerosRow2 - zerosCol1= 1 + 1 - 2 - 2 = -2 +- diff[2][2] =onesRow2 + onesCol2 - zerosRow2 - zerosCol2= 1 + 3 - 2 - 0 = 2 +
Example 2:
+
+Input: grid = [[1,1,1],[1,1,1]] +Output: [[5,5,5],[5,5,5]] +Explanation: +- diff[0][0] = onesRow0 + onesCol0 - zerosRow0 - zerosCol0 = 3 + 2 - 0 - 0 = 5 +- diff[0][1] = onesRow0 + onesCol1 - zerosRow0 - zerosCol1 = 3 + 2 - 0 - 0 = 5 +- diff[0][2] = onesRow0 + onesCol2 - zerosRow0 - zerosCol2 = 3 + 2 - 0 - 0 = 5 +- diff[1][0] = onesRow1 + onesCol0 - zerosRow1 - zerosCol0 = 3 + 2 - 0 - 0 = 5 +- diff[1][1] = onesRow1 + onesCol1 - zerosRow1 - zerosCol1 = 3 + 2 - 0 - 0 = 5 +- diff[1][2] = onesRow1 + onesCol2 - zerosRow1 - zerosCol2 = 3 + 2 - 0 - 0 = 5 ++ +
+
Constraints:
+ +m == grid.lengthn == grid[i].length1 <= m, n <= 1051 <= m * n <= 105grid[i][j] is either 0 or 1.You are given two strings s and t consisting of only lowercase English letters.
Return the minimum number of characters that need to be appended to the end of s so that t becomes a subsequence of s.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
+ ++
Example 1:
+ +Input: s = "coaching", t = "coding"
+Output: 4
+Explanation: Append the characters "ding" to the end of s so that s = "coachingding".
+Now, t is a subsequence of s ("coachingding").
+It can be shown that appending any 3 characters to the end of s will never make t a subsequence.
+
+
+Example 2:
+ +Input: s = "abcde", t = "a"
+Output: 0
+Explanation: t is already a subsequence of s ("abcde").
+
+
+Example 3:
+ +Input: s = "z", t = "abcde"
+Output: 5
+Explanation: Append the characters "abcde" to the end of s so that s = "zabcde".
+Now, t is a subsequence of s ("zabcde").
+It can be shown that appending any 4 characters to the end of s will never make t a subsequence.
+
+
++
Constraints:
+ +1 <= s.length, t.length <= 105s and t consist only of lowercase English letters.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 <= 201 <= nums[i], k <= 1000Design an EventEmitter class. This interface is similar (but with some differences) to the one found in Node.js or the Event Target interface of the DOM. The EventEmitter should allow for subscribing to events and emitting them.
Your EventEmitter class should have the following two methods:
subscribe are referentially identical.subscribe method should also return an object with an unsubscribe method that enables the user to unsubscribe. When it is called, the callback should be removed from the list of subscriptions and undefined should be returned.+
Example 1:
+ +Input: actions = ["EventEmitter", "emit", "subscribe", "subscribe", "emit"], values = [[], ["firstEvent", "function cb1() { return 5; }"], ["firstEvent", "function cb1() { return 5; }"], ["firstEvent"]]
+Output: [[],["emitted",[]],["subscribed"],["subscribed"],["emitted",[5,6]]]
+Explanation:
+const emitter = new EventEmitter();
+emitter.emit("firstEvent"); // [], no callback are subscribed yet
+emitter.subscribe("firstEvent", function cb1() { return 5; });
+emitter.subscribe("firstEvent", function cb2() { return 6; });
+emitter.emit("firstEvent"); // [5, 6], returns the output of cb1 and cb2
+
+
+Example 2:
+ +Input: actions = ["EventEmitter", "subscribe", "emit", "emit"], values = [[], ["firstEvent", "function cb1(...args) { return args.join(','); }"], ["firstEvent", [1,2,3]], ["firstEvent", [3,4,6]]]
+Output: [[],["subscribed"],["emitted",["1,2,3"]],["emitted",["3,4,6"]]]
+Explanation: Note that the emit method should be able to accept an OPTIONAL array of arguments.
+
+const emitter = new EventEmitter();
+emitter.subscribe("firstEvent, function cb1(...args) { return args.join(','); });
+emitter.emit("firstEvent", [1, 2, 3]); // ["1,2,3"]
+emitter.emit("firstEvent", [3, 4, 6]); // ["3,4,6"]
+
+
+Example 3:
+ +Input: actions = ["EventEmitter", "subscribe", "emit", "unsubscribe", "emit"], values = [[], ["firstEvent", "(...args) => args.join(',')"], ["firstEvent", [1,2,3]], [0], ["firstEvent", [4,5,6]]]
+Output: [[],["subscribed"],["emitted",["1,2,3"]],["unsubscribed",0],["emitted",[]]]
+Explanation:
+const emitter = new EventEmitter();
+const sub = emitter.subscribe("firstEvent", (...args) => args.join(','));
+emitter.emit("firstEvent", [1, 2, 3]); // ["1,2,3"]
+sub.unsubscribe(); // undefined
+emitter.emit("firstEvent", [4, 5, 6]); // [], there are no subscriptions
+
+
+Example 4:
+ +Input: actions = ["EventEmitter", "subscribe", "subscribe", "unsubscribe", "emit"], values = [[], ["firstEvent", "x => x + 1"], ["firstEvent", "x => x + 2"], [0], ["firstEvent", [5]]]
+Output: [[],["subscribed"],["emitted",["1,2,3"]],["unsubscribed",0],["emitted",[7]]]
+Explanation:
+const emitter = new EventEmitter();
+const sub1 = emitter.subscribe("firstEvent", x => x + 1);
+const sub2 = emitter.subscribe("firstEvent", x => x + 2);
+sub1.unsubscribe(); // undefined
+emitter.emit("firstEvent", [5]); // [7]
+
++
Constraints:
+ +1 <= actions.length <= 10values.length === actions.lengthEventEmitter, emit, subscribe, and unsubscribe.EventEmitter action doesn't take any arguments.emit action takes between either 1 or 2 arguments. The first argument is the name of the event we want to emit, and the 2nd argument is passed to the callback functions.subscribe action takes 2 arguments, where the first one is the event name and the second is the callback function.unsubscribe action takes one argument, which is the 0-indexed order of the subscription made before.We know that 4 and 7 are lucky digits. Also, a number is called lucky if it contains only lucky digits.
You are given an integer k, return the kth lucky number represented as a string.
+
Example 1:
+ +Input: k = 4 +Output: "47" +Explanation: The first lucky number is 4, the second one is 7, the third one is 44 and the fourth one is 47. ++ +
Example 2:
+ +Input: k = 10 +Output: "477" +Explanation: Here are lucky numbers sorted in increasing order: +4, 7, 44, 47, 74, 77, 444, 447, 474, 477. So the 10th lucky number is 477.+ +
Example 3:
+ +Input: k = 1000 +Output: "777747447" +Explanation: It can be shown that the 1000th lucky number is 777747447. ++ +
+
Constraints:
+ +1 <= k <= 109You are given the head of a non-empty linked list representing a non-negative integer without leading zeroes.
Return the head of the linked list after doubling it.
+
Example 1:
+
+Input: head = [1,8,9] +Output: [3,7,8] +Explanation: The figure above corresponds to the given linked list which represents the number 189. Hence, the returned linked list represents the number 189 * 2 = 378. ++ +
Example 2:
+
+Input: head = [9,9,9] +Output: [1,9,9,8] +Explanation: The figure above corresponds to the given linked list which represents the number 999. Hence, the returned linked list reprersents the number 999 * 2 = 1998. ++ +
+
Constraints:
+ +[1, 104]0 <= Node.val <= 90 itself.You are given two 0-indexed strings str1 and str2.
In an operation, you select a set of indices in str1, and for each index i in the set, increment str1[i] to the next character cyclically. That is 'a' becomes 'b', 'b' becomes 'c', and so on, and 'z' becomes 'a'.
Return true if it is possible to make str2 a subsequence of str1 by performing the operation at most once, and false otherwise.
Note: A subsequence of a string is a new string that is formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.
+ ++
Example 1:
+ +Input: str1 = "abc", str2 = "ad" +Output: true +Explanation: Select index 2 in str1. +Increment str1[2] to become 'd'. +Hence, str1 becomes "abd" and str2 is now a subsequence. Therefore, true is returned.+ +
Example 2:
+ +Input: str1 = "zc", str2 = "ad" +Output: true +Explanation: Select indices 0 and 1 in str1. +Increment str1[0] to become 'a'. +Increment str1[1] to become 'd'. +Hence, str1 becomes "ad" and str2 is now a subsequence. Therefore, true is returned.+ +
Example 3:
+ +Input: str1 = "ab", str2 = "d" +Output: false +Explanation: In this example, it can be shown that it is impossible to make str2 a subsequence of str1 using the operation at most once. +Therefore, false is returned.+ +
+
Constraints:
+ +1 <= str1.length <= 1051 <= str2.length <= 105str1 and str2 consist of only lowercase English letters.You are given a 0-indexed array nums consisting of positive integers.
There are two types of operations that you can apply on the array any number of times:
+ +Return the minimum number of operations required to make the array empty, or -1 if it is not possible.
+
Example 1:
+ +Input: nums = [2,3,3,2,2,4,2,3,4] +Output: 4 +Explanation: We can apply the following operations to make the array empty: +- Apply the first operation on the elements at indices 0 and 3. The resulting array is nums = [3,3,2,4,2,3,4]. +- Apply the first operation on the elements at indices 2 and 4. The resulting array is nums = [3,3,4,3,4]. +- Apply the second operation on the elements at indices 0, 1, and 3. The resulting array is nums = [4,4]. +- Apply the first operation on the elements at indices 0 and 1. The resulting array is nums = []. +It can be shown that we cannot make the array empty in less than 4 operations. ++ +
Example 2:
+ +Input: nums = [2,1,2,2,3,3] +Output: -1 +Explanation: It is impossible to empty the array. ++ +
+
Constraints:
+ +2 <= nums.length <= 1051 <= nums[i] <= 106You are given an integer array nums and an integer k.
The frequency of an element x is the number of times it occurs in an array.
An array is called good if the frequency of each element in this array is less than or equal to k.
Return the length of the longest good subarray of nums.
A subarray is a contiguous non-empty sequence of elements within an array.
+ ++
Example 1:
+ +Input: nums = [1,2,3,1,2,3,1,2], k = 2 +Output: 6 +Explanation: The longest possible good subarray is [1,2,3,1,2,3] since the values 1, 2, and 3 occur at most twice in this subarray. Note that the subarrays [2,3,1,2,3,1] and [3,1,2,3,1,2] are also good. +It can be shown that there are no good subarrays with length more than 6. ++ +
Example 2:
+ +Input: nums = [1,2,1,2,1,2,1,2], k = 1 +Output: 2 +Explanation: The longest possible good subarray is [1,2] since the values 1 and 2 occur at most once in this subarray. Note that the subarray [2,1] is also good. +It can be shown that there are no good subarrays with length more than 2. ++ +
Example 3:
+ +Input: nums = [5,5,5,5,5,5,5], k = 4 +Output: 4 +Explanation: The longest possible good subarray is [5,5,5,5] since the value 5 occurs 4 times in this subarray. +It can be shown that there are no good subarrays with length more than 4. ++ +
+
Constraints:
+ +1 <= nums.length <= 1051 <= nums[i] <= 1091 <= k <= nums.lengthYou are given an integer array nums and a positive integer k.
Return the number of subarrays where the maximum element of nums appears at least k times in that subarray.
A subarray is a contiguous sequence of elements within an array.
+ ++
Example 1:
+ +Input: nums = [1,3,2,3,3], k = 2 +Output: 6 +Explanation: The subarrays that contain the element 3 at least 2 times are: [1,3,2,3], [1,3,2,3,3], [3,2,3], [3,2,3,3], [2,3,3] and [3,3]. ++ +
Example 2:
+ +Input: nums = [1,4,2,1], k = 3 +Output: 0 +Explanation: No subarray contains the element 4 at least 3 times. ++ +
+
Constraints:
+ +1 <= nums.length <= 1051 <= nums[i] <= 1061 <= k <= 105You are given two 0-indexed strings source and target, both of length n and consisting of lowercase English letters. You are also given two 0-indexed character arrays original and changed, and an integer array cost, where cost[i] represents the cost of changing the character original[i] to the character changed[i].
You start with the string source. In one operation, you can pick a character x from the string and change it to the character y at a cost of z if there exists any index j such that cost[j] == z, original[j] == x, and changed[j] == y.
Return the minimum cost to convert the string source to the string target using any number of operations. If it is impossible to convert source to target, return -1.
Note that there may exist indices i, j such that original[j] == original[i] and changed[j] == changed[i].
+
Example 1:
+ +Input: source = "abcd", target = "acbe", original = ["a","b","c","c","e","d"], changed = ["b","c","b","e","b","e"], cost = [2,5,5,1,2,20] +Output: 28 +Explanation: To convert the string "abcd" to string "acbe": +- Change value at index 1 from 'b' to 'c' at a cost of 5. +- Change value at index 2 from 'c' to 'e' at a cost of 1. +- Change value at index 2 from 'e' to 'b' at a cost of 2. +- Change value at index 3 from 'd' to 'e' at a cost of 20. +The total cost incurred is 5 + 1 + 2 + 20 = 28. +It can be shown that this is the minimum possible cost. ++ +
Example 2:
+ +Input: source = "aaaa", target = "bbbb", original = ["a","c"], changed = ["c","b"], cost = [1,2] +Output: 12 +Explanation: To change the character 'a' to 'b' change the character 'a' to 'c' at a cost of 1, followed by changing the character 'c' to 'b' at a cost of 2, for a total cost of 1 + 2 = 3. To change all occurrences of 'a' to 'b', a total cost of 3 * 4 = 12 is incurred. ++ +
Example 3:
+ +Input: source = "abcd", target = "abce", original = ["a"], changed = ["e"], cost = [10000] +Output: -1 +Explanation: It is impossible to convert source to target because the value at index 3 cannot be changed from 'd' to 'e'. ++ +
+
Constraints:
+ +1 <= source.length == target.length <= 105source, target consist of lowercase English letters.1 <= cost.length == original.length == changed.length <= 2000original[i], changed[i] are lowercase English letters.1 <= cost[i] <= 106original[i] != changed[i]You are given a 0-indexed integer array nums and a positive integer k.
You can apply the following operation on the array any number of times:
+ +0 to 1 or vice versa.Return the minimum number of operations required to make the bitwise XOR of all elements of the final array equal to k.
Note that you can flip leading zero bits in the binary representation of elements. For example, for the number (101)2 you can flip the fourth bit and obtain (1101)2.
+
Example 1:
+ +Input: nums = [2,1,3,4], k = 1 +Output: 2 +Explanation: We can do the following operations: +- Choose element 2 which is 3 == (011)2, we flip the first bit and we obtain (010)2 == 2. nums becomes [2,1,2,4]. +- Choose element 0 which is 2 == (010)2, we flip the third bit and we obtain (110)2 = 6. nums becomes [6,1,2,4]. +The XOR of elements of the final array is (6 XOR 1 XOR 2 XOR 4) == 1 == k. +It can be shown that we cannot make the XOR equal to k in less than 2 operations. ++ +
Example 2:
+ +Input: nums = [2,0,2,0], k = 0 +Output: 0 +Explanation: The XOR of elements of the array is (2 XOR 0 XOR 2 XOR 0) == 0 == k. So no operation is needed. ++ +
+
Constraints:
+ +1 <= nums.length <= 1050 <= nums[i] <= 1060 <= k <= 106You are given a string word containing 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 = "xyzxyzxyzxyz" +Output: 12 +Explanation: The remapped keypad given in the image provides the minimum cost. +"x" -> one push on key 2 +"y" -> one push on key 3 +"z" -> one push on key 4 +Total cost is 1 * 4 + 1 * 4 + 1 * 4 = 12 +It can be shown that no other mapping can provide a lower cost. +Note that the key 9 is not mapped to any letter: it is not necessary to map letters to every key, but to map all the letters. ++ +
Example 3:
+
+Input: word = "aabbccddeeffgghhiiiiii" +Output: 24 +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 +"f" -> one push on key 7 +"g" -> one push on key 8 +"h" -> two pushes on key 9 +"i" -> one push on key 9 +Total cost is 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 2 * 2 + 6 * 1 = 24. +It can be shown that no other mapping can provide a lower cost. ++ +
+
Constraints:
+ +1 <= word.length <= 105word consists of lowercase English letters.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 * 1051 <= happiness[i] <= 1081 <= k <= nGiven 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+Follow-up: Can you come up with an algorithm that is less than
O(n2) time complexity?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:
+ +[1, 100].0 <= Node.val <= 9Given 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 * 104s consists of English letters, digits, symbols and spaces.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 == mnums2.length == n0 <= m <= 10000 <= n <= 10001 <= m + n <= 2000-106 <= nums1[i], nums2[i] <= 106Given 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 <= 1000s consist of only digits and English letters.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 <= 1000s consists of English letters (lower-case and upper-case), ',' and '.'.1 <= numRows <= 1000Given 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 - 1Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).
The algorithm for myAtoi(string s) is as follows:
'-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present."123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).[-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.Note:
+ +' ' is considered a whitespace character.+
Example 1:
+ +Input: s = "42"
+Output: 42
+Explanation: The underlined characters are what is read in, 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)
+ ^
+The parsed integer is 42.
+Since 42 is in the range [-231, 231 - 1], the final result is 42.
+
+
+Example 2:
+ +Input: s = " -42"
+Output: -42
+Explanation:
+Step 1: " -42" (leading whitespace is read and ignored)
+ ^
+Step 2: " -42" ('-' is read, so the result should be negative)
+ ^
+Step 3: " -42" ("42" is read in)
+ ^
+The parsed integer is -42.
+Since -42 is in the range [-231, 231 - 1], the final result is -42.
+
+
+Example 3:
+ +Input: s = "4193 with words"
+Output: 4193
+Explanation:
+Step 1: "4193 with words" (no characters read because there is no leading whitespace)
+ ^
+Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+')
+ ^
+Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit)
+ ^
+The parsed integer is 4193.
+Since 4193 is in the range [-231, 231 - 1], the final result is 4193.
+
+
++
Constraints:
+ +0 <= s.length <= 200s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.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?
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 <= 201 <= p.length <= 20s contains only lowercase English letters.p contains only lowercase English letters, '.', and '*'.'*', there will be a previous valid character to match.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.length2 <= n <= 1050 <= height[i] <= 104Roman 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 one's 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 an integer, convert it to a roman numeral.
+ ++
Example 1:
+ +Input: num = 3 +Output: "III" +Explanation: 3 is represented as 3 ones. ++ +
Example 2:
+ +Input: num = 58 +Output: "LVIII" +Explanation: L = 50, V = 5, III = 3. ++ +
Example 3:
+ +Input: num = 1994 +Output: "MCMXCIV" +Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. ++ +
+
Constraints:
+ +1 <= num <= 3999Roman 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 <= 15s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').s is a valid roman numeral in the range [1, 3999].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 <= 2000 <= strs[i].length <= 200strs[i] consists of only lowercase English letters.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] <= 105Given 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 <= 104Given 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 <= 4digits[i] is a digit in the range ['2', '9'].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 < na, b, c, and d are distinct.nums[a] + nums[b] + nums[c] + nums[d] == targetYou 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 <= 109Given 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:
+ +sz.1 <= sz <= 300 <= Node.val <= 1001 <= n <= sz+
Follow up: Could you do this in one pass?
+Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
+ ++
Example 1:
+ +Input: s = "()" +Output: true ++ +
Example 2:
+ +Input: s = "()[]{}"
+Output: true
+
+
+Example 3:
+ +Input: s = "(]" +Output: false ++ +
+
Constraints:
+ +1 <= s.length <= 104s consists of parentheses only '()[]{}'.You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a 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:
+ +[0, 50].-100 <= Node.val <= 100list1 and list2 are sorted in non-decreasing order.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 <= 8You 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.length0 <= k <= 1040 <= lists[i].length <= 500-104 <= lists[i][j] <= 104lists[i] is sorted in ascending order.lists[i].length will not exceed 104.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] ++ +
Example 2:
+ +Input: head = [] +Output: [] ++ +
Example 3:
+ +Input: head = [1] +Output: [1] ++ +
+
Constraints:
+ +[0, 100].0 <= Node.val <= 100Given 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:
+ +n.1 <= k <= n <= 50000 <= Node.val <= 1000+
Follow-up: Can you solve the problem in O(1) extra memory space?
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:
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.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] <= 100nums is sorted in non-decreasing order.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:
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.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 <= 1000 <= nums[i] <= 500 <= val <= 100Given 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 <= 104haystack and needle consist of only lowercase English characters.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 - 1divisor != 0A permutation of an array of integers is an arrangement of its members into a sequence or linear order.
+ +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).
+ +arr = [1,2,3] is [1,3,2].arr = [2,3,1] is [3,1,2].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 <= 1000 <= nums[i] <= 100There 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] <= 104nums are unique.nums is an ascending array that is possibly rotated.-104 <= target <= 104Given 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] <= 109nums is a non-decreasing array.-109 <= target <= 109Given 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] <= 104nums contains distinct values sorted in ascending order.-104 <= target <= 104Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
1-9 without repetition.1-9 without repetition.3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.Note:
+ ++
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 == 9board[i].length == 9board[i][j] is a digit 1-9 or '.'.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 <= 302 <= candidates[i] <= 40candidates are distinct.1 <= target <= 40Given 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 <= 1001 <= candidates[i] <= 501 <= target <= 30Given 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 - 1Given 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.length1 <= n <= 2 * 1040 <= height[i] <= 105You 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] andi + j < nReturn 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 <= 1040 <= nums[i] <= 1000nums[n - 1].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] <= 10nums are unique.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].length1 <= n <= 20-1000 <= matrix[i][j] <= 1000Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
+ ++
Example 1:
+Input: strs = ["eat","tea","tan","ate","nat","bat"] +Output: [["bat"],["nat","tan"],["ate","eat","tea"]] +
Example 2:
+Input: strs = [""] +Output: [[""]] +
Example 3:
+Input: strs = ["a"] +Output: [["a"]] ++
+
Constraints:
+ +1 <= strs.length <= 1040 <= strs[i].length <= 100strs[i] consists of lowercase English letters.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-1n is an integer.x is not zero or n > 0.-104 <= xn <= 104Given 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.
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.lengthn == matrix[i].length1 <= m, n <= 10-100 <= matrix[i][j] <= 100Given 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 <= 104intervals[i].length == 20 <= starti <= endi <= 104You 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.
+
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 <= 104intervals[i].length == 20 <= starti <= endi <= 105intervals is sorted by starti in ascending order.newInterval.length == 20 <= start <= end <= 105Given 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 <= 104s consists of only English letters and spaces ' '.s.Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
+
Example 1:
+
+Input: n = 3 +Output: [[1,2,3],[8,9,4],[7,6,5]] ++ +
Example 2:
+ +Input: n = 1 +Output: [[1]] ++ +
+
Constraints:
+ +1 <= n <= 20Given 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:
+ +[0, 500].-100 <= Node.val <= 1000 <= k <= 2 * 109There 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 <= 100You 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.lengthn == obstacleGrid[i].length1 <= m, n <= 100obstacleGrid[i][j] is 0 or 1.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.lengthn == grid[i].length1 <= m, n <= 2000 <= grid[i][j] <= 200You 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 <= 1000 <= digits[i] <= 9digits does not contain any leading 0's.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 <= 104a and b consist only of '0' or '1' characters.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:
+ +0 and not exceed maxWidth.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 <= 3001 <= words[i].length <= 20words[i] consists of only English letters and symbols.1 <= maxWidth <= 100words[i].length <= maxWidthGiven 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.
+ +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 - 1You 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 <= 45Given 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.lengthn == matrix[0].length1 <= m, n <= 200-231 <= matrix[i][j] <= 231 - 1+
Follow up:
+ +O(mn) space is probably a bad idea.O(m + n) space, but still not the best solution.You are given an m x n integer matrix matrix with the following two properties:
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.lengthn == matrix[i].length1 <= m, n <= 100-104 <= matrix[i][j], target <= 104Given 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.length1 <= n <= 300nums[i] is either 0, 1, or 2.+
Follow up: Could you come up with a one-pass algorithm using only constant extra space?
+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.lengthn == t.length1 <= m, n <= 105s and t consist of uppercase and lowercase English letters.+
Follow up: Could you find an algorithm that runs in O(m + n) time?
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 <= 201 <= k <= nGiven 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] <= 10nums are unique.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.lengthn = board[i].length1 <= m, n <= 61 <= word.length <= 15board 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?
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] <= 104nums 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?
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:
+ +[0, 300].-100 <= Node.val <= 100Given 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 <= 1050 <= heights[i] <= 104Given 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.lengthcols == matrix[i].length1 <= row, cols <= 200matrix[i][j] is '0' or '1'.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:
+ +[0, 200].-100 <= Node.val <= 100-200 <= x <= 200You 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 + nnums2.length == n0 <= m, n <= 2001 <= 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?
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] <= 10A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1" +'B' -> "2" +... +'Z' -> "26" ++ +
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
"AAJF" with the grouping (1 1 10 6)"KJF" with the grouping (11 10 6)Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
Given a string s containing only digits, return the number of ways to decode it.
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").
+
+
++
Constraints:
+ +1 <= s.length <= 100s contains only digits and may contain leading zero(s).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:
+ +n.1 <= n <= 500-500 <= Node.val <= 5001 <= left <= right <= n+Follow up: Could you do it in one pass?
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] ++ +
Example 2:
+ +Input: root = [] +Output: [] ++ +
Example 3:
+ +Input: root = [1] +Output: [1] ++ +
+
Constraints:
+ +[0, 100].-100 <= Node.val <= 100+Follow up: Recursive solution is trivial, could you do it iteratively?
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 <= 8Given 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 + ... + snt = t1 + t2 + ... + tm|n - m| <= 1s1 + 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 <= 1000 <= s3.length <= 200s1, s2, and s3 consist of lowercase English letters.+
Follow up: Could you solve it using only O(s2.length) additional memory space?
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
+ ++
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:
+ +[1, 104].-231 <= Node.val <= 231 - 1Given 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:
+ +[0, 100].-104 <= Node.val <= 104Given 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:
+ +[1, 1000].-100 <= Node.val <= 100+Follow up: Could you solve it both recursively and iteratively?
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:
+ +[0, 2000].-1000 <= Node.val <= 1000Given 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:
+ +[0, 104].-100 <= Node.val <= 100Given 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 <= 3000inorder.length == preorder.length-3000 <= preorder[i], inorder[i] <= 3000preorder and inorder consist of unique values.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.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:
+ +[0, 5000].-104 <= Node.val <= 104Given 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 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:
+ +[0, 5000].-1000 <= Node.val <= 1000-1000 <= targetSum <= 1000You 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:
+ +[0, 212 - 1].-1000 <= Node.val <= 1000+
Follow-up:
+ +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 <= 30Given 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?
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 <= 200triangle[0].length == 1triangle[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?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 <= 1050 <= prices[i] <= 104A 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 * 105s consists only of printable ASCII characters.A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:
si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.sk == endWordGiven 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 <= 10endWord.length == beginWord.length1 <= wordList.length <= 5000wordList[i].length == beginWord.lengthbeginWord, endWord, and wordList[i] consist of lowercase English letters.beginWord != endWordwordList are unique.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] <= 109You 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.
+ +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->2represents the number12. +The root-to-leaf path1->3represents the number13. +Therefore, sum = 12 + 13 =25. +
Example 2:
+
+Input: root = [4,9,0,5,1] +Output: 1026 +Explanation: +The root-to-leaf path+ +4->9->5represents the number 495. +The root-to-leaf path4->9->1represents the number 491. +The root-to-leaf path4->0represents the number 40. +Therefore, sum = 495 + 491 + 40 =1026. +
+
Constraints:
+ +[1, 1000].0 <= Node.val <= 910.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 <= 16s contains only lowercase English letters.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:
+ +[0, 100].1 <= Node.val <= 100Node.val is unique for each node.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:
+ +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.length1 <= n <= 2 * 1040 <= ratings[i] <= 2 * 104Given 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 * 104Given 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 - 1nums appears exactly three times except for one element which appears once.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.valrandom_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 <= 104Node.random is null or is pointing to some node in the linked list.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 <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20s and wordDict[i] consist of only lowercase English letters.wordDict are unique.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 <= 201 <= wordDict.length <= 10001 <= wordDict[i].length <= 10s and wordDict[i] consist of only lowercase English letters.wordDict are unique.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:
+ +[0, 104].-105 <= Node.val <= 105pos is -1 or a valid index in the linked-list.+
Follow up: Can you solve it using O(1) (i.e. constant) memory?
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:
+ +[1, 5 * 104].1 <= Node.val <= 1000Given the root of a binary tree, return the preorder traversal of its nodes' values.
+
Example 1:
+
+Input: root = [1,null,2,3] +Output: [1,2,3] ++ +
Example 2:
+ +Input: root = [] +Output: [] ++ +
Example 3:
+ +Input: root = [1] +Output: [1] ++ +
+
Constraints:
+ +[0, 100].-100 <= Node.val <= 100+
Follow up: Recursive solution is trivial, could you do it iteratively?
+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] ++ +
Example 2:
+ +Input: root = [] +Output: [] ++ +
Example 3:
+ +Input: root = [1] +Output: [1] ++ +
+
Constraints:
+ +[0, 100].-100 <= Node.val <= 100+Follow up: Recursive solution is trivial, could you do it iteratively?
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 <= 30000 <= key <= 1040 <= value <= 1052 * 105 calls will be made to get and put.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:
+ +[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)?
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:
+ +'+', '-', '*', and '/'.+
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 <= 104tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].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.length1 <= n <= 5000-5000 <= nums[i] <= 5000nums are unique.nums is sorted and rotated between 1 and n times.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 - 1pop, top and getMin operations will always be called on non-empty stacks.3 * 104 calls will be made to push, pop, top, and getMin.Given a string s, return the length of the longest substring that contains at most two distinct characters.
+
Example 1:
+ +Input: s = "eceba" +Output: 3 +Explanation: The substring is "ece" which its length is 3. ++ +
Example 2:
+ +Input: s = "ccaabbb" +Output: 5 +Explanation: The substring is "aabbb" which its length is 5. ++ +
+
Constraints:
+ +1 <= s.length <= 105s consists of English letters.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 - 1nums[i] != nums[i + 1] for all valid i.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] <= 1000numbers is sorted in non-decreasing order.-1000 <= target <= 1000Given 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 - 1Given 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.length1 <= n <= 5 * 104-109 <= nums[i] <= 109+Follow-up: Could you solve the problem in linear time and in
O(1) space?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 - 10 <= k <= 105+
Follow up:
+ +O(1) extra space?Reverse bits of a given 32 bits unsigned integer.
+ +Note:
+ +-3 and the output represents the signed integer -1073741825.+
Example 1:
+ +Input: n = 00000010100101000001111010011100 +Output: 964176192 (00111001011110000010100101000000) +Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000. ++ +
Example 2:
+ +Input: n = 11111111111111111111111111111101 +Output: 3221225471 (10111111111111111111111111111111) +Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111. ++ +
+
Constraints:
+ +32+
Follow up: If this function is called many times, how would you optimize it?
+Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
+ +Note:
+ +-3.+
Example 1:
+ +Input: n = 00000000000000000000000000001011 +Output: 3 +Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits. ++ +
Example 2:
+ +Input: n = 00000000000000000000000010000000 +Output: 1 +Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit. ++ +
Example 3:
+ +Input: n = 11111111111111111111111111111101 +Output: 31 +Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits. ++ +
+
Constraints:
+ +32.+Follow up: If this function is called many times, how would you optimize it?
Table: Weather
+---------------+---------+ +| Column Name | Type | ++---------------+---------+ +| id | int | +| recordDate | date | +| temperature | int | ++---------------+---------+ +id is the column with unique values for this table. +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). ++
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 <= 1000 <= nums[i] <= 400Given 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.lengthn == grid[i].length1 <= m, n <= 300grid[i][j] is '0' or '1'.Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
+
Example 1:
+ +Input: left = 5, right = 7 +Output: 4 ++ +
Example 2:
+ +Input: left = 0, right = 0 +Output: 0 ++ +
Example 3:
+ +Input: left = 1, right = 2147483647 +Output: 0 ++ +
+
Constraints:
+ +0 <= left <= right <= 231 - 1Write an algorithm to determine if a number n is happy.
A happy number is a number defined by the following process:
+ +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 - 1Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
+
Example 1:
+
+Input: head = [1,2,6,3,4,5,6], val = 6 +Output: [1,2,3,4,5] ++ +
Example 2:
+ +Input: head = [], val = 1 +Output: [] ++ +
Example 3:
+ +Input: head = [7,7,7,7], val = 7 +Output: [] ++ +
+
Constraints:
+ +[0, 104].1 <= Node.val <= 500 <= val <= 50Given 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 +
Example 2:
+Input: s = "foo", t = "bar" +Output: false +
Example 3:
+Input: s = "paper", t = "title" +Output: true ++
+
Constraints:
+ +1 <= s.length <= 5 * 104t.length == s.lengths and t consist of any valid ascii character.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:
+ +[0, 5000].-5000 <= Node.val <= 5000+
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
+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.
[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 <= 20000 <= prerequisites.length <= 5000prerequisites[i].length == 20 <= ai, bi < numCoursesA 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 <= 2000word and prefix consist only of lowercase English letters.3 * 104 calls in total will be made to insert, search, and startsWith.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 <= 1000 <= nums[i] <= 1000Given 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] <= 104Given 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 +
Example 2:
+Input: nums = [1,2,3,4] +Output: false +
Example 3:
+Input: nums = [1,1,1,3,3,4,3,2,4,2] +Output: true ++
+
Constraints:
+ +1 <= nums.length <= 105-109 <= nums[i] <= 109Given 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] <= 1090 <= k <= 105Given 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 * 105s 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).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:
+ +push to back, peek/pop from front, size and is empty operations are valid.+
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 <= 9100 calls will be made to push, pop, top, and empty.pop and top are valid.+
Follow-up: Can you implement the stack using only one queue?
+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:
+ +[0, 100].-100 <= Node.val <= 100Given 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?
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:
+ +n.1 <= k <= n <= 1040 <= 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?
+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?
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:
+ +push to top, peek/pop from top, size, and is empty operations are valid.+
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 <= 9100 calls will be made to push, pop, peek, and empty.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.
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:
+ +[1, 105].0 <= Node.val <= 9+Follow up: Could you do it in
O(n) time and O(1) space?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:
+ +[2, 105].-109 <= Node.val <= 109Node.val are unique.p != qp and q will exist in the BST.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:
+ +[2, 105].-109 <= Node.val <= 109Node.val are unique.p != qp and q will exist in the tree.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:
+ +node should be in the same order.node should be in the same order.Custom testing:
+ +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.+
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:
+ +[2, 1000].-1000 <= Node.val <= 1000node to be deleted is in the list and is not a tail node.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] <= 30nums 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.)
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] <= 1041 <= k <= nums.lengthGiven two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
+ ++
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 * 104s 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?
+Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.
+
Example 1:
+Input: intervals = [[0,30],[5,10],[15,20]] +Output: 2 +
Example 2:
+Input: intervals = [[7,10],[2,4]] +Output: 1 ++
+
Constraints:
+ +1 <= intervals.length <= 1040 <= starti < endi <= 106Given an array of unique integers preorder, return true if it is the correct preorder traversal sequence of a binary search tree.
+
Example 1:
+
+Input: preorder = [5,2,1,3,6] +Output: true ++ +
Example 2:
+ +Input: preorder = [5,2,6,1,3] +Output: false ++ +
+
Constraints:
+ +1 <= preorder.length <= 1041 <= preorder[i] <= 104preorder are unique.+
Follow up: Could you do it using only constant space complexity?
+There is a row of n houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
The cost of painting each house with a certain color is represented by an n x 3 cost matrix costs.
costs[0][0] is the cost of painting house 0 with the color red; costs[1][2] is the cost of painting house 1 with color green, and so on...Return the minimum cost to paint all houses.
+ ++
Example 1:
+ +Input: costs = [[17,2,17],[16,16,5],[14,3,19]] +Output: 10 +Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. +Minimum cost: 2 + 5 + 3 = 10. ++ +
Example 2:
+ +Input: costs = [[7,6,2]] +Output: 2 ++ +
+
Constraints:
+ +costs.length == ncosts[i].length == 31 <= n <= 1001 <= costs[i][j] <= 20Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.
You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.
+ ++
Example 1:
+ +Input: nums = [1,2,1,3,2,5] +Output: [3,5] +Explanation: [5, 3] is also a valid answer. ++ +
Example 2:
+ +Input: nums = [-1,0] +Output: [-1,0] ++ +
Example 3:
+ +Input: nums = [0,1] +Output: [1,0] ++ +
+
Constraints:
+ +2 <= nums.length <= 3 * 104-231 <= nums[i] <= 231 - 1nums will appear twice, only two integers will appear once.An ugly number is a positive integer whose prime factors are limited to 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, therefore all of its prime factors are limited to 2, 3, and 5. ++ +
Example 3:
+ +Input: n = 14 +Output: false +Explanation: 14 is not ugly since it includes the prime factor 7. ++ +
+
Constraints:
+ +-231 <= n <= 231 - 1An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
Given an integer n, return the nth ugly number.
+
Example 1:
+ +Input: n = 10 +Output: 12 +Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers. ++ +
Example 2:
+ +Input: n = 1 +Output: 1 +Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. ++ +
+
Constraints:
+ +1 <= n <= 1690Given 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.length1 <= n <= 1040 <= nums[i] <= nnums are unique.+
Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
+ +Machine 1 (sender) has the function:
+ +string encode(vector<string> strs) {
+ // ... your code
+ return encoded_string;
+}
+Machine 2 (receiver) has the function:
+
+vector<string> decode(string s) {
+ //... your code
+ return strs;
+}
+
+
+So Machine 1 does:
+ +string encoded_string = encode(strs); ++ +
and Machine 2 does:
+ +vector<string> strs2 = decode(encoded_string); ++ +
strs2 in Machine 2 should be the same as strs in Machine 1.
Implement the encode and decode methods.
You are not allowed to solve the problem using any serialize methods (such as eval).
+
Example 1:
+ +Input: dummy_input = ["Hello","World"] +Output: ["Hello","World"] +Explanation: +Machine 1: +Codec encoder = new Codec(); +String msg = encoder.encode(strs); +Machine 1 ---msg---> Machine 2 + +Machine 2: +Codec decoder = new Codec(); +String[] strs = decoder.decode(msg); ++ +
Example 2:
+ +Input: dummy_input = [""] +Output: [""] ++ +
+
Constraints:
+ +1 <= strs.length <= 2000 <= strs[i].length <= 200strs[i] contains any possible characters out of 256 valid ASCII characters.+
Follow up: Could you write a generalized algorithm to work on any possible set of characters?
+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 - 1You are painting a fence of n posts with k different colors. You must paint the posts following these rules:
Given the two integers n and k, return the number of ways you can paint the fence.
+
Example 1:
+
+Input: n = 3, k = 2 +Output: 6 +Explanation: All the possibilities are shown. +Note that painting all the posts red or all the posts green is invalid because there cannot be three posts in a row with the same color. ++ +
Example 2:
+ +Input: n = 1, k = 1 +Output: 1 ++ +
Example 3:
+ +Input: n = 7, k = 2 +Output: 42 ++ +
+
Constraints:
+ +1 <= n <= 501 <= k <= 105[0, 231 - 1] for the given n and k.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 - 1Given 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 <= 104Given 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?
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
There is only one repeated number in nums, return this repeated number.
You must solve the problem without modifying the array nums and uses only constant extra space.
+
Example 1:
+ +Input: nums = [1,3,4,2,2] +Output: 2 ++ +
Example 2:
+ +Input: nums = [3,1,3,4,2] +Output: 3 ++ +
+
Constraints:
+ +1 <= n <= 105nums.length == n + 11 <= nums[i] <= nnums appear only once except for precisely one integer which appears two or more times.+
Follow up:
+ +nums?Given a pattern and a string s, find if s follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
+
Example 1:
+ +Input: pattern = "abba", s = "dog cat cat dog" +Output: true ++ +
Example 2:
+ +Input: pattern = "abba", s = "dog cat cat fish" +Output: false ++ +
Example 3:
+ +Input: pattern = "aaaa", s = "dog cat cat dog" +Output: false ++ +
+
Constraints:
+ +1 <= pattern.length <= 300pattern contains only lower-case English letters.1 <= s.length <= 3000s contains only lowercase English letters and spaces ' '.s does not contain any leading or trailing spaces.s are separated by a single space.Given a pattern and a string s, return true if s matches the pattern.
A string s matches a pattern if there is some bijective mapping of single characters to non-empty strings such that if each character in pattern is replaced by the string it maps to, then the resulting string is s. A bijective mapping means that no two characters map to the same string, and no character maps to two different strings.
+
Example 1:
+ +Input: pattern = "abab", s = "redblueredblue" +Output: true +Explanation: One possible mapping is as follows: +'a' -> "red" +'b' -> "blue"+ +
Example 2:
+ +Input: pattern = "aaaa", s = "asdasdasdasd" +Output: true +Explanation: One possible mapping is as follows: +'a' -> "asd" ++ +
Example 3:
+ +Input: pattern = "aabb", s = "xyzabcxzyabc" +Output: false ++ +
+
Constraints:
+ +1 <= pattern.length, s.length <= 20pattern and s consist of only lowercase English letters.You are playing a Flip Game with your friend.
+ +You are given a string currentState that contains only '+' and '-'. You and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move, and therefore the other person will be the winner.
Return all possible states of the string currentState after one valid move. You may return the answer in any order. If there is no valid move, return an empty list [].
+
Example 1:
+ +Input: currentState = "++++" +Output: ["--++","+--+","++--"] ++ +
Example 2:
+ +Input: currentState = "+" +Output: [] ++ +
+
Constraints:
+ +1 <= currentState.length <= 500currentState[i] is either '+' or '-'.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.
+ +arr = [2,3,4], the median is 3.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 <= 105findMedian.5 * 104 calls will be made to addNum and findMedian.+
Follow up:
+ +[0, 100], how would you optimize your solution?99% of all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?Given an m x n binary grid grid where each 1 marks the home of one friend, return the minimal total travel distance.
The total travel distance is the sum of the distances between the houses of the friends and the meeting point.
+ +The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.
+
Example 1:
+
+Input: grid = [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]] +Output: 6 +Explanation: Given three friends living at (0,0), (0,4), and (2,2). +The point (0,2) is an ideal meeting point, as the total travel distance of 2 + 2 + 2 = 6 is minimal. +So return 6. ++ +
Example 2:
+ +Input: grid = [[1,1]] +Output: 1 ++ +
+
Constraints:
+ +m == grid.lengthn == grid[i].length1 <= m, n <= 200grid[i][j] is either 0 or 1.grid.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:
+ +[0, 104].-1000 <= Node.val <= 1000Given 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?
You are given an empty 2D binary grid grid of size m x n. The grid represents a map where 0's represent water and 1's represent land. Initially, all the cells of grid are water cells (i.e., all the cells are 0's).
We may perform an add land operation which turns the water at position into a land. You are given an array positions where positions[i] = [ri, ci] is the position (ri, ci) at which we should operate the ith operation.
Return an array of integers answer where answer[i] is the number of islands after turning the cell (ri, ci) into a land.
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: m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]] +Output: [1,1,2,3] +Explanation: +Initially, the 2d grid is filled with water. +- Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land. We have 1 island. +- Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land. We still have 1 island. +- Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land. We have 2 islands. +- Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land. We have 3 islands. ++ +
Example 2:
+ +Input: m = 1, n = 1, positions = [[0,0]] +Output: [1] ++ +
+
Constraints:
+ +1 <= m, n, positions.length <= 1041 <= m * n <= 104positions[i].length == 20 <= ri < m0 <= ci < n+
Follow up: Could you solve it in time complexity O(k log(mn)), where k == positions.length?
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 * 104edges.length == n - 10 <= ai, bi < nai != bi(ai, bi) are distinct.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 <= 104s consists of lowercase English letters.+
Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
+A word's generalized abbreviation can be constructed by taking any number of non-overlapping and non-adjacent substrings and replacing them with their respective lengths.
+ +"abcde" can be abbreviated into:
+
+ "a3e" ("bcd" turned into "3")"1bcd1" ("a" and "e" both turned into "1")"5" ("abcde" turned into "5")"abcde" (no substrings replaced)"23" ("ab" turned into "2" and "cde" turned into "3") is invalid as the substrings chosen are adjacent."22de" ("ab" turned into "2" and "bc" turned into "2") is invalid as the substring chosen overlap.Given a string word, return a list of all the possible generalized abbreviations of word. Return the answer in any order.
+
Example 1:
+Input: word = "word" +Output: ["4","3d","2r1","2rd","1o2","1o1d","1or1","1ord","w3","w2d","w1r1","w1rd","wo2","wo1d","wor1","word"] +
Example 2:
+Input: word = "a" +Output: ["1","a"] ++
+
Constraints:
+ +1 <= word.length <= 15word consists of only lowercase English letters.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 <= 121 <= coins[i] <= 231 - 10 <= amount <= 104Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.
Return the minimum number of patches required.
+ ++
Example 1:
+ +Input: nums = [1,3], n = 6 +Output: 1 +Explanation: +Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4. +Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3]. +Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6]. +So we only need 1 patch. ++ +
Example 2:
+ +Input: nums = [1,5,10], n = 20 +Output: 2 +Explanation: The two patches can be [2, 4]. ++ +
Example 3:
+ +Input: nums = [1,2,2], n = 5 +Output: 0 ++ +
+
Constraints:
+ +1 <= nums.length <= 10001 <= nums[i] <= 104nums is sorted in ascending order.1 <= n <= 231 - 1You 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.
["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 <= 300tickets[i].length == 2fromi.length == 3toi.length == 3fromi and toi consist of uppercase English letters.fromi != toiGiven 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:
+ +O(n log n). Can you do it in linear time O(n) and possibly in a single pass?__builtin_popcount in C++)?Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.
+
Example 1:
+ +Input: s = "eceba", k = 2 +Output: 3 +Explanation: The substring is "ece" with length 3.+ +
Example 2:
+ +Input: s = "aa", k = 1 +Output: 2 +Explanation: The substring is "aa" with length 2. ++ +
+
Constraints:
+ +1 <= s.length <= 5 * 1040 <= k <= 50You 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[-106, 106].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?
Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.
Return the maximum product you can get.
+ ++
Example 1:
+ +Input: n = 2 +Output: 1 +Explanation: 2 = 1 + 1, 1 × 1 = 1. ++ +
Example 2:
+ +Input: n = 10 +Output: 36 +Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36. ++ +
+
Constraints:
+ +2 <= n <= 58Write 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 <= 105s[i] is a printable ascii character.Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
+ +Implement the MovingAverage class:
MovingAverage(int size) Initializes the object with the size of the window size.double next(int val) Returns the moving average of the last size values of the stream.+
Example 1:
+ +Input +["MovingAverage", "next", "next", "next", "next"] +[[3], [1], [10], [3], [5]] +Output +[null, 1.0, 5.5, 4.66667, 6.0] + +Explanation +MovingAverage movingAverage = new MovingAverage(3); +movingAverage.next(1); // return 1.0 = 1 / 1 +movingAverage.next(10); // return 5.5 = (1 + 10) / 2 +movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3 +movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3 ++ +
+
Constraints:
+ +1 <= size <= 1000-105 <= val <= 105104 calls will be made to next.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] <= 104k is in the range [1, the number of unique elements in the array].+
Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
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 <= 10000 <= nums1[i], nums2[i] <= 1000Given 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 <= 10000 <= nums1[i], nums2[i] <= 1000+
Follow up:
+ +nums1's size is small compared to nums2's size? Which algorithm is better?nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?Android devices have a special lock screen with a 3 x 3 grid of dots. Users can set an "unlock pattern" by connecting the dots in a specific sequence, forming a series of joined line segments where each segment's endpoints are two consecutive dots in the sequence. A sequence of k dots is a valid unlock pattern if both of the following are true:
2 and 9 without dots 5 or 6 appearing beforehand is valid because the line from dot 2 to dot 9 does not pass through the center of either dot 5 or 6.1 and 3 without dot 2 appearing beforehand is invalid because the line from dot 1 to dot 3 passes through the center of dot 2.Here are some example valid and invalid unlock patterns:
+ +
[4,1,3,6] is invalid because the line connecting dots 1 and 3 pass through dot 2, but dot 2 did not previously appear in the sequence.[4,1,9,2] is invalid because the line connecting dots 1 and 9 pass through dot 5, but dot 5 did not previously appear in the sequence.[2,4,1,3,6] is valid because it follows the conditions. The line connecting dots 1 and 3 meets the condition because dot 2 previously appeared in the sequence.[6,5,4,1,9,2] is valid because it follows the conditions. The line connecting dots 1 and 9 meets the condition because dot 5 previously appeared in the sequence.Given two integers m and n, return the number of unique and valid unlock patterns of the Android grid lock screen that consist of at least m keys and at most n keys.
Two unlock patterns are considered unique if there is a dot in one sequence that is not in the other, or the order of the dots is different.
+ ++
Example 1:
+ +Input: m = 1, n = 1 +Output: 9 ++ +
Example 2:
+ +Input: m = 1, n = 2 +Output: 65 ++ +
+
Constraints:
+ +1 <= m, n <= 9Given a string s and an integer k, rearrange s such that the same characters are at least distance k from each other. If it is not possible to rearrange the string, return an empty string "".
+
Example 1:
+ +Input: s = "aabbcc", k = 3 +Output: "abcabc" +Explanation: The same letters are at least a distance of 3 from each other. ++ +
Example 2:
+ +Input: s = "aaabc", k = 3 +Output: "" +Explanation: It is not possible to rearrange the string. ++ +
Example 3:
+ +Input: s = "aaadbbcc", k = 2 +Output: "abacabcd" +Explanation: The same letters are at least a distance of 2 from each other. ++ +
+
Constraints:
+ +1 <= s.length <= 3 * 105s consists of only lowercase English letters.0 <= k <= s.lengthGiven a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:
answer[i] % answer[j] == 0, oranswer[j] % answer[i] == 0If there are multiple solutions, return any of them.
+ ++
Example 1:
+ +Input: nums = [1,2,3] +Output: [1,2] +Explanation: [1,3] is also accepted. ++ +
Example 2:
+ +Input: nums = [1,2,4,8] +Output: [1,2,4,8] ++ +
+
Constraints:
+ +1 <= nums.length <= 10001 <= nums[i] <= 2 * 109nums are unique.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 <= 2001 <= nums[i] <= 1000nums 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?
+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 - 12 * 105 calls will be made to insert, remove, and getRandom.getRandom is called.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 <= 105ransomNote and magazine consist of lowercase English letters.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 +
Example 2:
+Input: s = "loveleetcode" +Output: 2 +
Example 3:
+Input: s = "aabb" +Output: -1 ++
+
Constraints:
+ +1 <= s.length <= 105s consists of only lowercase English letters.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 <= 1000t.length == s.length + 1s and t consist of lowercase English letters.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 <= 1000 <= t.length <= 104s 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?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 <= 105num consists of only digits.num does not have any leading zeros except for the zero itself.A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
+ +Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit.
If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction.
+
Example 1:
+ +Input: stones = [0,1,3,5,6,8,12,17] +Output: true +Explanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. ++ +
Example 2:
+ +Input: stones = [0,1,2,3,4,8,9,11] +Output: false +Explanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. ++ +
+
Constraints:
+ +2 <= stones.length <= 20000 <= stones[i] <= 231 - 1stones[0] == 0stones is sorted in a strictly increasing order.Given the root of a binary tree, return the sum of all left leaves.
A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.
+ ++
Example 1:
+
+Input: root = [3,9,20,null,null,15,7] +Output: 24 +Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively. ++ +
Example 2:
+ +Input: root = [1] +Output: 0 ++ +
+
Constraints:
+ +[1, 1000].-1000 <= Node.val <= 1000Given 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 <= 2000s consists of lowercase and/or uppercase English letters only.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 <= 2001 <= nums[i] <= 100Given 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.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
+ ++
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 * 104s and p consist of lowercase English letters.Given a string expression representing arbitrarily nested ternary expressions, evaluate the expression, and return the result of it.
You can always assume that the given expression is valid and only contains digits, '?', ':', 'T', and 'F' where 'T' is true and 'F' is false. All the numbers in the expression are one-digit numbers (i.e., in the range [0, 9]).
The conditional expressions group right-to-left (as usual in most languages), and the result of the expression will always evaluate to either a digit, 'T' or 'F'.
+
Example 1:
+ +Input: expression = "T?2:3" +Output: "2" +Explanation: If true, then result is 2; otherwise result is 3. ++ +
Example 2:
+ +Input: expression = "F?1:T?4:5" +Output: "4" +Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as: +"(F ? 1 : (T ? 4 : 5))" --> "(F ? 1 : 4)" --> "4" +or "(F ? 1 : (T ? 4 : 5))" --> "(T ? 4 : 5)" --> "4" ++ +
Example 3:
+ +Input: expression = "T?T?F:5:3" +Output: "F" +Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as: +"(T ? (T ? F : 5) : 3)" --> "(T ? F : 3)" --> "F" +"(T ? (T ? F : 5) : 3)" --> "(T ? F : 5)" --> "F" ++ +
+
Constraints:
+ +5 <= expression.length <= 104expression consists of digits, 'T', 'F', '?', and ':'.expression is a valid ternary expression and that each number is a one-digit number.Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or 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 extra space.
+
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.length1 <= n <= 1051 <= nums[i] <= nnums appears once or twice.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.
+ +[1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences.[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.
+ +[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 - 1Given 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 * 105s consists of uppercase and lowercase English letters and digits.There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.
Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
Given the array points, return the minimum number of arrows that must be shot to burst all balloons.
+
Example 1:
+ +Input: points = [[10,16],[2,8],[1,6],[7,12]] +Output: 2 +Explanation: The balloons can be burst by 2 arrows: +- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. +- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]. ++ +
Example 2:
+ +Input: points = [[1,2],[3,4],[5,6],[7,8]] +Output: 4 +Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows. ++ +
Example 3:
+ +Input: points = [[1,2],[2,3],[3,4],[4,5]] +Output: 2 +Explanation: The balloons can be burst by 2 arrows: +- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. +- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5]. ++ +
+
Constraints:
+ +1 <= points.length <= 105points[i].length == 2-231 <= xstart < xend <= 231 - 1Assume 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 * 1040 <= s.length <= 3 * 1041 <= g[i], s[j] <= 231 - 1Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].
Return true if there is a 132 pattern in nums, otherwise, return false.
+
Example 1:
+ +Input: nums = [1,2,3,4] +Output: false +Explanation: There is no 132 pattern in the sequence. ++ +
Example 2:
+ +Input: nums = [3,1,4,2] +Output: true +Explanation: There is a 132 pattern in the sequence: [1, 4, 2]. ++ +
Example 3:
+ +Input: nums = [-1,3,2,0] +Output: true +Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. ++ +
+
Constraints:
+ +n == nums.length1 <= n <= 2 * 105-109 <= nums[i] <= 109There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous.
You can feed the pigs according to these steps:
+ +minutesToDie minutes. You may not feed any other pigs during this time.minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.Given buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.
+
Example 1:
+ +Input: buckets = 4, minutesToDie = 15, minutesToTest = 15 +Output: 2 +Explanation: We can determine the poisonous bucket as follows: +At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3. +At time 15, there are 4 possible outcomes: +- If only the first pig dies, then bucket 1 must be poisonous. +- If only the second pig dies, then bucket 3 must be poisonous. +- If both pigs die, then bucket 2 must be poisonous. +- If neither pig dies, then bucket 4 must be poisonous. ++ +
Example 2:
+ +Input: buckets = 4, minutesToDie = 15, minutesToTest = 30 +Output: 2 +Explanation: We can determine the poisonous bucket as follows: +At time 0, feed the first pig bucket 1, and feed the second pig bucket 2. +At time 15, there are 2 possible outcomes: +- If either pig dies, then the poisonous bucket is the one it was fed. +- If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4. +At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed. ++ +
+
Constraints:
+ +1 <= buckets <= 10001 <= minutesToDie <= minutesToTest <= 100Given 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 <= 104s consists of lowercase English letters.You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
+ ++
Example 1:
+
+Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]] +Output: 16 +Explanation: The perimeter is the 16 yellow stripes in the image above. ++ +
Example 2:
+ +Input: grid = [[1]] +Output: 4 ++ +
Example 3:
+ +Input: grid = [[1,0]] +Output: 4 ++ +
+
Constraints:
+ +row == grid.lengthcol == grid[i].length1 <= row, col <= 100grid[i][j] is 0 or 1.grid.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.
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/
+Given a binary array nums, return the maximum number of consecutive 1's in the array if you can flip at most one 0.
+
Example 1:
+ +Input: nums = [1,0,1,1,0] +Output: 4 +Explanation: +- If we flip the first zero, nums becomes [1,1,1,1,0] and we have 4 consecutive ones. +- If we flip the second zero, nums becomes [1,0,1,1,1] and we have 3 consecutive ones. +The max number of consecutive ones is 4. ++ +
Example 2:
+ +Input: nums = [1,0,1,1,0,1] +Output: 4 +Explanation: +- If we flip the first zero, nums becomes [1,1,1,1,0,1] and we have 4 consecutive ones. +- If we flip the second zero, nums becomes [1,0,1,1,1,1] and we have 4 consecutive ones. +The max number of consecutive ones is 4. ++ +
+
Constraints:
+ +1 <= nums.length <= 105nums[i] is either 0 or 1.+
Follow up: What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?
+There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the m x n maze, the ball's start position and the destination, where start = [startrow, startcol] and destination = [destinationrow, destinationcol], return true if the ball can stop at the destination, otherwise return false.
You may assume that the borders of the maze are all walls (see examples).
+ ++
Example 1:
+
+Input: maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4] +Output: true +Explanation: One possible way is : left -> down -> left -> down -> right -> down -> right. ++ +
Example 2:
+
+Input: maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [3,2] +Output: false +Explanation: There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there. ++ +
Example 3:
+ +Input: maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [4,3], destination = [0,1] +Output: false ++ +
+
Constraints:
+ +m == maze.lengthn == maze[i].length1 <= m, n <= 100maze[i][j] is 0 or 1.start.length == 2destination.length == 20 <= startrow, destinationrow <= m0 <= startcol, destinationcol <= nGiven the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.
If the tree has more than one mode, return them in any order.
+ +Assume a BST is defined as follows:
+ ++
Example 1:
+
+Input: root = [1,null,2,2] +Output: [2] ++ +
Example 2:
+ +Input: root = [0] +Output: [0] ++ +
+
Constraints:
+ +[1, 104].-105 <= Node.val <= 105+Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects.
You are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it.
Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.
Pick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital.
The answer is guaranteed to fit in a 32-bit signed integer.
+ ++
Example 1:
+ +Input: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1] +Output: 4 +Explanation: Since your initial capital is 0, you can only start the project indexed 0. +After finishing it you will obtain profit 1 and your capital becomes 1. +With capital 1, you can either start the project indexed 1 or the project indexed 2. +Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. +Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. ++ +
Example 2:
+ +Input: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2] +Output: 6 ++ +
+
Constraints:
+ +1 <= k <= 1050 <= w <= 109n == profits.lengthn == capital.length1 <= n <= 1050 <= profits[i] <= 1040 <= capital[i] <= 109There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the m x n maze, the ball's start position and the destination, where start = [startrow, startcol] and destination = [destinationrow, destinationcol], return the shortest distance for the ball to stop at the destination. If the ball cannot stop at destination, return -1.
The distance is the number of empty spaces traveled by the ball from the start position (excluded) to the destination (included).
+ +You may assume that the borders of the maze are all walls (see examples).
+ ++
Example 1:
+
+Input: maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4] +Output: 12 +Explanation: One possible way is : left -> down -> left -> down -> right -> down -> right. +The length of the path is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12. ++ +
Example 2:
+
+Input: maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [3,2] +Output: -1 +Explanation: There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there. ++ +
Example 3:
+ +Input: maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [4,3], destination = [0,1] +Output: -1 ++ +
+
Constraints:
+ +m == maze.lengthn == maze[i].length1 <= m, n <= 100maze[i][j] is 0 or 1.start.length == 2destination.length == 20 <= startrow, destinationrow < m0 <= startcol, destinationcol < nYou 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:
1st place athlete's rank is "Gold Medal".2nd place athlete's rank is "Silver Medal".3rd place athlete's rank is "Bronze Medal".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.length1 <= n <= 1040 <= score[i] <= 106score are unique.The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
F(0) = 0, F(1) = 1 +F(n) = F(n - 1) + F(n - 2), for n > 1. ++ +
Given n, calculate F(n).
+
Example 1:
+ +Input: n = 2 +Output: 1 +Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. ++ +
Example 2:
+ +Input: n = 3 +Output: 2 +Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. ++ +
Example 3:
+ +Input: n = 4 +Output: 3 +Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. ++ +
+
Constraints:
+ +0 <= n <= 30Given the root of a binary tree, return the leftmost value in the last row of the tree.
+
Example 1:
+
+Input: root = [2,1,3] +Output: 1 ++ +
Example 2:
+
+Input: root = [1,2,3,4,null,5,6,null,null,7] +Output: 7 ++ +
+
Constraints:
+ +[1, 104].-231 <= Node.val <= 231 - 1In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring" and use the dial to spell a specific keyword to open the door.
+ +Given a string ring that represents the code engraved on the outer ring and another string key that represents the keyword that needs to be spelled, return the minimum number of steps to spell all the characters in the keyword.
Initially, the first character of the ring is aligned at the "12:00" direction. You should spell all the characters in key one by one by rotating ring clockwise or anticlockwise to make each character of the string key aligned at the "12:00" direction and then by pressing the center button.
At the stage of rotating the ring to spell the key character key[i]:
ring's characters at the "12:00" direction, where this character must equal key[i].key[i] has been aligned at the "12:00" direction, press the center button to spell, which also counts as one step. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling.+
Example 1:
+
+Input: ring = "godding", key = "gd" +Output: 4 +Explanation: +For the first key character 'g', since it is already in place, we just need 1 step to spell this character. +For the second key character 'd', we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo". +Also, we need 1 more step for spelling. +So the final output is 4. ++ +
Example 2:
+ +Input: ring = "godding", key = "godding" +Output: 13 ++ +
+
Constraints:
+ +1 <= ring.length, key.length <= 100ring and key consist of only lower case English letters.key could always be spelled by rotating ring.Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
+
Example 1:
+
+Input: root = [1,3,2,5,3,null,9] +Output: [1,3,9] ++ +
Example 2:
+ +Input: root = [1,2,3] +Output: [1,3] ++ +
+
Constraints:
+ +[0, 104].-231 <= Node.val <= 231 - 1You 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 <= 3001 <= coins[i] <= 5000coins are unique.0 <= amount <= 5000Given 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:
+ +k.Note that:
+ +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 <= 1050 <= nums[i] <= 1090 <= sum(nums[i]) <= 231 - 11 <= k <= 231 - 1Given 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 <= 105nums[i] is either 0 or 1.Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array.
A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:
0 <= i, j < nums.lengthi != j|nums[i] - nums[j]| == kNotice that |val| denotes the absolute value of val.
+
Example 1:
+ +Input: nums = [3,1,4,1,5], k = 2 +Output: 2 +Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). +Although we have two 1s in the input, we should only return the number of unique pairs. ++ +
Example 2:
+ +Input: nums = [1,2,3,4,5], k = 1 +Output: 4 +Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). ++ +
Example 3:
+ +Input: nums = [1,3,1,5,4], k = 0 +Output: 1 +Explanation: There is one 0-diff pair in the array, (1, 1). ++ +
+
Constraints:
+ +1 <= nums.length <= 104-107 <= nums[i] <= 1070 <= k <= 107You 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 <= 1050 <= nums[i] <= 105Given 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.lengthn == mat[i].length1 <= m, n <= 1041 <= m * n <= 104mat[i][j] is either 0 or 1.0 in mat.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:
+ +[1, 104].-100 <= Node.val <= 100An 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:
+ +'A') for strictly fewer than 2 days total.'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 <= 105Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
+
Example 1:
+Input: s = "Let's take LeetCode contest" +Output: "s'teL ekat edoCteeL tsetnoc" +
Example 2:
+Input: s = "God Ding" +Output: "doG gniD" ++
+
Constraints:
+ +1 <= s.length <= 5 * 104s contains printable ASCII characters.s does not contain any leading or trailing spaces.s.s are separated by a single space.Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.
+
Example 1:
+ +Input: nums = [1,4,3,2] +Output: 4 +Explanation: All possible pairings (ignoring the ordering of elements) are: +1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3 +2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3 +3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4 +So the maximum possible sum is 4.+ +
Example 2:
+ +Input: nums = [6,2,6,5,1,2] +Output: 9 +Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9. ++ +
+
Constraints:
+ +1 <= n <= 104nums.length == 2 * n-104 <= nums[i] <= 104Given 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 <= 18n consists of only digits.n does not have leading zeros.n is representing an integer in the range [1, 1018 - 1].In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.
You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.
The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.
+ +If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
+
Example 1:
+
+Input: mat = [[1,2],[3,4]], r = 1, c = 4 +Output: [[1,2,3,4]] ++ +
Example 2:
+
+Input: mat = [[1,2],[3,4]], r = 2, c = 4 +Output: [[1,2],[3,4]] ++ +
+
Constraints:
+ +m == mat.lengthn == mat[i].length1 <= m, n <= 100-1000 <= mat[i][j] <= 10001 <= r, c <= 300Given 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 <= 104s1 and s2 consist of lowercase English letters.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:
+ +root tree is in the range [1, 2000].subRoot tree is in the range [1, 1000].-104 <= root.val <= 104-104 <= subRoot.val <= 104You are given two integers height and width representing a garden of size height x width. You are also given:
tree where tree = [treer, treec] is the position of the tree in the garden,squirrel where squirrel = [squirrelr, squirrelc] is the position of the squirrel in the garden,nuts where nuts[i] = [nutir, nutic] is the position of the ith nut in the garden.The squirrel can only take at most one nut at one time and can move in four directions: up, down, left, and right, to the adjacent cell.
+ +Return the minimal distance for the squirrel to collect all the nuts and put them under the tree one by one.
+ +The distance is the number of moves.
+ ++
Example 1:
+
+Input: height = 5, width = 7, tree = [2,2], squirrel = [4,4], nuts = [[3,0], [2,5]] +Output: 12 +Explanation: The squirrel should go to the nut at [2, 5] first to achieve a minimal distance. ++ +
Example 2:
+
+Input: height = 1, width = 3, tree = [0,1], squirrel = [0,0], nuts = [[0,2]] +Output: 3 ++ +
+
Constraints:
+ +1 <= height, width <= 100tree.length == 2squirrel.length == 21 <= nuts.length <= 5000nuts[i].length == 20 <= treer, squirrelr, nutir <= height0 <= treec, squirrelc, nutic <= widthThere is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball.
Given the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7.
+
Example 1:
+
+Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0 +Output: 6 ++ +
Example 2:
+
+Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1 +Output: 12 ++ +
+
Constraints:
+ +1 <= m, n <= 500 <= maxMove <= 500 <= startRow < m0 <= startColumn < nTable: 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 | ++------+ ++
Given the root of an n-ary tree, return the postorder traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
+ ++
Example 1:
+
+Input: root = [1,null,3,2,4,null,5,6] +Output: [5,6,3,2,4,1] ++ +
Example 2:
+
+Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] +Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1] ++ +
+
Constraints:
+ +[0, 104].0 <= Node.val <= 1041000.+
Follow up: Recursive solution is trivial, could you do it iteratively?
+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:
+ +'0' to '9', '/', '+' and '-'. So does the output.±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.[1, 10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.[1, 10].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:
+ +3000000 km2), or25000000).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 | ++-------------+------------+---------+ ++
Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.
Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.
+ ++
Example 1:
+
+Input: root = [1,2,3,4] +Output: "1(2(4))(3)" +Explanation: Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3)" ++ +
Example 2:
+
+Input: root = [1,2,3,null,4] +Output: "1(2()(4))(3)" +Explanation: Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output. ++ +
+
Constraints:
+ +[1, 104].-1000 <= Node.val <= 1000You 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:
+ +[0, 2000].-104 <= Node.val <= 104You are given an array of CPU tasks, each represented by letters A to Z, and a cooling time, n. Each cycle or interval allows the completion of one task. Tasks can be completed in any order, but there's a constraint: identical tasks must be separated by at least n intervals due to cooling time.
Return the minimum number of 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 cycles 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 cycle, 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 <= 104tasks[i] is an uppercase English letter.0 <= n <= 100Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.
Note that the root node is at depth 1.
The adding rule is:
+ +depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root.cur's original left subtree should be the left subtree of the new left subtree root.cur's original right subtree should be the right subtree of the new right subtree root.depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree.+
Example 1:
+
+Input: root = [4,2,6,3,1,5], val = 1, depth = 2 +Output: [4,1,1,2,null,null,6,3,1,5] ++ +
Example 2:
+
+Input: root = [4,2,null,3,1], val = 1, depth = 3 +Output: [4,2,null,1,1,3,null,null,1] ++ +
+
Constraints:
+ +[1, 104].[1, 104].-100 <= Node.val <= 100-105 <= val <= 1051 <= depth <= the depth of tree + 1You are given m arrays, where each array is sorted in ascending order.
You can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers a and b to be their absolute difference |a - b|.
Return the maximum distance.
+ ++
Example 1:
+ +Input: arrays = [[1,2,3],[4,5],[1,2,3]] +Output: 4 +Explanation: One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array. ++ +
Example 2:
+ +Input: arrays = [[1],[1]] +Output: 0 ++ +
+
Constraints:
+ +m == arrays.length2 <= m <= 1051 <= arrays[i].length <= 500-104 <= arrays[i][j] <= 104arrays[i] is sorted in ascending order.105 integers in all the arrays.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 consist 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 <= 10000 <= k <= 1000Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.
+
Example 1:
+ +Input: c = 5 +Output: true +Explanation: 1 * 1 + 2 * 2 = 5 ++ +
Example 2:
+ +Input: c = 3 +Output: false ++ +
+
Constraints:
+ +0 <= c <= 231 - 1You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.
You are given an integer array nums representing the data status of this set after the error.
Find the number that occurs twice and the number that is missing and return them in the form of an array.
+ ++
Example 1:
+Input: nums = [1,2,2,4] +Output: [2,3] +
Example 2:
+Input: nums = [1,1] +Output: [1,2] ++
+
Constraints:
+ +2 <= nums.length <= 1041 <= nums[i] <= 104You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.
A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.
Return the length longest chain which can be formed.
+ +You do not need to use up all the given intervals. You can select pairs in any order.
+ ++
Example 1:
+ +Input: pairs = [[1,2],[2,3],[3,4]] +Output: 2 +Explanation: The longest chain is [1,2] -> [3,4]. ++ +
Example 2:
+ +Input: pairs = [[1,2],[7,8],[4,5]] +Output: 3 +Explanation: The longest chain is [1,2] -> [4,5] -> [7,8]. ++ +
+
Constraints:
+ +n == pairs.length1 <= n <= 1000-1000 <= lefti < righti <= 1000Given 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 <= 1000s consists of lowercase English letters.In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word derivative. For example, when the root "help" is followed by the word "ful", we can form a derivative "helpful".
Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the derivatives in the sentence with the root forming it. If a derivative can be replaced by more than one root, replace it with the root that has the shortest length.
Return the sentence after the replacement.
+
Example 1:
+ +Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery" +Output: "the cat was rat by the bat" ++ +
Example 2:
+ +Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs" +Output: "a a b c" ++ +
+
Constraints:
+ +1 <= dictionary.length <= 10001 <= dictionary[i].length <= 100dictionary[i] consists of only lower-case letters.1 <= sentence.length <= 106sentence consists of only lower-case letters and spaces.sentence is in the range [1, 1000]sentence is in the range [1, 1000]sentence will be separated by exactly one space.sentence does not have leading or trailing spaces.There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step:
Given an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen.
+
Example 1:
+ +Input: n = 3 +Output: 3 +Explanation: Initially, we have one character 'A'. +In step 1, we use Copy All operation. +In step 2, we use Paste operation to get 'AA'. +In step 3, we use Paste operation to get 'AAA'. ++ +
Example 2:
+ +Input: n = 1 +Output: 0 ++ +
+
Constraints:
+ +1 <= n <= 1000Given the root of a binary search tree and an integer k, return true if there exist two elements in the BST such that their sum is equal to k, or false otherwise.
+
Example 1:
+
+Input: root = [5,3,6,2,4,null,7], k = 9 +Output: true ++ +
Example 2:
+
+Input: root = [5,3,6,2,4,null,7], k = 28 +Output: false ++ +
+
Constraints:
+ +[1, 104].-104 <= Node.val <= 104root is guaranteed to be a valid binary search tree.-105 <= k <= 105An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).
+Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it.
+
Example 1:
+
+Input: img = [[1,1,1],[1,0,1],[1,1,1]] +Output: [[0,0,0],[0,0,0],[0,0,0]] +Explanation: +For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0 +For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0 +For the point (1,1): floor(8/9) = floor(0.88888889) = 0 ++ +
Example 2:
+
+Input: img = [[100,200,100],[200,50,200],[100,200,100]] +Output: [[137,141,137],[141,138,141],[137,141,137]] +Explanation: +For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137 +For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141 +For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138 ++ +
+
Constraints:
+ +m == img.lengthn == img[i].length1 <= m, n <= 2000 <= img[i][j] <= 255There is a strange printer with the following two special properties:
+ +Given a string s, return the minimum number of turns the printer needed to print it.
+
Example 1:
+ +Input: s = "aaabbb" +Output: 2 +Explanation: Print "aaa" first and then print "bbb". ++ +
Example 2:
+ +Input: s = "aba" +Output: 2 +Explanation: Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'. ++ +
+
Constraints:
+ +1 <= s.length <= 100s consists of lowercase English letters.Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.
The following rules define a valid string:
+ +'(' must have a corresponding right parenthesis ')'.')' must have a corresponding left parenthesis '('.'(' must go before the corresponding right parenthesis ')'.'*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".+
Example 1:
+Input: s = "()" +Output: true +
Example 2:
+Input: s = "(*)" +Output: true +
Example 3:
+Input: s = "(*))" +Output: true ++
+
Constraints:
+ +1 <= s.length <= 100s[i] is '(', ')' or '*'.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.lengthn == grid[i].length1 <= m, n <= 50grid[i][j] is either 0 or 1.You are given the root of a binary search tree (BST) and an integer val.
Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.
+
Example 1:
+
+Input: root = [4,2,7,1,3], val = 2 +Output: [2,1,3] ++ +
Example 2:
+
+Input: root = [4,2,7,1,3], val = 5 +Output: [] ++ +
+
Constraints:
+ +[1, 5000].1 <= Node.val <= 107root is a binary search tree.1 <= val <= 107You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.
+ ++
Example 1:
+
+Input: root = [4,2,7,1,3], val = 5 +Output: [4,2,7,1,3,5] +Explanation: Another accepted tree is: ++ ++
Example 2:
+ +Input: root = [40,20,60,10,30,50,70], val = 25 +Output: [40,20,60,10,30,50,70,null,null,25] ++ +
Example 3:
+ +Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5 +Output: [4,2,7,1,3,5] ++ +
+
Constraints:
+ +[0, 104].-108 <= Node.val <= 108Node.val are unique.-108 <= val <= 108val does not exist in the original BST.Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Implement KthLargest class:
KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream.+
Example 1:
+ +Input +["KthLargest", "add", "add", "add", "add", "add"] +[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]] +Output +[null, 4, 5, 5, 8, 8] + +Explanation +KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]); +kthLargest.add(3); // return 4 +kthLargest.add(5); // return 5 +kthLargest.add(10); // return 5 +kthLargest.add(9); // return 8 +kthLargest.add(4); // return 8 ++ +
+
Constraints:
+ +1 <= k <= 1040 <= nums.length <= 104-104 <= nums[i] <= 104-104 <= val <= 104104 calls will be made to add.k elements in the array when you search for the kth element.Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
+
Example 1:
+ +Input: nums = [-1,0,3,5,9,12], target = 9 +Output: 4 +Explanation: 9 exists in nums and its index is 4 ++ +
Example 2:
+ +Input: nums = [-1,0,3,5,9,12], target = 2 +Output: -1 +Explanation: 2 does not exist in nums so return -1 ++ +
+
Constraints:
+ +1 <= nums.length <= 104-104 < nums[i], target < 104nums are unique.nums is sorted in ascending order.Design a HashMap without using any built-in hash table libraries.
+ +Implement the MyHashMap class:
MyHashMap() initializes the object with an empty map.void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value.int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.void remove(key) removes the key and its corresponding value if the map contains the mapping for the key.+
Example 1:
+ +Input +["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"] +[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]] +Output +[null, null, null, 1, -1, null, 1, null, -1] + +Explanation +MyHashMap myHashMap = new MyHashMap(); +myHashMap.put(1, 1); // The map is now [[1,1]] +myHashMap.put(2, 2); // The map is now [[1,1], [2,2]] +myHashMap.get(1); // return 1, The map is now [[1,1], [2,2]] +myHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]] +myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value) +myHashMap.get(2); // return 1, The map is now [[1,1], [2,1]] +myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]] +myHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]] ++ +
+
Constraints:
+ +0 <= key, value <= 106104 calls will be made to put, get, and remove.Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal.
+
Example 1:
+ +Input: s1 = "sea", s2 = "eat" +Output: 231 +Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum. +Deleting "t" from "eat" adds 116 to the sum. +At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this. ++ +
Example 2:
+ +Input: s1 = "delete", s2 = "leet" +Output: 403 +Explanation: Deleting "dee" from "delete" to turn the string into "let", +adds 100[d] + 101[e] + 101[e] to the sum. +Deleting "e" from "leet" adds 101[e] to the sum. +At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403. +If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher. ++ +
+
Constraints:
+ +1 <= s1.length, s2.length <= 1000s1 and s2 consist of lowercase English letters.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 * 1041 <= nums[i] <= 10000 <= k <= 106Given 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 <= 10002 <= accounts[i].length <= 101 <= accounts[i][j].length <= 30accounts[i][0] consists of English letters.accounts[i][j] (for j > 0) is a valid email.This question is about implementing a basic elimination algorithm for Candy Crush.
+ +Given an m x n integer array board representing the grid of candy where board[i][j] represents the type of candy. A value of board[i][j] == 0 represents that the cell is empty.
The given board represents the state of the game following the player's move. Now, you need to restore the board to a stable state by crushing candies according to the following rules:
+ +You need to perform the above rules until the board becomes stable, then return the stable board.
+ ++
Example 1:
+
+Input: board = [[110,5,112,113,114],[210,211,5,213,214],[310,311,3,313,314],[410,411,412,5,414],[5,1,512,3,3],[610,4,1,613,614],[710,1,2,713,714],[810,1,2,1,1],[1,1,2,2,2],[4,1,4,4,1014]] +Output: [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[110,0,0,0,114],[210,0,0,0,214],[310,0,0,113,314],[410,0,0,213,414],[610,211,112,313,614],[710,311,412,613,714],[810,411,512,713,1014]] ++ +
Example 2:
+ +Input: board = [[1,3,5,5,2],[3,4,3,3,1],[3,2,4,5,2],[2,4,4,5,5],[1,4,4,1,1]] +Output: [[1,3,0,0,0],[3,4,0,5,2],[3,2,0,3,1],[2,4,0,5,2],[1,4,3,1,1]] ++ +
+
Constraints:
+ +m == board.lengthn == board[i].length3 <= m, n <= 501 <= board[i][j] <= 2000Given 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:
+ +[0, 1000].0 <= Node.val <= 10001 <= k <= 50Given a string formula representing a chemical formula, return the count of each atom.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
+ +One or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow.
"H2O" and "H2O2" are possible, but "H1O2" is impossible.Two formulas are concatenated together to produce another formula.
+ +"H2O2He3Mg4" is also a formula.A formula placed in parentheses, and a count (optionally added) is also a formula.
+ +"(H2O2)" and "(H2O2)3" are formulas.Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.
The test cases are generated so that all the values in the output fit in a 32-bit integer.
+ ++
Example 1:
+ +Input: formula = "H2O"
+Output: "H2O"
+Explanation: The count of elements are {'H': 2, 'O': 1}.
+
+
+Example 2:
+ +Input: formula = "Mg(OH)2"
+Output: "H2MgO2"
+Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
+
+
+Example 3:
+ +Input: formula = "K4(ON(SO3)2)2"
+Output: "K4N2O14S4"
+Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
+
+
++
Constraints:
+ +1 <= formula.length <= 1000formula consists of English letters, digits, '(', and ')'.formula is always valid.An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.
You are also given three integers sr, sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].
To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color.
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 4-directionally 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 0, so no changes are made to the image. ++ +
+
Constraints:
+ +m == image.lengthn == image[i].length1 <= m, n <= 500 <= image[i][j], color < 2160 <= sr < m0 <= sc < nGiven 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 <= 10530 <= temperatures[i] <= 100You 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:
+ +(0, 0) and reaching (n - 1, n - 1) by moving right or down through valid path cells (cells with value 0 or 1).(n - 1, n - 1), returning to (0, 0) by moving left or up through valid path cells.0.(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.lengthn == grid[i].length1 <= n <= 50grid[i][j] is -1, 0, or 1.grid[0][0] != -1grid[n - 1][n - 1] != -1You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index 0, or the step with index 1.
Return the minimum cost to reach the top of the floor.
+ ++
Example 1:
+ +Input: cost = [10,15,20] +Output: 15 +Explanation: You will start at index 1. +- Pay 15 and climb two steps to reach the top. +The total cost is 15. ++ +
Example 2:
+ +Input: cost = [1,100,1,1,1,100,1,1,100,1] +Output: 6 +Explanation: You will start at index 0. +- Pay 1 and climb two steps to reach index 2. +- Pay 1 and climb two steps to reach index 4. +- Pay 1 and climb two steps to reach index 6. +- Pay 1 and climb one step to reach index 7. +- Pay 1 and climb two steps to reach index 9. +- Pay 1 and climb one step to reach the top. +The total cost is 6. ++ +
+
Constraints:
+ +2 <= cost.length <= 10000 <= cost[i] <= 999You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.
The lock initially starts at '0000', a string representing the state of the 4 wheels.
You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
+
Example 1:
+ +Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202" +Output: 6 +Explanation: +A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202". +Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid, +because the wheels of the lock become stuck after the display becomes the dead end "0102". ++ +
Example 2:
+ +Input: deadends = ["8888"], target = "0009" +Output: 1 +Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009". ++ +
Example 3:
+ +Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888" +Output: -1 +Explanation: We cannot reach the target without getting stuck. ++ +
+
Constraints:
+ +1 <= deadends.length <= 500deadends[i].length == 4target.length == 4deadends.target and deadends[i] consist of digits only.Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.
Return any possible rearrangement of s or return "" if not possible.
+
Example 1:
+Input: s = "aab" +Output: "aba" +
Example 2:
+Input: s = "aaab" +Output: "" ++
+
Constraints:
+ +1 <= s.length <= 500s consists of lowercase English letters.Given the root of a binary search tree (BST) and an integer target, split the tree into two subtrees where the first subtree has nodes that are all smaller or equal to the target value, while the second subtree has all nodes that are greater than the target value. It is not necessarily the case that the tree contains a node with the value target.
Additionally, most of the structure of the original tree should remain. Formally, for any child c with parent p in the original tree, if they are both in the same subtree after the split, then node c should still have the parent p.
Return an array of the two roots of the two subtrees in order.
+ ++
Example 1:
+
+Input: root = [4,2,6,1,3,5,7], target = 2 +Output: [[2,1],[4,3,6,null,null,5,7]] ++ +
Example 2:
+ +Input: root = [1], target = 1 +Output: [[1],[]] ++ +
+
Constraints:
+ +[1, 50].0 <= Node.val, target <= 1000We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.
n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows.
+
Example 1:
+ +Input: n = 1, k = 1 +Output: 0 +Explanation: row 1: 0 ++ +
Example 2:
+ +Input: n = 2, k = 1 +Output: 0 +Explanation: +row 1: 0 +row 2: 01 ++ +
Example 3:
+ +Input: n = 2, k = 2 +Output: 1 +Explanation: +row 1: 0 +row 2: 01 ++ +
+
Constraints:
+ +1 <= n <= 301 <= k <= 2n - 1Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string.
Return a list of all possible strings we could create. Return the output in any order.
+ ++
Example 1:
+ +Input: s = "a1b2" +Output: ["a1b2","a1B2","A1b2","A1B2"] ++ +
Example 2:
+ +Input: s = "3z4" +Output: ["3z4","3Z4"] ++ +
+
Constraints:
+ +1 <= s.length <= 12s consists of lowercase English letters, uppercase English letters, and digits.You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k.
For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].
Return the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j].
+
Example 1:
+ +Input: arr = [1,2,3,5], k = 3 +Output: [2,5] +Explanation: The fractions to be considered in sorted order are: +1/5, 1/3, 2/5, 1/2, 3/5, and 2/3. +The third fraction is 2/5. ++ +
Example 2:
+ +Input: arr = [1,7], k = 1 +Output: [1,7] ++ +
+
Constraints:
+ +2 <= arr.length <= 10001 <= arr[i] <= 3 * 104arr[0] == 1arr[i] is a prime number for i > 0.arr are unique and sorted in strictly increasing order.1 <= k <= arr.length * (arr.length - 1) / 2+Follow up: Can you solve the problem with better than
O(n2) complexity?There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.
You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.
+
Example 1:
+
+Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 +Output: 700 +Explanation: +The graph is shown above. +The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. +Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops. ++ +
Example 2:
+
+Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 +Output: 200 +Explanation: +The graph is shown above. +The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. ++ +
Example 3:
+
+Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0 +Output: 500 +Explanation: +The graph is shown above. +The optimal path with no stops from city 0 to 2 is marked in red and has cost 500. ++ +
+
Constraints:
+ +1 <= n <= 1000 <= flights.length <= (n * (n - 1) / 2)flights[i].length == 30 <= fromi, toi < nfromi != toi1 <= pricei <= 1040 <= src, dst, k < nsrc != dstYou are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.
Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.
Return any permutation of s that satisfies this property.
+
Example 1:
+ +Input: order = "cba", s = "abcd"
+ +Output: "cbad"
+ +Explanation: "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a".
Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.
Example 2:
+ +Input: order = "bcafg", s = "abcd"
+ +Output: "bcad"
+ +Explanation: The characters "b", "c", and "a" from order dictate the order for the characters in s. The character "d" in s does not appear in order, so its position is flexible.
Following the order of appearance in order, "b", "c", and "a" from s should be arranged as "b", "c", "a". "d" can be placed at any position since it's not in order. The output "bcad" correctly follows this rule. Other arrangements like "bacd" or "bcda" would also be valid, as long as "b", "c", "a" maintain their order.
+
Constraints:
+ +1 <= order.length <= 261 <= s.length <= 200order and s consist of lowercase English letters.order are unique.We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row. Each glass holds one cup of champagne.
Then, some champagne is poured into the first glass at the top. When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it. When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on. (A glass at the bottom row has its excess champagne fall on the floor.)
+ +For example, after one cup of champagne is poured, the top most glass is full. After two cups of champagne are poured, the two glasses on the second row are half full. After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now. After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.
+ +
Now after pouring some non-negative integer cups of champagne, return how full the jth glass in the ith row is (both i and j are 0-indexed.)
+
Example 1:
+ +Input: poured = 1, query_row = 1, query_glass = 1 +Output: 0.00000 +Explanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty. ++ +
Example 2:
+ +Input: poured = 2, query_row = 1, query_glass = 1 +Output: 0.50000 +Explanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange. ++ +
Example 3:
+ +Input: poured = 100000009, query_row = 33, query_glass = 17 +Output: 1.00000 ++ +
+
Constraints:
+ +0 <= poured <= 1090 <= query_glass <= query_row < 100There are two types of soup: type A and type B. Initially, we have n ml of each type of soup. There are four kinds of operations:
100 ml of soup A and 0 ml of soup B,75 ml of soup A and 25 ml of soup B,50 ml of soup A and 50 ml of soup B, and25 ml of soup A and 75 ml of soup B.When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup.
Note that we do not have an operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time. Answers within 10-5 of the actual answer will be accepted.
+
Example 1:
+ +Input: n = 50 +Output: 0.62500 +Explanation: If we choose the first two operations, A will become empty first. +For the third operation, A and B will become empty at the same time. +For the fourth operation, B will become empty first. +So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625. ++ +
Example 2:
+ +Input: n = 100 +Output: 0.71875 ++ +
+
Constraints:
+ +0 <= n <= 109You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever.
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 <= 105routes[i] are unique.sum(routes[i].length) <= 1050 <= routes[i][j] < 1060 <= source, target < 106Given 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 <= 10002 <= arr[i] <= 109arr are unique.You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where:
difficulty[i] and profit[i] are the difficulty and the profit of the ith job, andworker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]).Every worker can be assigned at most one job, but one job can be completed multiple times.
+ +$1, then the total profit will be $3. If a worker cannot complete any job, their profit is $0.Return the maximum profit we can achieve after assigning the workers to the jobs.
+ ++
Example 1:
+ +Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7] +Output: 100 +Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately. ++ +
Example 2:
+ +Input: difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25] +Output: 0 ++ +
+
Constraints:
+ +n == difficulty.lengthn == profit.lengthm == worker.length1 <= n, m <= 1041 <= difficulty[i], profit[i], worker[i] <= 105There 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 * 104edges.length == n - 1edges[i].length == 20 <= ai, bi < nai != biA 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
Given a row x col grid of integers, how many 3 x 3 contiguous magic square subgrids are there?
Note: while a magic square can only contain numbers from 1 to 9, grid may contain numbers up to 15.
+
Example 1:
+
+Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]] +Output: 1 +Explanation: +The following subgrid is a 3 x 3 magic square: ++ ++while this one is not: +
+In total, there is only one magic square inside the given grid. +
Example 2:
+ +Input: grid = [[8]] +Output: 0 ++ +
+
Constraints:
+ +row == grid.lengthcol == grid[i].length1 <= row, col <= 100 <= grid[i][j] <= 15Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
+ ++
Example 1:
+ +Input: s = "ab#c", t = "ad#c" +Output: true +Explanation: Both s and t become "ac". ++ +
Example 2:
+ +Input: s = "ab##", t = "c#d#" +Output: true +Explanation: Both s and t become "". ++ +
Example 3:
+ +Input: s = "a#c", t = "b" +Output: false +Explanation: s becomes "c" while t becomes "b". ++ +
+
Constraints:
+ +1 <= s.length, t.length <= 200s and t only contain lowercase letters and '#' characters.+
Follow up: Can you solve it in O(n) time and O(1) space?
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 <= 1040 <= hand[i] <= 1091 <= groupSize <= hand.length+
Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
+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.length1 <= n <= 120 <= graph[i].length < ngraph[i] does not contain i.graph[a] contains b, then graph[b] contains a.An array arr a mountain if the following properties hold:
arr.length >= 3i 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 arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1].
You must solve it in O(log(arr.length)) time complexity.
+
Example 1:
+ +Input: arr = [0,1,0] +Output: 1 ++ +
Example 2:
+ +Input: arr = [0,2,1,0] +Output: 1 ++ +
Example 3:
+ +Input: arr = [0,10,5,2] +Output: 1 ++ +
+
Constraints:
+ +3 <= arr.length <= 1050 <= arr[i] <= 106arr is guaranteed to be a mountain array.There are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the ith worker and wage[i] is the minimum wage expectation for the ith worker.
We want to hire exactly k workers to form a paid group. To hire a group of k workers, we must pay them according to the following rules:
Given the integer k, return the least amount of money needed to form a paid group satisfying the above conditions. Answers within 10-5 of the actual answer will be accepted.
+
Example 1:
+ +Input: quality = [10,20,5], wage = [70,50,30], k = 2 +Output: 105.00000 +Explanation: We pay 70 to 0th worker and 35 to 2nd worker. ++ +
Example 2:
+ +Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], k = 3 +Output: 30.66667 +Explanation: We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately. ++ +
+
Constraints:
+ +n == quality.length == wage.length1 <= k <= n <= 1041 <= quality[i], wage[i] <= 104At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5.
Note that you do not have any change in hand at first.
+ +Given an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise.
+
Example 1:
+ +Input: bills = [5,5,5,10,20] +Output: true +Explanation: +From the first 3 customers, we collect three $5 bills in order. +From the fourth customer, we collect a $10 bill and give back a $5. +From the fifth customer, we give a $10 bill and a $5 bill. +Since all customers got correct change, we output true. ++ +
Example 2:
+ +Input: bills = [5,5,10,10,20] +Output: false +Explanation: +From the first two customers in order, we collect two $5 bills. +For the next two customers in order, we collect a $10 bill and give back a $5 bill. +For the last customer, we can not give the change of $15 back because we only have two $10 bills. +Since not every customer received the correct change, the answer is false. ++ +
+
Constraints:
+ +1 <= bills.length <= 105bills[i] is either 5, 10, or 20.You are given an m x n binary matrix grid.
A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's).
Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.
+ +Return the highest possible score after making any number of moves (including zero moves).
+ ++
Example 1:
+
+Input: grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]] +Output: 39 +Explanation: 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39 ++ +
Example 2:
+ +Input: grid = [[0]] +Output: 1 ++ +
+
Constraints:
+ +m == grid.lengthn == grid[i].length1 <= m, n <= 20grid[i][j] is either 0 or 1.Given a 2D integer array matrix, return the transpose of matrix.
The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
+ +
+
Example 1:
+ +Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] +Output: [[1,4,7],[2,5,8],[3,6,9]] ++ +
Example 2:
+ +Input: matrix = [[1,2,3],[4,5,6]] +Output: [[1,4],[2,5],[3,6]] ++ +
+
Constraints:
+ +m == matrix.lengthn == matrix[i].length1 <= m, n <= 10001 <= m * n <= 105-109 <= matrix[i][j] <= 109Consider 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:
+ +[1, 200].[0, 200].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 <= 104piles.length <= h <= 1091 <= piles[i] <= 109Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
+ ++
Example 1:
+
+Input: head = [1,2,3,4,5] +Output: [3,4,5] +Explanation: The middle node of the list is node 3. ++ +
Example 2:
+
+Input: head = [1,2,3,4,5,6] +Output: [4,5,6] +Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. ++ +
+
Constraints:
+ +[1, 100].1 <= Node.val <= 100You are given an encoded string s. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken:
d, the entire current tape is repeatedly written d - 1 more times in total.Given an integer k, return the kth letter (1-indexed) in the decoded string.
+
Example 1:
+ +Input: s = "leet2code3", k = 10 +Output: "o" +Explanation: The decoded string is "leetleetcodeleetleetcodeleetleetcode". +The 10th letter in the string is "o". ++ +
Example 2:
+ +Input: s = "ha22", k = 5 +Output: "h" +Explanation: The decoded string is "hahahaha". +The 5th letter is "h". ++ +
Example 3:
+ +Input: s = "a2345678999999999999999", k = 1 +Output: "a" +Explanation: The decoded string is "a" repeated 8301530446056247680 times. +The 1st letter is "a". ++ +
+
Constraints:
+ +2 <= s.length <= 100s consists of lowercase English letters and digits 2 through 9.s starts with a letter.1 <= k <= 109k is less than or equal to the length of the decoded string.263 letters.You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.
Return the minimum number of boats to carry every given person.
+ ++
Example 1:
+ +Input: people = [1,2], limit = 3 +Output: 1 +Explanation: 1 boat (1, 2) ++ +
Example 2:
+ +Input: people = [3,2,2,1], limit = 3 +Output: 3 +Explanation: 3 boats (1, 2), (2) and (3) ++ +
Example 3:
+ +Input: people = [3,5,3,4], limit = 5 +Output: 4 +Explanation: 4 boats (3), (3), (4), (5) ++ +
+
Constraints:
+ +1 <= people.length <= 5 * 1041 <= people[i] <= limit <= 3 * 104You 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 <= 1000 <= rStart < rows0 <= cStart < colsAlice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy that Bob has.
Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have.
+ +Return an integer array answer where answer[0] is the number of candies in the box that Alice must exchange, and answer[1] is the number of candies in the box that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists.
+
Example 1:
+ +Input: aliceSizes = [1,1], bobSizes = [2,2] +Output: [1,2] ++ +
Example 2:
+ +Input: aliceSizes = [1,2], bobSizes = [2,3] +Output: [1,2] ++ +
Example 3:
+ +Input: aliceSizes = [2], bobSizes = [1,3] +Output: [2,3] ++ +
+
Constraints:
+ +1 <= aliceSizes.length, bobSizes.length <= 1041 <= aliceSizes[i], bobSizes[j] <= 105Given 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 <= 20An array is monotonic if it is either monotone increasing or monotone decreasing.
+ +An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].
Given an integer array nums, return true if the given array is monotonic, or false otherwise.
+
Example 1:
+ +Input: nums = [1,2,2,3] +Output: true ++ +
Example 2:
+ +Input: nums = [6,5,4,4] +Output: true ++ +
Example 3:
+ +Input: nums = [1,3,2] +Output: false ++ +
+
Constraints:
+ +1 <= nums.length <= 105-105 <= nums[i] <= 105Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.
Return any array that satisfies this condition.
+ ++
Example 1:
+ +Input: nums = [3,1,2,4] +Output: [2,4,3,1] +Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. ++ +
Example 2:
+ +Input: nums = [0] +Output: [0] ++ +
+
Constraints:
+ +1 <= nums.length <= 50000 <= nums[i] <= 5000Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.
+
Example 1:
+ +Input: arr = [3,1,2,4] +Output: 17 +Explanation: +Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. +Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. +Sum is 17. ++ +
Example 2:
+ +Input: arr = [11,81,94,43,3] +Output: 444 ++ +
+
Constraints:
+ +1 <= arr.length <= 3 * 1041 <= arr[i] <= 3 * 104Given an array of integers nums, sort the array in ascending order and return it.
You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible.
+
Example 1:
+ +Input: nums = [5,2,3,1] +Output: [1,2,3,5] +Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5). ++ +
Example 2:
+ +Input: nums = [5,1,1,2,0,0] +Output: [0,0,1,1,2,5] +Explanation: Note that the values of nums are not necessairly unique. ++ +
+
Constraints:
+ +1 <= nums.length <= 5 * 104-5 * 104 <= nums[i] <= 5 * 104Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that:
k other songs have been played.Given n, goal, and k, return the number of possible playlists that you can create. Since the answer can be very large, return it modulo 109 + 7.
+
Example 1:
+ +Input: n = 3, goal = 3, k = 1 +Output: 6 +Explanation: There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1]. ++ +
Example 2:
+ +Input: n = 2, goal = 3, k = 0 +Output: 6 +Explanation: There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2]. ++ +
Example 3:
+ +Input: n = 2, goal = 3, k = 1 +Output: 2 +Explanation: There are 2 possible playlists: [1, 2, 1] and [2, 1, 2]. ++ +
+
Constraints:
+ +0 <= k < n <= goal <= 100Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal.
A subarray is a contiguous part of the array.
+ ++
Example 1:
+ +Input: nums = [1,0,1,0,1], goal = 2 +Output: 4 +Explanation: The 4 subarrays are bolded and underlined below: +[1,0,1,0,1] +[1,0,1,0,1] +[1,0,1,0,1] +[1,0,1,0,1] ++ +
Example 2:
+ +Input: nums = [0,0,0,0,0], goal = 0 +Output: 15 ++ +
+
Constraints:
+ +1 <= nums.length <= 3 * 104nums[i] is either 0 or 1.0 <= goal <= nums.lengthGiven an n x n array of integers matrix, return the minimum sum of any falling path through matrix.
A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1).
+
Example 1:
+
+Input: matrix = [[2,1,3],[6,5,4],[7,8,9]] +Output: 13 +Explanation: There are two falling paths with a minimum sum as shown. ++ +
Example 2:
+
+Input: matrix = [[-19,57],[-40,-5]] +Output: -59 +Explanation: The falling path with a minimum sum is shown. ++ +
+
Constraints:
+ +n == matrix.length == matrix[i].length1 <= n <= 100-100 <= matrix[i][j] <= 100The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
+ +A chess knight can move as indicated in the chess diagram below:
+
+We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
+
+Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
+
Example 1:
+ +Input: n = 1 +Output: 10 +Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient. ++ +
Example 2:
+ +Input: n = 2 +Output: 20 +Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94] ++ +
Example 3:
+ +Input: n = 3131 +Output: 136006598 +Explanation: Please take care of the mod. ++ +
+
Constraints:
+ +1 <= n <= 5000Given 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:
+ +[1, 2 * 104].1 <= Node.val <= 1051 <= low <= high <= 105Node.val are unique.You are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1.
Return the minimum number of moves to make every value in nums unique.
The test cases are generated so that the answer fits in a 32-bit integer.
+ ++
Example 1:
+ +Input: nums = [1,2,2] +Output: 1 +Explanation: After 1 move, the array could be [1, 2, 3]. ++ +
Example 2:
+ +Input: nums = [3,2,1,2,1,7] +Output: 6 +Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7]. +It can be shown with 5 or less moves that it is impossible for the array to have all unique values. ++ +
+
Constraints:
+ +1 <= nums.length <= 1050 <= nums[i] <= 105You start with an initial power of power, an initial score of 0, and a bag of tokens given as an integer array tokens, where each tokens[i] donates the value of tokeni.
Your goal is to maximize the total score by strategically playing these tokens. In one move, you can play an unplayed token in one of the two ways (but not both for the same token):
+ +tokens[i], you may play tokeni, losing tokens[i] power and gaining 1 score.1, you may play tokeni, gaining tokens[i] power and losing 1 score.Return the maximum possible score you can achieve after playing any number of tokens.
+ ++
Example 1:
+ +Input: tokens = [100], power = 50
+ +Output: 0
+ +Explanation: Since your score is 0 initially, you cannot play the token face-down. You also cannot play it face-up since your power (50) is less than tokens[0] (100).
Example 2:
+ +Input: tokens = [200,100], power = 150
+ +Output: 1
+ +Explanation: Play token1 (100) face-up, reducing your power to 50 and increasing your score to 1.
There is no need to play token0, since you cannot play it face-up to add to your score. The maximum score achievable is 1.
Example 3:
+ +Input: tokens = [100,200,300,400], power = 200
+ +Output: 2
+ +Explanation: Play the tokens in this order to get a score of 2:
100) face-up, reducing power to 100 and increasing score to 1.400) face-down, increasing power to 500 and reducing score to 0.200) face-up, reducing power to 300 and increasing score to 1.300) face-up, reducing power to 0 and increasing score to 2.The maximum score achievable is 2.
+
Constraints:
+ +0 <= tokens.length <= 10000 <= tokens[i], power < 104You 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:
+ +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 <= 10001 <= deck[i] <= 106deck are unique.An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\', or blank space ' '. These characters divide the square into contiguous regions.
Given the grid grid represented as a string array, return the number of regions.
Note that backslash characters are escaped, so a '\' is represented as '\\'.
+
Example 1:
+
+Input: grid = [" /","/ "] +Output: 2 ++ +
Example 2:
+
+Input: grid = [" /"," "] +Output: 1 ++ +
Example 3:
+
+Input: grid = ["/\\","\\/"] +Output: 5 +Explanation: Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\. ++ +
+
Constraints:
+ +n == grid.length == grid[i].length1 <= n <= 30grid[i][j] is either '/', '\', or ' '.Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).
The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).
+ ++
Example 1:
+
+Input: points = [[1,3],[-2,2]], k = 1 +Output: [[-2,2]] +Explanation: +The distance between (1, 3) and the origin is sqrt(10). +The distance between (-2, 2) and the origin is sqrt(8). +Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. +We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. ++ +
Example 2:
+ +Input: points = [[3,3],[5,-1],[-2,4]], k = 2 +Output: [[3,3],[-2,4]] +Explanation: The answer [[-2,4],[3,3]] would also be accepted. ++ +
+
Constraints:
+ +1 <= k <= points.length <= 104-104 < xi, yi < 104Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k.
A subarray is a contiguous part of an array.
+ ++
Example 1:
+ +Input: nums = [4,5,0,-2,-3,1], k = 5 +Output: 7 +Explanation: There are 7 subarrays with a sum divisible by k = 5: +[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3] ++ +
Example 2:
+ +Input: nums = [5], k = 9 +Output: 0 ++ +
+
Constraints:
+ +1 <= nums.length <= 3 * 104-104 <= nums[i] <= 1042 <= k <= 104Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
+
Example 1:
+ +Input: nums = [-4,-1,0,3,10] +Output: [0,1,9,16,100] +Explanation: After squaring, the array becomes [16,1,0,9,100]. +After sorting, it becomes [0,1,9,16,100]. ++ +
Example 2:
+ +Input: nums = [-7,-3,2,3,11] +Output: [4,9,9,49,121] ++ +
+
Constraints:
+ +1 <= nums.length <= 104-104 <= nums[i] <= 104nums is sorted in non-decreasing order.+Follow up: Squaring each element and sorting the new array is very trivial, could you find an
O(n) solution using a different approach?You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree.
In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.
+ +Return the minimum number of moves required to make every node have exactly one coin.
+ ++
Example 1:
+
+Input: root = [3,0,0] +Output: 2 +Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child. ++ +
Example 2:
+
+Input: root = [0,3,0] +Output: 3 +Explanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child. ++ +
+
Constraints:
+ +n.1 <= n <= 1000 <= Node.val <= nNode.val is n.Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.
+ +Implement the TimeMap class:
TimeMap() Initializes the object of the data structure.void set(String key, String value, int timestamp) Stores the key key with the value value at the given time timestamp.String get(String key, int timestamp) Returns a value such that set was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the value associated with the largest timestamp_prev. If there are no values, it returns "".+
Example 1:
+ +Input
+["TimeMap", "set", "get", "get", "set", "get", "get"]
+[[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]]
+Output
+[null, null, "bar", "bar", null, "bar2", "bar2"]
+
+Explanation
+TimeMap timeMap = new TimeMap();
+timeMap.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1.
+timeMap.get("foo", 1); // return "bar"
+timeMap.get("foo", 3); // return "bar", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar".
+timeMap.set("foo", "bar2", 4); // store the key "foo" and value "bar2" along with timestamp = 4.
+timeMap.get("foo", 4); // return "bar2"
+timeMap.get("foo", 5); // return "bar2"
+
+
++
Constraints:
+ +1 <= key.length, value.length <= 100key and value consist of lowercase English letters and digits.1 <= timestamp <= 107timestamp of set are strictly increasing.2 * 105 calls will be made to set and get.You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z'.
Return the lexicographically smallest string that starts at a leaf of this tree and ends at the root.
+ +As a reminder, any shorter prefix of a string is lexicographically smaller.
+ +"ab" is lexicographically smaller than "aba".A leaf of a node is a node that has no children.
+ ++
Example 1:
+
+Input: root = [0,1,2,3,4,3,4] +Output: "dba" ++ +
Example 2:
+
+Input: root = [25,1,3,1,3,0,2] +Output: "adz" ++ +
Example 3:
+
+Input: root = [2,2,1,null,1,0,null,0] +Output: "abc" ++ +
+
Constraints:
+ +[1, 8500].0 <= Node.val <= 25Given an integer array nums and an integer k, return the number of good subarrays of nums.
A good array is an array where the number of different integers in that array is exactly k.
[1,2,3,1,2] has 3 different integers: 1, 2, and 3.A subarray is a contiguous part of an array.
+ ++
Example 1:
+ +Input: nums = [1,2,1,2,3], k = 2 +Output: 7 +Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2] ++ +
Example 2:
+ +Input: nums = [1,2,1,3,4], k = 3 +Output: 3 +Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4]. ++ +
+
Constraints:
+ +1 <= nums.length <= 2 * 1041 <= nums[i], k <= nums.lengthYou are given an m x n grid where each cell can have one of three values:
0 representing an empty cell,1 representing a fresh orange, or2 representing a rotten orange.Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.
+ +Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.
+
Example 1:
+
+Input: grid = [[2,1,1],[1,1,0],[0,1,1]] +Output: 4 ++ +
Example 2:
+ +Input: grid = [[2,1,1],[0,1,1],[1,0,1]] +Output: -1 +Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. ++ +
Example 3:
+ +Input: grid = [[0,2]] +Output: 0 +Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0. ++ +
+
Constraints:
+ +m == grid.lengthn == grid[i].length1 <= m, n <= 10grid[i][j] is 0, 1, or 2.You are given a binary array nums and an integer k.
A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.
Return the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1.
A subarray is a contiguous part of an array.
+ ++
Example 1:
+ +Input: nums = [0,1,0], k = 1 +Output: 2 +Explanation: Flip nums[0], then flip nums[2]. ++ +
Example 2:
+ +Input: nums = [1,1,0], k = 2 +Output: -1 +Explanation: No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1]. ++ +
Example 3:
+ +Input: nums = [0,0,0,1,0,1,1,0], k = 3 +Output: 3 +Explanation: +Flip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0] +Flip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0] +Flip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1] ++ +
+
Constraints:
+ +1 <= nums.length <= 1051 <= k <= nums.lengthIn a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
+ +You are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi. If a trust relationship does not exist in trust array, then such a trust relationship does not exist.
Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.
+
Example 1:
+ +Input: n = 2, trust = [[1,2]] +Output: 2 ++ +
Example 2:
+ +Input: n = 3, trust = [[1,3],[2,3]] +Output: 3 ++ +
Example 3:
+ +Input: n = 3, trust = [[1,3],[2,3],[3,1]] +Output: -1 ++ +
+
Constraints:
+ +1 <= n <= 10000 <= trust.length <= 104trust[i].length == 2trust are unique.ai != bi1 <= ai, bi <= nGiven a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order.
+
Example 1:
+Input: words = ["bella","label","roller"] +Output: ["e","l","l"] +
Example 2:
+Input: words = ["cool","lock","cook"] +Output: ["c","o"] ++
+
Constraints:
+ +1 <= words.length <= 1001 <= words[i].length <= 100words[i] consists of lowercase English letters.Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b.
A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b.
+
Example 1:
+
+Input: root = [8,3,10,1,6,null,14,null,null,4,7,13] +Output: 7 +Explanation: We have various ancestor-node differences, some of which are given below : +|8 - 3| = 5 +|3 - 7| = 4 +|8 - 1| = 7 +|10 - 13| = 3 +Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.+ +
Example 2:
+
+Input: root = [1,null,2,null,0,3] +Output: 3 ++ +
+
Constraints:
+ +[2, 5000].0 <= Node.val <= 105Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer.
+ ++
Example 1:
+ +Input: arr = [1,15,7,9,2,5,10], k = 3 +Output: 84 +Explanation: arr becomes [15,15,15,9,10,10,10] ++ +
Example 2:
+ +Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4 +Output: 83 ++ +
Example 3:
+ +Input: arr = [1], k = 1 +Output: 1 ++ +
+
Constraints:
+ +1 <= arr.length <= 5000 <= arr[i] <= 1091 <= k <= arr.lengthYou are given an array of integers stones where stones[i] is the weight of the ith stone.
We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is:
x == y, both stones are destroyed, andx != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.At the end of the game, there is at most one stone left.
+ +Return the weight of the last remaining stone. If there are no stones left, return 0.
+
Example 1:
+ +Input: stones = [2,7,4,1,8,1] +Output: 1 +Explanation: +We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, +we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, +we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, +we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone. ++ +
Example 2:
+ +Input: stones = [1] +Output: 1 ++ +
+
Constraints:
+ +1 <= stones.length <= 301 <= stones[i] <= 1000You are given an array of words where each word consists of lowercase English letters.
wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB.
"abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad".A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1.
Return the length of the longest possible word chain with words chosen from the given list of words.
+
Example 1:
+ +Input: words = ["a","b","ba","bca","bda","bdca"] +Output: 4 +Explanation: One of the longest word chains is ["a","ba","bda","bdca"]. ++ +
Example 2:
+ +Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"] +Output: 5 +Explanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"]. ++ +
Example 3:
+ +Input: words = ["abcd","dbqca"] +Output: 1 +Explanation: The trivial word chain ["abcd"] is one of the longest word chains. +["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed. ++ +
+
Constraints:
+ +1 <= words.length <= 10001 <= words[i].length <= 16words[i] only consists of lowercase English letters.A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line.
You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed).
Return the number of indices where heights[i] != expected[i].
+
Example 1:
+ +Input: heights = [1,1,4,2,1,3] +Output: 3 +Explanation: +heights: [1,1,4,2,1,3] +expected: [1,1,1,2,3,4] +Indices 2, 4, and 5 do not match. ++ +
Example 2:
+ +Input: heights = [5,1,2,3,4] +Output: 5 +Explanation: +heights: [5,1,2,3,4] +expected: [1,2,3,4,5] +All indices do not match. ++ +
Example 3:
+ +Input: heights = [1,2,3,4,5] +Output: 0 +Explanation: +heights: [1,2,3,4,5] +expected: [1,2,3,4,5] +All indices match. ++ +
+
Constraints:
+ +1 <= heights.length <= 1001 <= heights[i] <= 100There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the ith minute and all those customers leave after the end of that minute.
On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the ith minute, and is 0 otherwise.
When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied.
+ +The bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once.
Return the maximum number of customers that can be satisfied throughout the day.
+ ++
Example 1:
+ +Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3 +Output: 16 +Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes. +The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16. ++ +
Example 2:
+ +Input: customers = [1], grumpy = [0], minutes = 1 +Output: 1 ++ +
+
Constraints:
+ +n == customers.length == grumpy.length1 <= minutes <= n <= 2 * 1040 <= customers[i] <= 1000grumpy[i] is either 0 or 1.On a campus represented on the X-Y plane, there are n workers and m bikes, with n <= m.
You are given an array workers of length n where workers[i] = [xi, yi] is the position of the ith worker. You are also given an array bikes of length m where bikes[j] = [xj, yj] is the position of the jth bike. All the given positions are unique.
Assign a bike to each worker. Among the available bikes and workers, we choose the (workeri, bikej) pair with the shortest Manhattan distance between each other and assign the bike to that worker.
If there are multiple (workeri, bikej) pairs with the same shortest Manhattan distance, we choose the pair with the smallest worker index. If there are multiple ways to do that, we choose the pair with the smallest bike index. Repeat this process until there are no available workers.
Return an array answer of length n, where answer[i] is the index (0-indexed) of the bike that the ith worker is assigned to.
The Manhattan distance between two points p1 and p2 is Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|.
+
Example 1:
+
+Input: workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]] +Output: [1,0] +Explanation: Worker 1 grabs Bike 0 as they are closest (without ties), and Worker 0 is assigned Bike 1. So the output is [1, 0]. ++ +
Example 2:
+
+Input: workers = [[0,0],[1,1],[2,0]], bikes = [[1,0],[2,2],[2,1]] +Output: [0,2,1] +Explanation: Worker 0 grabs Bike 0 at first. Worker 1 and Worker 2 share the same distance to Bike 2, thus Worker 1 is assigned to Bike 2, and Worker 2 will take Bike 1. So the output is [0,2,1]. ++ +
+
Constraints:
+ +n == workers.lengthm == bikes.length1 <= n <= m <= 1000workers[i].length == bikes[j].length == 20 <= xi, yi < 10000 <= xj, yj < 1000Given an integer array nums which is sorted in ascending order and all of its elements are unique and given also an integer k, return the kth missing number starting from the leftmost number of the array.
+
Example 1:
+ +Input: nums = [4,7,9,10], k = 1 +Output: 5 +Explanation: The first missing number is 5. ++ +
Example 2:
+ +Input: nums = [4,7,9,10], k = 3 +Output: 8 +Explanation: The missing numbers are [5,6,8,...], hence the third missing number is 8. ++ +
Example 3:
+ +Input: nums = [1,2,4], k = 3 +Output: 6 +Explanation: The missing numbers are [3,5,6,7,...], hence the third missing number is 6. ++ +
+
Constraints:
+ +1 <= nums.length <= 5 * 1041 <= nums[i] <= 107nums is sorted in ascending order, and all the elements are unique.1 <= k <= 108+Follow up: Can you find a logarithmic time complexity (i.e.,
O(log(n))) solution?Given a string s, return the length of the longest repeating substrings. If no repeating substring exists, return 0.
+
Example 1:
+ +Input: s = "abcd" +Output: 0 +Explanation: There is no repeating substring. ++ +
Example 2:
+ +Input: s = "abbaba" +Output: 2 +Explanation: The longest repeating substrings are "ab" and "ba", each of which occurs twice. ++ +
Example 3:
+ +Input: s = "aabcaabdaab"
+Output: 3
+Explanation: The longest repeating substring is "aab", which occurs 3 times.
+
+
++
Constraints:
+ +1 <= s.length <= 2000s consists of lowercase English letters.Given an integer array nums, return the number of non-empty subarrays with the leftmost element of the subarray not larger than other elements in the subarray.
A subarray is a contiguous part of an array.
+ ++
Example 1:
+ +Input: nums = [1,4,2,5,3] +Output: 11 +Explanation: There are 11 valid subarrays: [1],[4],[2],[5],[3],[1,4],[2,5],[1,4,2],[2,5,3],[1,4,2,5],[1,4,2,5,3]. ++ +
Example 2:
+ +Input: nums = [3,2,1] +Output: 3 +Explanation: The 3 valid subarrays are: [3],[2],[1]. ++ +
Example 3:
+ +Input: nums = [2,2,2] +Output: 6 +Explanation: There are 6 valid subarrays: [2],[2],[2],[2,2],[2,2],[2,2,2]. ++ +
+
Constraints:
+ +1 <= nums.length <= 5 * 1040 <= nums[i] <= 105On a campus represented as a 2D grid, there are n workers and m bikes, with n <= m. Each worker and bike is a 2D coordinate on this grid.
We assign one unique bike to each worker so that the sum of the Manhattan distances between each worker and their assigned bike is minimized.
+ +Return the minimum possible sum of Manhattan distances between each worker and their assigned bike.
The Manhattan distance between two points p1 and p2 is Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|.
+
Example 1:
+
+Input: workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]] +Output: 6 +Explanation: +We assign bike 0 to worker 0, bike 1 to worker 1. The Manhattan distance of both assignments is 3, so the output is 6. ++ +
Example 2:
+
+Input: workers = [[0,0],[1,1],[2,0]], bikes = [[1,0],[2,2],[2,1]] +Output: 4 +Explanation: +We first assign bike 0 to worker 0, then assign bike 1 to worker 1 or worker 2, bike 2 to worker 2 or worker 1. Both assignments lead to sum of the Manhattan distances as 4. ++ +
Example 3:
+ +Input: workers = [[0,0],[1,0],[2,0],[3,0],[4,0]], bikes = [[0,999],[1,999],[2,999],[3,999],[4,999]] +Output: 4995 ++ +
+
Constraints:
+ +n == workers.lengthm == bikes.length1 <= n <= m <= 10workers[i].length == 2bikes[i].length == 20 <= workers[i][0], workers[i][1], bikes[i][0], bikes[i][1] < 1000For two strings s and t, we say "t divides s" if and only if s = 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 <= 1000str1 and str2 consist of English uppercase letters.Given a matrix and a target, return the number of non-empty submatrices that sum to target.
A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2.
Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'.
+
Example 1:
+
+Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0 +Output: 4 +Explanation: The four 1x1 submatrices that only contain 0. ++ +
Example 2:
+ +Input: matrix = [[1,-1],[-1,1]], target = 0 +Output: 5 +Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix. ++ +
Example 3:
+ +Input: matrix = [[904]], target = 0 +Output: 0 ++ +
+
Constraints:
+ +1 <= matrix.length <= 1001 <= matrix[0].length <= 100-1000 <= matrix[i] <= 1000-10^8 <= target <= 10^8(This problem is an interactive problem.)
+ +You may recall that an array arr is a mountain array if and only if:
arr.length >= 3i 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: array = [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: array = [0,1,2,4,2,1], target = 3
+Output: -1
+Explanation: 3 does not exist in the array, so we return -1.
+
+
++
Constraints:
+ +3 <= mountain_arr.length() <= 1040 <= target <= 1090 <= mountain_arr.get(index) <= 109Given an array nums of integers and integer k, return the maximum sum such that there exists i < j with nums[i] + nums[j] = sum and sum < k. If no i, j exist satisfying this equation, return -1.
+
Example 1:
+ +Input: nums = [34,23,1,24,75,33,54,8], k = 60 +Output: 58 +Explanation: We can use 34 and 24 to sum 58 which is less than 60. ++ +
Example 2:
+ +Input: nums = [10,20,30], k = 15 +Output: -1 +Explanation: In this case it is not possible to get a pair sum less that 15. ++ +
+
Constraints:
+ +1 <= nums.length <= 1001 <= nums[i] <= 10001 <= k <= 2000There are n people in a social group labeled from 0 to n - 1. You are given an array logs where logs[i] = [timestampi, xi, yi] indicates that xi and yi will be friends at the time timestampi.
Friendship is symmetric. That means if a is friends with b, then b is friends with a. Also, person a is acquainted with a person b if a is friends with b, or a is a friend of someone acquainted with b.
Return the earliest time for which every person became acquainted with every other person. If there is no such earliest time, return -1.
+
Example 1:
+ +Input: logs = [[20190101,0,1],[20190104,3,4],[20190107,2,3],[20190211,1,5],[20190224,2,4],[20190301,0,3],[20190312,1,2],[20190322,4,5]], n = 6 +Output: 20190301 +Explanation: +The first event occurs at timestamp = 20190101, and after 0 and 1 become friends, we have the following friendship groups [0,1], [2], [3], [4], [5]. +The second event occurs at timestamp = 20190104, and after 3 and 4 become friends, we have the following friendship groups [0,1], [2], [3,4], [5]. +The third event occurs at timestamp = 20190107, and after 2 and 3 become friends, we have the following friendship groups [0,1], [2,3,4], [5]. +The fourth event occurs at timestamp = 20190211, and after 1 and 5 become friends, we have the following friendship groups [0,1,5], [2,3,4]. +The fifth event occurs at timestamp = 20190224, and as 2 and 4 are already friends, nothing happens. +The sixth event occurs at timestamp = 20190301, and after 0 and 3 become friends, we all become friends. ++ +
Example 2:
+ +Input: logs = [[0,2,0],[1,0,1],[3,0,3],[4,1,2],[7,3,1]], n = 4 +Output: 3 +Explanation: At timestamp = 3, all the persons (i.e., 0, 1, 2, and 3) become friends. ++ +
+
Constraints:
+ +2 <= n <= 1001 <= logs.length <= 104logs[i].length == 30 <= timestampi <= 1090 <= xi, yi <= n - 1xi != yitimestampi are unique.(xi, yi) occur at most one time in the input.You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth.
We want to place these books in order onto bookcase shelves that have a total width shelfWidth.
We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place.
Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books.
+ +5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf.Return the minimum possible height that the total bookshelf can be after placing shelves in this manner.
+ ++
Example 1:
+
+Input: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4 +Output: 6 +Explanation: +The sum of the heights of the 3 shelves is 1 + 3 + 2 = 6. +Notice that book number 2 does not have to be on the first shelf. ++ +
Example 2:
+ +Input: books = [[1,3],[2,4],[3,2]], shelfWidth = 6 +Output: 4 ++ +
+
Constraints:
+ +1 <= books.length <= 10001 <= thicknessi <= shelfWidth <= 10001 <= heighti <= 1000Given 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:
+ +1000.1 and 1000.to_delete.length <= 1000to_delete contains distinct values between 1 and 1000.Given a string s, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.
+
Example 1:
+ +Input: s = "leetcodeisacommunityforcoders" +Output: "ltcdscmmntyfrcdrs" ++ +
Example 2:
+ +Input: s = "aeiou" +Output: "" ++ +
+
Constraints:
+ +1 <= s.length <= 1000s consists of only lowercase English letters.Given the root of a binary tree, return the maximum average value of a subtree of that tree. Answers within 10-5 of the actual answer will be accepted.
A subtree of a tree is any node of that tree plus all its descendants.
+ +The average value of a tree is the sum of its values, divided by the number of nodes.
+ ++
Example 1:
+
+Input: root = [5,6,1] +Output: 6.00000 +Explanation: +For the node with value = 5 we have an average of (5 + 6 + 1) / 3 = 4. +For the node with value = 6 we have an average of 6 / 1 = 6. +For the node with value = 1 we have an average of 1 / 1 = 1. +So the answer is 6 which is the maximum. ++ +
Example 2:
+ +Input: root = [0,null,1] +Output: 1.00000 ++ +
+
Constraints:
+ +[1, 104].0 <= Node.val <= 105Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.
Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order.
+
Example 1:
+ +Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] +Output: [2,2,2,1,4,3,3,9,6,7,19] ++ +
Example 2:
+ +Input: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6] +Output: [22,28,8,6,17,44] ++ +
+
Constraints:
+ +1 <= arr1.length, arr2.length <= 10000 <= arr1[i], arr2[i] <= 1000arr2 are distinct.arr2[i] is in arr1.You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCoursei.
In one semester, you can take any number of courses as long as you have taken all the prerequisites in the previous semester for the courses you are taking.
+ +Return the minimum number of semesters needed to take all courses. If there is no way to take all the courses, return -1.
+
Example 1:
+
+Input: n = 3, relations = [[1,3],[2,3]] +Output: 2 +Explanation: The figure above represents the given graph. +In the first semester, you can take courses 1 and 2. +In the second semester, you can take course 3. ++ +
Example 2:
+
+Input: n = 3, relations = [[1,2],[2,3],[3,1]] +Output: -1 +Explanation: No course can be studied because they are prerequisites of each other. ++ +
+
Constraints:
+ +1 <= n <= 50001 <= relations.length <= 5000relations[i].length == 21 <= prevCoursei, nextCoursei <= nprevCoursei != nextCoursei[prevCoursei, nextCoursei] are unique.The Tribonacci sequence Tn is defined as follows:
+ +T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.
+ +Given n, return the value of Tn.
+
Example 1:
+ +Input: n = 4 +Output: 4 +Explanation: +T_3 = 0 + 1 + 1 = 2 +T_4 = 1 + 1 + 2 = 4 ++ +
Example 2:
+ +Input: n = 25 +Output: 1389537 ++ +
+
Constraints:
+ +0 <= n <= 37answer <= 2^31 - 1.Alice and Bob continue their games with piles of stones. There are a 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.
Alice and Bob take turns, with Alice starting first. Initially, M = 1.
On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M. Then, we set M = max(M, X).
The game continues until all the stones have been taken.
+ +Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get.
+ ++
Example 1:
+ +Input: piles = [2,7,9,4,4] +Output: 10 +Explanation: If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger. ++ +
Example 2:
+ +Input: piles = [1,2,3,4,5,100] +Output: 104 ++ +
+
Constraints:
+ +1 <= piles.length <= 1001 <= piles[i] <= 104Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
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.
+ +"ace" is a subsequence of "abcde".A common subsequence of two strings is a subsequence that is common to both strings.
+ ++
Example 1:
+ +Input: text1 = "abcde", text2 = "ace" +Output: 3 +Explanation: The longest common subsequence is "ace" and its length is 3. ++ +
Example 2:
+ +Input: text1 = "abc", text2 = "abc" +Output: 3 +Explanation: The longest common subsequence is "abc" and its length is 3. ++ +
Example 3:
+ +Input: text1 = "abc", text2 = "def" +Output: 0 +Explanation: There is no such common subsequence, so the result is 0. ++ +
+
Constraints:
+ +1 <= text1.length, text2.length <= 1000text1 and text2 consist of only lowercase English characters.Table: Views
+---------------+---------+ +| Column Name | Type | ++---------------+---------+ +| article_id | int | +| author_id | int | +| viewer_id | int | +| view_date | date | ++---------------+---------+ +There is no primary key (column with unique values) for this table, the table may have duplicate rows. +Each row of this table indicates that some viewer viewed an article (written by some author) on some date. +Note that equal author_id and viewer_id indicate the same person. ++ +
+ +
Write a solution to find all the authors that viewed at least one of their own articles.
+ +Return the result table sorted by id in ascending order.
The result format is in the following example.
+ ++
Example 1:
+ +Input: +Views table: ++------------+-----------+-----------+------------+ +| article_id | author_id | viewer_id | view_date | ++------------+-----------+-----------+------------+ +| 1 | 3 | 5 | 2019-08-01 | +| 1 | 3 | 6 | 2019-08-02 | +| 2 | 7 | 7 | 2019-08-01 | +| 2 | 7 | 6 | 2019-08-02 | +| 4 | 7 | 1 | 2019-07-22 | +| 3 | 4 | 4 | 2019-07-21 | +| 3 | 4 | 4 | 2019-07-21 | ++------------+-----------+-----------+------------+ +Output: ++------+ +| id | ++------+ +| 4 | +| 7 | ++------+ ++
You have n dice, and each die has k faces numbered from 1 to k.
Given three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice, so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7.
+
Example 1:
+ +Input: n = 1, k = 6, target = 3 +Output: 1 +Explanation: You throw one die with 6 faces. +There is only one way to get a sum of 3. ++ +
Example 2:
+ +Input: n = 2, k = 6, target = 7 +Output: 6 +Explanation: You throw two dice, each with 6 faces. +There are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1. ++ +
Example 3:
+ +Input: n = 30, k = 30, target = 500 +Output: 222616187 +Explanation: The answer must be returned modulo 109 + 7. ++ +
+
Constraints:
+ +1 <= n, k <= 301 <= target <= 1000You are given an array of strings words and a string chars.
A string is good if it can be formed by characters from chars (each character can only be used once).
Return the sum of lengths of all good strings in words.
+ ++
Example 1:
+ +Input: words = ["cat","bt","hat","tree"], chars = "atach" +Output: 6 +Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6. ++ +
Example 2:
+ +Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr" +Output: 10 +Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10. ++ +
+
Constraints:
+ +1 <= words.length <= 10001 <= words[i].length, chars.length <= 100words[i] and chars consist of lowercase English letters.There is a special keyboard with all keys in a single row.
+ +Given a string keyboard of length 26 indicating the layout of the keyboard (indexed from 0 to 25). Initially, your finger is at index 0. To type a character, you have to move your finger to the index of the desired character. The time taken to move your finger from index i to index j is |i - j|.
You want to type a string word. Write a function to calculate how much time it takes to type it with one finger.
+
Example 1:
+ +Input: keyboard = "abcdefghijklmnopqrstuvwxyz", word = "cba" +Output: 4 +Explanation: The index moves from 0 to 2 to write 'c' then to 1 to write 'b' then to 0 again to write 'a'. +Total time = 2 + 1 + 1 = 4. ++ +
Example 2:
+ +Input: keyboard = "pqrstuvwxyzabcdefghijklmno", word = "leetcode" +Output: 73 ++ +
+
Constraints:
+ +keyboard.length == 26keyboard contains each English lowercase letter exactly once in some order.1 <= word.length <= 104word[i] is an English lowercase letter.You have some number of sticks with positive integer lengths. These lengths are given as an array sticks, where sticks[i] is the length of the ith stick.
You can connect any two sticks of lengths x and y into one stick by paying a cost of x + y. You must connect all the sticks until there is only one stick remaining.
Return the minimum cost of connecting all the given sticks into one stick in this way.
+ ++
Example 1:
+ +Input: sticks = [2,4,3] +Output: 14 +Explanation: You start with sticks = [2,4,3]. +1. Combine sticks 2 and 3 for a cost of 2 + 3 = 5. Now you have sticks = [5,4]. +2. Combine sticks 5 and 4 for a cost of 5 + 4 = 9. Now you have sticks = [9]. +There is only one stick left, so you are done. The total cost is 5 + 9 = 14. ++ +
Example 2:
+ +Input: sticks = [1,8,3,5] +Output: 30 +Explanation: You start with sticks = [1,8,3,5]. +1. Combine sticks 1 and 3 for a cost of 1 + 3 = 4. Now you have sticks = [4,8,5]. +2. Combine sticks 4 and 5 for a cost of 4 + 5 = 9. Now you have sticks = [9,8]. +3. Combine sticks 9 and 8 for a cost of 9 + 8 = 17. Now you have sticks = [17]. +There is only one stick left, so you are done. The total cost is 4 + 9 + 17 = 30. ++ +
Example 3:
+ +Input: sticks = [5] +Output: 0 +Explanation: There is only one stick, so you don't need to do anything. The total cost is 0. ++ +
+
Constraints:
+ +1 <= sticks.length <= 1041 <= sticks[i] <= 104Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
+ ++
(Note that in the examples below, all sequences are serializations of ListNode objects.)
Example 1:
+ +Input: head = [1,2,-3,3,1] +Output: [3,1] +Note: The answer [1,2,1] would also be accepted. ++ +
Example 2:
+ +Input: head = [1,2,3,-3,4] +Output: [1,2,4] ++ +
Example 3:
+ +Input: head = [1,2,3,-3,-2] +Output: [1] ++ +
+
Constraints:
+ +1 and 1000 nodes.-1000 <= node.val <= 1000.Consider a matrix M with dimensions width * height, such that every cell has value 0 or 1, and any square sub-matrix of M of size sideLength * sideLength has at most maxOnes ones.
Return the maximum possible number of ones that the matrix M can have.
+
Example 1:
+ +Input: width = 3, height = 3, sideLength = 2, maxOnes = 1 +Output: 4 +Explanation: +In a 3*3 matrix, no 2*2 sub-matrix can have more than 1 one. +The best solution that has 4 ones is: +[1,0,1] +[0,0,0] +[1,0,1] ++ +
Example 2:
+ +Input: width = 3, height = 3, sideLength = 2, maxOnes = 2 +Output: 6 +Explanation: +[1,0,1] +[1,0,1] +[1,0,1] ++ +
+
Constraints:
+ +1 <= width, height <= 1001 <= sideLength <= width, height0 <= maxOnes <= sideLength * sideLengthYou are given a string s that consists of lower case English letters and brackets.
Reverse the strings in each pair of matching parentheses, starting from the innermost one.
+ +Your result should not contain any brackets.
+ ++
Example 1:
+ +Input: s = "(abcd)" +Output: "dcba" ++ +
Example 2:
+ +Input: s = "(u(love)i)" +Output: "iloveu" +Explanation: The substring "love" is reversed first, then the whole string is reversed. ++ +
Example 3:
+ +Input: s = "(ed(et(oc))el)" +Output: "leetcode" +Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string. ++ +
+
Constraints:
+ +1 <= s.length <= 2000s only contains lower case English characters and parentheses.In an infinite chess board with coordinates from -infinity to +infinity, you have a knight at square [0, 0].
A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
+
+Return the minimum number of steps needed to move the knight to the square [x, y]. It is guaranteed the answer exists.
+
Example 1:
+ +Input: x = 2, y = 1 +Output: 1 +Explanation: [0, 0] → [2, 1] ++ +
Example 2:
+ +Input: x = 5, y = 5 +Output: 4 +Explanation: [0, 0] → [2, 1] → [4, 2] → [3, 4] → [5, 5] ++ +
+
Constraints:
+ +-300 <= x, y <= 3000 <= |x| + |y| <= 300You are given a list of blocks, where blocks[i] = t means that the i-th block needs t units of time to be built. A block can only be built by exactly one worker.
A worker can either split into two workers (number of workers increases by one) or build a block then go home. Both decisions cost some time.
+ +The time cost of spliting one worker into two workers is given as an integer split. Note that if two workers split at the same time, they split in parallel so the cost would be split.
Output the minimum time needed to build all blocks.
+ +Initially, there is only one worker.
+ ++
Example 1:
+ +Input: blocks = [1], split = 1 +Output: 1 +Explanation: We use 1 worker to build 1 block in 1 time unit. ++ +
Example 2:
+ +Input: blocks = [1,2], split = 5 +Output: 7 +Explanation: We split the worker into 2 workers in 5 time units then assign each of them to a block so the cost is 5 + max(1, 2) = 7. ++ +
Example 3:
+ +Input: blocks = [1,2,3], split = 1 +Output: 4 +Explanation: Split 1 worker into 2, then assign the first worker to the last block and split the second worker into 2. +Then, use the two unassigned workers to build the first two blocks. +The cost is 1 + max(3, 1 + max(1, 2)) = 4. ++ +
+
Constraints:
+ +1 <= blocks.length <= 10001 <= blocks[i] <= 10^51 <= split <= 100There are n items each belonging to zero or one of m groups where group[i] is the group that the i-th item belongs to and it's equal to -1 if the i-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.
Return a sorted list of the items such that:
+ +beforeItems[i] is a list containing all the items that should come before the i-th item in the sorted array (to the left of the i-th item).Return any solution if there is more than one solution and return an empty list if there is no solution.
+ ++
Example 1:
+ +
Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]] +Output: [6,3,4,1,5,2,0,7] ++ +
Example 2:
+ +Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]] +Output: [] +Explanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list. ++ +
+
Constraints:
+ +1 <= m <= n <= 3 * 104group.length == beforeItems.length == n-1 <= group[i] <= m - 10 <= beforeItems[i].length <= n - 10 <= beforeItems[i][j] <= n - 1i != beforeItems[i][j]beforeItems[i] does not contain duplicates elements.Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise.
+
Example 1:
+ +Input: arr = [1,2,2,1,1,3] +Output: true +Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.+ +
Example 2:
+ +Input: arr = [1,2] +Output: false ++ +
Example 3:
+ +Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] +Output: true ++ +
+
Constraints:
+ +1 <= arr.length <= 1000-1000 <= arr[i] <= 1000You are given two strings s and t of the same length and an integer maxCost.
You want to change s to t. Changing the ith character of s to ith character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters).
Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost. If there is no substring from s that can be changed to its corresponding substring from t, return 0.
+
Example 1:
+ +Input: s = "abcd", t = "bcdf", maxCost = 3 +Output: 3 +Explanation: "abc" of s can change to "bcd". +That costs 3, so the maximum length is 3. ++ +
Example 2:
+ +Input: s = "abcd", t = "cdef", maxCost = 3 +Output: 1 +Explanation: Each character in s costs 2 to change to character in t, so the maximum length is 1. ++ +
Example 3:
+ +Input: s = "abcd", t = "acde", maxCost = 0 +Output: 1 +Explanation: You cannot make any change, so the maximum length is 1. ++ +
+
Constraints:
+ +1 <= s.length <= 105t.length == s.length0 <= maxCost <= 106s and t consist of only lowercase English letters.Given a string s and an integer k, return true if s is a k-palindrome.
A string is k-palindrome if it can be transformed into a palindrome by removing at most k characters from it.
+
Example 1:
+ +Input: s = "abcdeca", k = 2 +Output: true +Explanation: Remove 'b' and 'e' characters. ++ +
Example 2:
+ +Input: s = "abbababa", k = 1 +Output: true ++ +
+
Constraints:
+ +1 <= s.length <= 1000s consists of only lowercase English letters.1 <= k <= s.lengthIn 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:
+ +0 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.lengthn == grid[i].length1 <= m, n <= 150 <= grid[i][j] <= 100Given an integer n, your task is to count how many strings of length n can be formed under the following rules:
'a', 'e', 'i', 'o', 'u')'a' may only be followed by an 'e'.'e' may only be followed by an 'a' or an 'i'.'i' may not be followed by another 'i'.'o' may only be followed by an 'i' or a 'u'.'u' may only be followed by an 'a'.Since the answer may be too large, return it modulo 10^9 + 7.
+
Example 1:
+ +Input: n = 1 +Output: 5 +Explanation: All possible strings are: "a", "e", "i" , "o" and "u". ++ +
Example 2:
+ +Input: n = 2 +Output: 10 +Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua". ++ +
Example 3:
+ +Input: n = 5 +Output: 68+ +
+
Constraints:
+ +1 <= n <= 2 * 10^4You have some coins. The i-th coin has a probability prob[i] of facing heads when tossed.
Return the probability that the number of coins facing heads equals target if you toss every coin exactly once.
+
Example 1:
+Input: prob = [0.4], target = 1 +Output: 0.40000 +
Example 2:
+Input: prob = [0.5,0.5,0.5,0.5,0.5], target = 0 +Output: 0.03125 ++
+
Constraints:
+ +1 <= prob.length <= 10000 <= prob[i] <= 10 <= target <= prob.length10^-5 of the correct answer.We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].
You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.
If you choose a job that ends at time X you will be able to start another job that starts at time X.
+
Example 1:
+ +
Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70] +Output: 120 +Explanation: The subset chosen is the first and fourth job. +Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70. ++ +
Example 2:
+ +
Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60] +Output: 150 +Explanation: The subset chosen is the first, fourth and fifth job. +Profit obtained 150 = 20 + 70 + 60. ++ +
Example 3:
+ +
Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4] +Output: 6 ++ +
+
Constraints:
+ +1 <= startTime.length == endTime.length == profit.length <= 5 * 1041 <= startTime[i] < endTime[i] <= 1091 <= profit[i] <= 104You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters.
Return the maximum possible length of s.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
+ ++
Example 1:
+ +Input: arr = ["un","iq","ue"]
+Output: 4
+Explanation: All the valid concatenations are:
+- ""
+- "un"
+- "iq"
+- "ue"
+- "uniq" ("un" + "iq")
+- "ique" ("iq" + "ue")
+Maximum length is 4.
+
+
+Example 2:
+ +Input: arr = ["cha","r","act","ers"]
+Output: 6
+Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers").
+
+
+Example 3:
+ +Input: arr = ["abcdefghijklmnopqrstuvwxyz"] +Output: 26 +Explanation: The only string in arr has all 26 characters. ++ +
+
Constraints:
+ +1 <= arr.length <= 161 <= arr[i].length <= 26arr[i] contains only lowercase English letters.The diameter of a tree is the number of edges in the longest path in that tree.
+ +There is an undirected tree of n nodes labeled from 0 to n - 1. You are given a 2D array edges where edges.length == n - 1 and edges[i] = [ai, bi] indicates that there is an undirected edge between nodes ai and bi in the tree.
Return the diameter of the tree.
+ ++
Example 1:
+
+Input: edges = [[0,1],[0,2]] +Output: 2 +Explanation: The longest path of the tree is the path 1 - 0 - 2. ++ +
Example 2:
+
+Input: edges = [[0,1],[1,2],[2,3],[1,4],[4,5]] +Output: 4 +Explanation: The longest path of the tree is the path 3 - 2 - 1 - 4 - 5. ++ +
+
Constraints:
+ +n == edges.length + 11 <= n <= 1040 <= ai, bi < nai != biGiven an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
+ ++
Example 1:
+ +Input: nums = [1,1,2,1,1], k = 3 +Output: 2 +Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1]. ++ +
Example 2:
+ +Input: nums = [2,4,6], k = 1 +Output: 0 +Explanation: There are no odd numbers in the array. ++ +
Example 3:
+ +Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2 +Output: 16 ++ +
+
Constraints:
+ +1 <= nums.length <= 500001 <= nums[i] <= 10^51 <= k <= nums.lengthGiven 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:
+ +AB (A concatenated with B), where A and B are valid strings, or(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 <= 105s[i] is either'(' , ')', or lowercase English letter.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 <= 141 <= words[i].length <= 151 <= letters.length <= 100letters[i].length == 1score.length == 260 <= score[i] <= 10words[i], letters[i] contains only lower case English letters.You are given an immutable linked list, print out all values of each node in reverse with the help of the following interface:
+ +ImmutableListNode: An interface of immutable linked list, you are given the head of the list.You need to use the following functions to access the linked list (you can't access the ImmutableListNode directly):
ImmutableListNode.printValue(): Print value of the current node.ImmutableListNode.getNext(): Return the next node.The input is only given to initialize the linked list internally. You must solve this problem without modifying the linked list. In other words, you must operate the linked list using only the mentioned APIs.
+ ++
Example 1:
+ +Input: head = [1,2,3,4] +Output: [4,3,2,1] ++ +
Example 2:
+ +Input: head = [0,-4,-1,3,-5] +Output: [-5,3,-1,-4,0] ++ +
Example 3:
+ +Input: head = [-2,0,6,4,4,-6] +Output: [-6,4,4,6,0,-2] ++ +
+
Constraints:
+ +[1, 1000].[-1000, 1000].+ +
Follow up:
+ +Could you solve this problem in:
+ +On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points.
You can move according to these rules:
+ +1 second, you can either:
+
+ sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).+
Example 1:
+Input: points = [[1,1],[3,4],[-1,0]] +Output: 7 +Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0] +Time from [1,1] to [3,4] = 3 seconds +Time from [3,4] to [-1,0] = 4 seconds +Total time = 7 seconds+ +
Example 2:
+ +Input: points = [[3,2],[-2,2]] +Output: 5 ++ +
+
Constraints:
+ +points.length == n1 <= n <= 100points[i].length == 2-1000 <= points[i][0], points[i][1] <= 1000You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).
Given two integers steps and arrLen, return the number of ways such that your pointer is still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 109 + 7.
+
Example 1:
+ +Input: steps = 3, arrLen = 2 +Output: 4 +Explanation: There are 4 differents ways to stay at index 0 after 3 steps. +Right, Left, Stay +Stay, Right, Left +Right, Stay, Left +Stay, Stay, Stay ++ +
Example 2:
+ +Input: steps = 2, arrLen = 4 +Output: 2 +Explanation: There are 2 differents ways to stay at index 0 after 2 steps +Right, Left +Stay, Stay ++ +
Example 3:
+ +Input: steps = 4, arrLen = 2 +Output: 8 ++ +
+
Constraints:
+ +1 <= steps <= 5001 <= arrLen <= 106A set of real numbers can be represented as the union of several disjoint intervals, where each interval is in the form [a, b). A real number x is in the set if one of its intervals [a, b) contains x (i.e. a <= x < b).
You are given a sorted list of disjoint intervals intervals representing a set of real numbers as described above, where intervals[i] = [ai, bi] represents the interval [ai, bi). You are also given another interval toBeRemoved.
Return the set of real numbers with the interval toBeRemoved removed from intervals. In other words, return the set of real numbers such that every x in the set is in intervals but not in toBeRemoved. Your answer should be a sorted list of disjoint intervals as described above.
+
Example 1:
+
+Input: intervals = [[0,2],[3,4],[5,7]], toBeRemoved = [1,6] +Output: [[0,1],[6,7]] ++ +
Example 2:
+
+Input: intervals = [[0,5]], toBeRemoved = [2,3] +Output: [[0,2],[3,5]] ++ +
Example 3:
+ +Input: intervals = [[-5,-4],[-3,-2],[1,2],[3,5],[8,9]], toBeRemoved = [-1,4] +Output: [[-5,-4],[-3,-2],[4,5],[8,9]] ++ +
+
Constraints:
+ +1 <= intervals.length <= 104-109 <= ai < bi <= 109There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.
You are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3.
Return a list of groups such that each person i is in a group of size groupSizes[i].
Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.
+ ++
Example 1:
+ +Input: groupSizes = [3,3,3,3,3,1,3] +Output: [[5],[0,1,2],[3,4,6]] +Explanation: +The first group is [5]. The size is 1, and groupSizes[5] = 1. +The second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3. +The third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3. +Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]]. ++ +
Example 2:
+ +Input: groupSizes = [2,1,3,3,3,2] +Output: [[1],[0,5],[2,3,4]] ++ +
+
Constraints:
+ +groupSizes.length == n1 <= n <= 5001 <= groupSizes[i] <= nGiven an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.
+ ++
Example 1:
+ +Input: arr = [1,2,2,6,6,6,6,7,10] +Output: 6 ++ +
Example 2:
+ +Input: arr = [1,1] +Output: 1 ++ +
+
Constraints:
+ +1 <= arr.length <= 1040 <= arr[i] <= 105Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts.
A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column.
+
Example 1:
+
+Input: grid = [[1,2,3],[4,5,6],[7,8,9]] +Output: 13 +Explanation: +The possible falling paths are: +[1,5,9], [1,5,7], [1,6,7], [1,6,8], +[2,4,8], [2,4,9], [2,6,7], [2,6,8], +[3,4,8], [3,4,9], [3,5,7], [3,5,9] +The falling path with the smallest sum is [1,5,7], so the answer is 13. ++ +
Example 2:
+ +Input: grid = [[7]] +Output: 7 ++ +
+
Constraints:
+ +n == grid.length == grid[i].length1 <= n <= 200-99 <= grid[i][j] <= 99An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
+ +Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
+
Example 1:
+Input: low = 100, high = 300 +Output: [123,234] +
Example 2:
+Input: low = 1000, high = 13000 +Output: [1234,2345,3456,4567,5678,6789,12345] ++
+
Constraints:
+ +10 <= low <= high <= 10^9Given a binary tree root and an integer target, delete all the leaf nodes with value target.
Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot).
+
Example 1:
+ +
Input: root = [1,2,3,2,null,2,4], target = 2 +Output: [1,null,3,null,4] +Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). +After removing, new nodes become leaf nodes with value (target = 2) (Picture in center). ++ +
Example 2:
+ +
Input: root = [1,3,3,3,2], target = 3 +Output: [1,3,null,null,2] ++ +
Example 3:
+ +
Input: root = [1,2,null,2,null,2], target = 2 +Output: [1] +Explanation: Leaf nodes in green with value (target = 2) are removed at each step. ++ +
+
Constraints:
+ +[1, 3000].1 <= Node.val, target <= 1000There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n).
There are n + 1 taps located at points [0, 1, ..., n] in the garden.
Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open.
Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.
+ ++
Example 1:
+
+Input: n = 5, ranges = [3,4,1,1,0,0] +Output: 1 +Explanation: The tap at point 0 can cover the interval [-3,3] +The tap at point 1 can cover the interval [-3,5] +The tap at point 2 can cover the interval [1,3] +The tap at point 3 can cover the interval [2,4] +The tap at point 4 can cover the interval [4,4] +The tap at point 5 can cover the interval [5,5] +Opening Only the second tap will water the whole garden [0,5] ++ +
Example 2:
+ +Input: n = 3, ranges = [0,0,0,0] +Output: -1 +Explanation: Even if you activate all the four taps you cannot water the whole garden. ++ +
+
Constraints:
+ +1 <= n <= 104ranges.length == n + 10 <= ranges[i] <= 100There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.
Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number.
Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.
+ ++
Example 1:
+
+Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4 +Output: 3 +Explanation: The figure above describes the graph. +The neighboring cities at a distanceThreshold = 4 for each city are: +City 0 -> [City 1, City 2] +City 1 -> [City 0, City 2, City 3] +City 2 -> [City 0, City 1, City 3] +City 3 -> [City 1, City 2] +Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number. ++ +
Example 2:
+
+Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2 +Output: 0 +Explanation: The figure above describes the graph. +The neighboring cities at a distanceThreshold = 2 for each city are: +City 0 -> [City 1] +City 1 -> [City 0, City 4] +City 2 -> [City 3, City 4] +City 3 -> [City 2, City 4] +City 4 -> [City 1, City 2, City 3] +The city 0 has 1 neighboring city at a distanceThreshold = 2. ++ +
+
Constraints:
+ +2 <= n <= 1001 <= edges.length <= n * (n - 1) / 2edges[i].length == 30 <= fromi < toi < n1 <= weighti, distanceThreshold <= 10^4(fromi, toi) are distinct.You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs j where 0 <= j < i).
You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day.
You are given an integer array jobDifficulty and an integer d. The difficulty of the ith job is jobDifficulty[i].
Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.
+
Example 1:
+
+Input: jobDifficulty = [6,5,4,3,2,1], d = 2 +Output: 7 +Explanation: First day you can finish the first 5 jobs, total difficulty = 6. +Second day you can finish the last job, total difficulty = 1. +The difficulty of the schedule = 6 + 1 = 7 ++ +
Example 2:
+ +Input: jobDifficulty = [9,9,9], d = 4 +Output: -1 +Explanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs. ++ +
Example 3:
+ +Input: jobDifficulty = [1,1,1], d = 3 +Output: 3 +Explanation: The schedule is one job per day. total difficulty will be 3. ++ +
+
Constraints:
+ +1 <= jobDifficulty.length <= 3000 <= jobDifficulty[i] <= 10001 <= d <= 10You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row.
A row i is weaker than a row j if one of the following is true:
i is less than the number of soldiers in row j.i < j.Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.
+
Example 1:
+ +Input: mat = +[[1,1,0,0,0], + [1,1,1,1,0], + [1,0,0,0,0], + [1,1,0,0,0], + [1,1,1,1,1]], +k = 3 +Output: [2,0,3] +Explanation: +The number of soldiers in each row is: +- Row 0: 2 +- Row 1: 4 +- Row 2: 1 +- Row 3: 2 +- Row 4: 5 +The rows ordered from weakest to strongest are [2,0,3,1,4]. ++ +
Example 2:
+ +Input: mat = +[[1,0,0,0], + [1,1,1,1], + [1,0,0,0], + [1,0,0,0]], +k = 2 +Output: [0,2] +Explanation: +The number of soldiers in each row is: +- Row 0: 1 +- Row 1: 4 +- Row 2: 1 +- Row 3: 1 +The rows ordered from weakest to strongest are [0,2,3,1]. ++ +
+
Constraints:
+ +m == mat.lengthn == mat[i].length2 <= n, m <= 1001 <= k <= mmatrix[i][j] is either 0 or 1.You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character.
Return the minimum number of steps to make t an anagram of s.
An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.
+ ++
Example 1:
+ +Input: s = "bab", t = "aba" +Output: 1 +Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s. ++ +
Example 2:
+ +Input: s = "leetcode", t = "practice" +Output: 5 +Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s. ++ +
Example 3:
+ +Input: s = "anagram", t = "mangaar" +Output: 0 +Explanation: "anagram" and "mangaar" are anagrams. ++ +
+
Constraints:
+ +1 <= s.length <= 5 * 104s.length == t.lengths and t consist of lowercase English letters only.You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.
Return the array after sorting it.
+ ++
Example 1:
+ +Input: arr = [0,1,2,3,4,5,6,7,8] +Output: [0,1,2,4,8,3,5,6,7] +Explantion: [0] is the only integer with 0 bits. +[1,2,4,8] all have 1 bit. +[3,5,6] have 2 bits. +[7] has 3 bits. +The sorted array by bits is [0,1,2,4,8,3,5,6,7] ++ +
Example 2:
+ +Input: arr = [1024,512,256,128,64,32,16,8,4,2,1] +Output: [1,2,4,8,16,32,64,128,256,512,1024] +Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order. ++ +
+
Constraints:
+ +1 <= arr.length <= 5000 <= arr[i] <= 104Given n orders, each order consist in pickup and delivery services.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
+ +Since the answer may be too large, return it modulo 10^9 + 7.
+ ++
Example 1:
+ +Input: n = 1 +Output: 1 +Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1. ++ +
Example 2:
+ +Input: n = 2 +Output: 6 +Explanation: All possible orders: +(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1). +This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2. ++ +
Example 3:
+ +Input: n = 3 +Output: 90 ++ +
+
Constraints:
+ +1 <= n <= 500You 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.length1 <= n <= 104-1 <= leftChild[i], rightChild[i] <= n - 1Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order.
A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.
+ ++
Example 1:
+ +Input: matrix = [[3,7,8],[9,11,13],[15,16,17]] +Output: [15] +Explanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column. ++ +
Example 2:
+ +Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]] +Output: [12] +Explanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column. ++ +
Example 3:
+ +Input: matrix = [[7,8],[1,2]] +Output: [7] +Explanation: 7 is the only lucky number since it is the minimum in its row and the maximum in its column. ++ +
+
Constraints:
+ +m == mat.lengthn == mat[i].length1 <= n, m <= 501 <= matrix[i][j] <= 105.There are n soldiers standing in a line. Each soldier is assigned a unique rating value.
You have to form a team of 3 soldiers amongst them under the following rules:
+ +i, j, k) with rating (rating[i], rating[j], rating[k]).rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n).Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).
+ ++
Example 1:
+ +Input: rating = [2,5,3,4,1] +Output: 3 +Explanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). ++ +
Example 2:
+ +Input: rating = [2,1,3] +Output: 0 +Explanation: We can't form any team given the conditions. ++ +
Example 3:
+ +Input: rating = [1,2,3,4] +Output: 4 ++ +
+
Constraints:
+ +n == rating.length3 <= n <= 10001 <= rating[i] <= 105rating are unique.Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules:
If the current number is even, you have to divide it by 2.
If the current number is odd, you have to add 1 to it.
It is guaranteed that you can always reach one for all test cases.
+ ++
Example 1:
+ +Input: s = "1101" +Output: 6 +Explanation: "1101" corressponds to number 13 in their decimal representation. +Step 1) 13 is odd, add 1 and obtain 14. +Step 2) 14 is even, divide by 2 and obtain 7. +Step 3) 7 is odd, add 1 and obtain 8. +Step 4) 8 is even, divide by 2 and obtain 4. +Step 5) 4 is even, divide by 2 and obtain 2. +Step 6) 2 is even, divide by 2 and obtain 1. ++ +
Example 2:
+ +Input: s = "10" +Output: 1 +Explanation: "10" corressponds to number 2 in their decimal representation. +Step 1) 2 is even, divide by 2 and obtain 1. ++ +
Example 3:
+ +Input: s = "1" +Output: 0 ++ +
+
Constraints:
+ +1 <= s.length <= 500s consists of characters '0' or '1's[0] == '1'You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers:
+You should build the array arr which has the following properties:
+ +arr has exactly n integers.1 <= arr[i] <= m where (0 <= i < n).arr, the value search_cost is equal to k.Return the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 109 + 7.
+
Example 1:
+ +Input: n = 2, m = 3, k = 1 +Output: 6 +Explanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3] ++ +
Example 2:
+ +Input: n = 5, m = 2, k = 3 +Output: 0 +Explanation: There are no possible arrays that satisfy the mentioned conditions. ++ +
Example 3:
+ +Input: n = 9, m = 1, k = 1 +Output: 1 +Explanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1] ++ +
+
Constraints:
+ +1 <= n <= 501 <= m <= 1000 <= k <= nGiven a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring).
The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.
+ ++
Example 1:
+ +Input: s = "011101" +Output: 5 +Explanation: +All possible ways of splitting s into two non-empty substrings are: +left = "0" and right = "11101", score = 1 + 4 = 5 +left = "01" and right = "1101", score = 1 + 3 = 4 +left = "011" and right = "101", score = 1 + 2 = 3 +left = "0111" and right = "01", score = 1 + 1 = 2 +left = "01110" and right = "1", score = 2 + 1 = 3 ++ +
Example 2:
+ +Input: s = "00111" +Output: 5 +Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5 ++ +
Example 3:
+ +Input: s = "1111" +Output: 3 ++ +
+
Constraints:
+ +2 <= s.length <= 500s consists of characters '0' and '1' only.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 <= 1051 <= nums[i].length <= 1051 <= sum(nums[i].length) <= 1051 <= nums[i][j] <= 105Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
+ ++
Example 1:
+ +Input: nums = [10,2,-10,5,20], k = 2 +Output: 37 +Explanation: The subsequence is [10, 2, 5, 20]. ++ +
Example 2:
+ +Input: nums = [-1,-2,-3], k = 1 +Output: -1 +Explanation: The subsequence must be non-empty, so we choose the largest number. ++ +
Example 3:
+ +Input: nums = [10,-2,-10,-5,20], k = 2 +Output: 23 +Explanation: The subsequence is [10, -2, -5, 20]. ++ +
+
Constraints:
+ +1 <= k <= nums.length <= 105-104 <= nums[i] <= 104A row-sorted binary matrix means that all elements are 0 or 1 and each row of the matrix is sorted in non-decreasing order.
Given a row-sorted binary matrix binaryMatrix, return the index (0-indexed) of the leftmost column with a 1 in it. If such an index does not exist, return -1.
You can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface:
BinaryMatrix.get(row, col) returns the element of the matrix at index (row, col) (0-indexed).BinaryMatrix.dimensions() returns the dimensions of the matrix as a list of 2 elements [rows, cols], which means the matrix is rows x cols.Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.
For custom testing purposes, the input will be the entire binary matrix mat. You will not have access to the binary matrix directly.
+
Example 1:
+
+Input: mat = [[0,0],[1,1]] +Output: 0 ++ +
Example 2:
+
+Input: mat = [[0,0],[0,1]] +Output: 1 ++ +
Example 3:
+
+Input: mat = [[0,0],[0,0]] +Output: -1 ++ +
+
Constraints:
+ +rows == mat.lengthcols == mat[i].length1 <= rows, cols <= 100mat[i][j] is either 0 or 1.mat[i] is sorted in non-decreasing order.You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city.
It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.
+ ++
Example 1:
+ +Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]] +Output: "Sao Paulo" +Explanation: Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo". ++ +
Example 2:
+ +Input: paths = [["B","C"],["D","B"],["C","A"]] +Output: "A" +Explanation: All possible trips are: +"D" -> "B" -> "C" -> "A". +"B" -> "C" -> "A". +"C" -> "A". +"A". +Clearly the destination city is "A". ++ +
Example 3:
+ +Input: paths = [["A","Z"]] +Output: "Z" ++ +
+
Constraints:
+ +1 <= paths.length <= 100paths[i].length == 21 <= cityAi.length, cityBi.length <= 10cityAi != cityBiGiven an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.
+
Example 1:
+ +Input: nums = [8,2,4,7], limit = 4 +Output: 2 +Explanation: All subarrays are: +[8] with maximum absolute diff |8-8| = 0 <= 4. +[8,2] with maximum absolute diff |8-2| = 6 > 4. +[8,2,4] with maximum absolute diff |8-2| = 6 > 4. +[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. +[2] with maximum absolute diff |2-2| = 0 <= 4. +[2,4] with maximum absolute diff |2-4| = 2 <= 4. +[2,4,7] with maximum absolute diff |2-7| = 5 > 4. +[4] with maximum absolute diff |4-4| = 0 <= 4. +[4,7] with maximum absolute diff |4-7| = 3 <= 4. +[7] with maximum absolute diff |7-7| = 0 <= 4. +Therefore, the size of the longest subarray is 2. ++ +
Example 2:
+ +Input: nums = [10,1,2,4,7,2], limit = 5 +Output: 4 +Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. ++ +
Example 3:
+ +Input: nums = [4,2,2,2,4,4,2,2], limit = 0 +Output: 3 ++ +
+
Constraints:
+ +1 <= nums.length <= 1051 <= nums[i] <= 1090 <= limit <= 109You 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:
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 <= 1001 <= n <= 1001 <= target[i] <= ntarget is strictly increasing.Given an array of integers arr.
We want to select three indices i, j and k where (0 <= i < j <= k < arr.length).
Let's define a and b as follows:
a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]Note that ^ denotes the bitwise-xor operation.
+ +Return the number of triplets (i, j and k) Where a == b.
+
Example 1:
+ +Input: arr = [2,3,1,6,7] +Output: 4 +Explanation: The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4) ++ +
Example 2:
+ +Input: arr = [1,1,1,1,1] +Output: 10 ++ +
+
Constraints:
+ +1 <= arr.length <= 3001 <= arr[i] <= 108Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.
+ +Return the number of pseudo-palindromic paths going from the root node to leaf nodes.
+ ++
Example 1:
+ +
Input: root = [2,3,1,3,1,null,1] +Output: 2 +Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome). ++ +
Example 2:
+ +
Input: root = [2,1,1,1,3,null,null,null,null,null,1] +Output: 1 +Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome). ++ +
Example 3:
+ +Input: root = [9] +Output: 1 ++ +
+
Constraints:
+ +[1, 105].1 <= Node.val <= 9Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
+ +A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
+
Example 1:
+ +Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6] +Output: 18 +Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2. +Their dot product is (2*3 + (-2)*(-6)) = 18.+ +
Example 2:
+ +Input: nums1 = [3,-2], nums2 = [2,-6,7] +Output: 21 +Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2. +Their dot product is (3*7) = 21.+ +
Example 3:
+ +Input: nums1 = [-1,-1], nums2 = [1,1] +Output: -1 +Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2. +Their dot product is -1.+ +
+
Constraints:
+ +1 <= nums1.length, nums2.length <= 500-1000 <= nums1[i], nums2[i] <= 1000You are given two integer arrays of equal length target and arr. In one step, you can select any non-empty subarray of arr and reverse it. You are allowed to make any number of steps.
Return true if you can make arr equal to target or false otherwise.
+
Example 1:
+ +Input: target = [1,2,3,4], arr = [2,4,1,3] +Output: true +Explanation: You can follow the next steps to convert arr to target: +1- Reverse subarray [2,4,1], arr becomes [1,4,2,3] +2- Reverse subarray [4,2], arr becomes [1,2,4,3] +3- Reverse subarray [4,3], arr becomes [1,2,3,4] +There are multiple ways to convert arr to target, this is not the only way to do so. ++ +
Example 2:
+ +Input: target = [7], arr = [7] +Output: true +Explanation: arr is equal to target without any reverses. ++ +
Example 3:
+ +Input: target = [3,7,9], arr = [3,7,11] +Output: false +Explanation: arr does not have value 9 and it can never be converted to target. ++ +
+
Constraints:
+ +target.length == arr.length1 <= target.length <= 10001 <= target[i] <= 10001 <= arr[i] <= 1000nums, 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 <= 5001 <= nums[i] <= 10^3In a binary tree, a lonely node is a node that is the only child of its parent node. The root of the tree is not lonely because it does not have a parent node.
+ +Given the root of a binary tree, return an array containing the values of all lonely nodes in the tree. Return the list in any order.
+
Example 1:
+
+Input: root = [1,2,3,null,4] +Output: [4] +Explanation: Light blue node is the only lonely node. +Node 1 is the root and is not lonely. +Nodes 2 and 3 have the same parent and are not lonely. ++ +
Example 2:
+
+Input: root = [7,1,4,6,null,5,3,null,null,null,null,null,2] +Output: [6,2] +Explanation: Light blue nodes are lonely nodes. +Please remember that order doesn't matter, [2,6] is also an acceptable answer. ++ +
Example 3:
+
++Input: root = [11,99,88,77,null,null,66,55,null,null,44,33,null,null,22] +Output: [77,55,33,66,44,22] +Explanation: Nodes 99 and 88 share the same parent. Node 11 is the root. +All other nodes are lonely. ++ +
+
Constraints:
+ +tree is in the range [1, 1000].1 <= Node.val <= 106Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
Return the array in the form [x1,y1,x2,y2,...,xn,yn].
+
Example 1:
+ +Input: nums = [2,5,1,3,4,7], n = 3 +Output: [2,3,5,4,1,7] +Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]. ++ +
Example 2:
+ +Input: nums = [1,2,3,4,4,3,2,1], n = 4 +Output: [1,4,2,3,3,2,4,1] ++ +
Example 3:
+ +Input: nums = [1,1,2,2], n = 2 +Output: [1,2,1,2] ++ +
+
Constraints:
+ +1 <= n <= 500nums.length == 2n1 <= nums[i] <= 10^3Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.
+
Example 1:
+ +Input: arr = [5,5,4], k = 1 +Output: 1 +Explanation: Remove the single 4, only 5 is left. ++Example 2: + +
Input: arr = [4,3,1,1,3,3,2], k = 3 +Output: 2 +Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.+ +
+
Constraints:
+ +1 <= arr.length <= 10^51 <= arr[i] <= 10^90 <= k <= arr.lengthYou are given an integer array bloomDay, an integer m and an integer k.
You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
+
Example 1:
+ +Input: bloomDay = [1,10,3,10,2], m = 3, k = 1 +Output: 3 +Explanation: Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden. +We need 3 bouquets each should contain 1 flower. +After day 1: [x, _, _, _, _] // we can only make one bouquet. +After day 2: [x, _, _, _, x] // we can only make two bouquets. +After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3. ++ +
Example 2:
+ +Input: bloomDay = [1,10,3,10,2], m = 3, k = 2 +Output: -1 +Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1. ++ +
Example 3:
+ +Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3 +Output: 12 +Explanation: We need 2 bouquets each should have 3 flowers. +Here is the garden after the 7 and 12 days: +After day 7: [x, x, x, x, _, x, x] +We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent. +After day 12: [x, x, x, x, x, x, x] +It is obvious that we can make two bouquets in different ways. ++ +
+
Constraints:
+ +bloomDay.length == n1 <= n <= 1051 <= bloomDay[i] <= 1091 <= m <= 1061 <= k <= nGiven a weighted undirected connected graph with n vertices numbered from 0 to n - 1, and an array edges where edges[i] = [ai, bi, weighti] represents a bidirectional and weighted edge between nodes ai and bi. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
+ +Note that you can return the indices of the edges in any order.
+ ++
Example 1:
+ +
Input: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]] +Output: [[0,1],[2,3,4,5]] +Explanation: The figure above describes the graph. +The following figure shows all the possible MSTs: ++ ++Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output. +The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output. +
Example 2:
+ +
Input: n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]] +Output: [[],[0,1,2,3]] +Explanation: We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical. ++ +
+
Constraints:
+ +2 <= n <= 1001 <= edges.length <= min(200, n * (n - 1) / 2)edges[i].length == 30 <= ai < bi < n1 <= weighti <= 1000(ai, bi) are distinct.Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path.
Return true if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited. Return false otherwise.
+
Example 1:
+
+Input: path = "NES" +Output: false +Explanation: Notice that the path doesn't cross any point more than once. ++ +
Example 2:
+
+Input: path = "NESWW" +Output: true +Explanation: Notice that the path visits the origin twice.+ +
+
Constraints:
+ +1 <= path.length <= 104path[i] is either 'N', 'S', 'E', or 'W'.We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some of the ants move to the left, the other move to the right.
When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time.
+ +When an ant reaches one end of the plank at a time t, it falls out of the plank immediately.
Given an integer n and two integer arrays left and right, the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank.
+
Example 1:
+
+Input: n = 4, left = [4,3], right = [0,1] +Output: 4 +Explanation: In the image above: +-The ant at index 0 is named A and going to the right. +-The ant at index 1 is named B and going to the right. +-The ant at index 3 is named C and going to the left. +-The ant at index 4 is named D and going to the left. +The last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank). ++ +
Example 2:
+
+Input: n = 7, left = [], right = [0,1,2,3,4,5,6,7] +Output: 7 +Explanation: All ants are going to the right, the ant at index 0 needs 7 seconds to fall. ++ +
Example 3:
+
+Input: n = 7, left = [0,1,2,3,4,5,6,7], right = [] +Output: 7 +Explanation: All ants are going to the left, the ant at index 7 needs 7 seconds to fall. ++ +
+
Constraints:
+ +1 <= n <= 1040 <= left.length <= n + 10 <= left[i] <= n0 <= right.length <= n + 10 <= right[i] <= n1 <= left.length + right.length <= n + 1left and right are unique, and each value can appear only in one of the two arrays.You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.
Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 109 + 7.
+
Example 1:
+ +Input: nums = [1,2,3,4], n = 4, left = 1, right = 5 +Output: 13 +Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13. ++ +
Example 2:
+ +Input: nums = [1,2,3,4], n = 4, left = 3, right = 4 +Output: 6 +Explanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6. ++ +
Example 3:
+ +Input: nums = [1,2,3,4], n = 4, left = 1, right = 10 +Output: 50 ++ +
+
Constraints:
+ +n == nums.length1 <= nums.length <= 10001 <= nums[i] <= 1001 <= left <= right <= n * (n + 1) / 2You are given an integer array nums.
In one move, you can choose one element of nums and change it to any value.
Return the minimum difference between the largest and smallest value of nums after performing at most three moves.
+
Example 1:
+ +Input: nums = [5,3,2,4] +Output: 0 +Explanation: We can make at most 3 moves. +In the first move, change 2 to 3. nums becomes [5,3,3,4]. +In the second move, change 4 to 3. nums becomes [5,3,3,3]. +In the third move, change 5 to 3. nums becomes [3,3,3,3]. +After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0. ++ +
Example 2:
+ +Input: nums = [1,5,0,10,14] +Output: 1 +Explanation: We can make at most 3 moves. +In the first move, change 5 to 0. nums becomes [1,0,0,10,14]. +In the second move, change 10 to 0. nums becomes [1,0,0,0,14]. +In the third move, change 14 to 1. nums becomes [1,0,0,0,1]. +After performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 1. +It can be shown that there is no way to make the difference 0 in 3 moves.+ +
Example 3:
+ +Input: nums = [3,100,20] +Output: 0 +Explanation: We can make at most 3 moves. +In the first move, change 100 to 7. nums becomes [3,7,20]. +In the second move, change 20 to 7. nums becomes [3,7,7]. +In the third move, change 3 to 7. nums becomes [7,7,7]. +After performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0. ++ +
+
Constraints:
+ +1 <= nums.length <= 105-109 <= nums[i] <= 109Given an array of integers nums, return the number of good pairs.
A pair (i, j) is called good if nums[i] == nums[j] and i < j.
+
Example 1:
+ +Input: nums = [1,2,3,1,1,3] +Output: 4 +Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. ++ +
Example 2:
+ +Input: nums = [1,1,1,1] +Output: 6 +Explanation: Each pair in the array are good. ++ +
Example 3:
+ +Input: nums = [1,2,3] +Output: 0 ++ +
+
Constraints:
+ +1 <= nums.length <= 1001 <= nums[i] <= 100There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
+ +Given the two integers numBottles and numExchange, return the maximum number of water bottles you can drink.
+
Example 1:
+
+Input: numBottles = 9, numExchange = 3 +Output: 13 +Explanation: You can exchange 3 empty bottles to get 1 full water bottle. +Number of water bottles you can drink: 9 + 3 + 1 = 13. ++ +
Example 2:
+
+Input: numBottles = 15, numExchange = 4 +Output: 19 +Explanation: You can exchange 4 empty bottles to get 1 full water bottle. +Number of water bottles you can drink: 15 + 3 + 1 = 19. ++ +
+
Constraints:
+ +1 <= numBottles <= 1002 <= numExchange <= 100You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.
Return the number of good leaf node pairs in the tree.
+ ++
Example 1:
+
+Input: root = [1,2,3,null,4], distance = 3 +Output: 1 +Explanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair. ++ +
Example 2:
+
+Input: root = [1,2,3,4,5,6,7], distance = 3 +Output: 2 +Explanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4. ++ +
Example 3:
+ +Input: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3 +Output: 1 +Explanation: The only good pair is [2,5]. ++ +
+
Constraints:
+ +tree is in the range [1, 210].1 <= Node.val <= 1001 <= distance <= 10Run-length encoding 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 "aabccc" we replace "aa" by "a2" and replace "ccc" by "c3". Thus the compressed string becomes "a2bc3".
Notice that in this problem, we are not adding '1' after single characters.
Given a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length.
Find the minimum length of the run-length encoded version of s after deleting at most k characters.
+
Example 1:
+ +Input: s = "aaabcccd", k = 2 +Output: 4 +Explanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4.+ +
Example 2:
+ +Input: s = "aabbaa", k = 2 +Output: 2 +Explanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2. ++ +
Example 3:
+ +Input: s = "aaaaaaaaaaa", k = 0 +Output: 3 +Explanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3. ++ +
+
Constraints:
+ +1 <= s.length <= 1000 <= k <= s.lengths contains only lowercase English letters.Given an integer array arr of distinct integers and an integer k.
A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0, and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds.
Return the integer which will win the game.
+ +It is guaranteed that there will be a winner of the game.
+ ++
Example 1:
+ +Input: arr = [2,1,3,5,4,6,7], k = 2 +Output: 5 +Explanation: Let's see the rounds of the game: +Round | arr | winner | win_count + 1 | [2,1,3,5,4,6,7] | 2 | 1 + 2 | [2,3,5,4,6,7,1] | 3 | 1 + 3 | [3,5,4,6,7,1,2] | 5 | 1 + 4 | [5,4,6,7,1,2,3] | 5 | 2 +So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games. ++ +
Example 2:
+ +Input: arr = [3,2,1], k = 10 +Output: 3 +Explanation: 3 will win the first 10 rounds consecutively. ++ +
+
Constraints:
+ +2 <= arr.length <= 1051 <= arr[i] <= 106arr contains distinct integers.1 <= k <= 109Given a string s of lower and upper case English letters.
A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:
0 <= i <= s.length - 2s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.
+ +Return the string after making it good. The answer is guaranteed to be unique under the given constraints.
+ +Notice that an empty string is also good.
+ ++
Example 1:
+ +Input: s = "leEeetcode" +Output: "leetcode" +Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode". ++ +
Example 2:
+ +Input: s = "abBAcC" +Output: "" +Explanation: We have many possible scenarios, and all lead to the same answer. For example: +"abBAcC" --> "aAcC" --> "cC" --> "" +"abBAcC" --> "abBA" --> "aA" --> "" ++ +
Example 3:
+ +Input: s = "s" +Output: "s" ++ +
+
Constraints:
+ +1 <= s.length <= 100s contains only lower and upper case English letters.arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false.
++
Example 1:
+ +Input: arr = [2,6,4,1] +Output: false +Explanation: There are no three consecutive odds. ++ +
Example 2:
+ +Input: arr = [1,2,34,3,4,5,7,23,12] +Output: true +Explanation: [5,7,23] are three consecutive odds. ++ +
+
Constraints:
+ +1 <= arr.length <= 10001 <= arr[i] <= 1000In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
+
Example 1:
+
+Input: position = [1,2,3,4,7], m = 3 +Output: 3 +Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3. ++ +
Example 2:
+ +Input: position = [5,4,3,2,1,1000000000], m = 2 +Output: 999999999 +Explanation: We can use baskets 1 and 1000000000. ++ +
+
Constraints:
+ +n == position.length2 <= n <= 1051 <= position[i] <= 109position are distinct.2 <= m <= position.lengthThere are 3n piles of coins of varying size, you and your friends will take piles of coins as follows:
3 piles of coins (not necessarily consecutive).Given an array of integers piles where piles[i] is the number of coins in the ith pile.
Return the maximum number of coins that you can have.
+ ++
Example 1:
+ +Input: piles = [2,4,1,2,7,8] +Output: 9 +Explanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one. +Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one. +The maximum number of coins which you can have are: 7 + 2 = 9. +On the other hand if we choose this arrangement (1, 2, 8), (2, 4, 7) you only get 2 + 4 = 6 coins which is not optimal. ++ +
Example 2:
+ +Input: piles = [2,4,5] +Output: 4 ++ +
Example 3:
+ +Input: piles = [9,8,7,6,5,1,2,3,4] +Output: 18 ++ +
+
Constraints:
+ +3 <= piles.length <= 105piles.length % 3 == 01 <= piles[i] <= 104You 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.lengthn == grid[i].length1 <= m, n <= 30grid[i][j] is either 0 or 1.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 ballons at indices 0 and 4. Each ballon 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.length1 <= n <= 1051 <= neededTime[i] <= 104colors contains only lowercase English letters.You are given two arrays of positive integers, boxes and warehouse, representing the heights of some boxes of unit width and the heights of n rooms in a warehouse respectively. The warehouse's rooms are labeled from 0 to n - 1 from left to right where warehouse[i] (0-indexed) is the height of the ith room.
Boxes are put into the warehouse by the following rules:
+ +Return the maximum number of boxes you can put into the warehouse.
+ ++
Example 1:
+
+Input: boxes = [1,2,2,3,4], warehouse = [3,4,1,2] +Output: 4 +Explanation: ++ ++We can store the boxes in the following order: +1- Put the yellow box in room 2 from either the left or right side. +2- Put the orange box in room 3 from the right side. +3- Put the green box in room 1 from the left side. +4- Put the red box in room 0 from the left side. +Notice that there are other valid ways to put 4 boxes such as swapping the red and green boxes or the red and orange boxes. +
Example 2:
+
+Input: boxes = [3,5,5,2], warehouse = [2,1,3,4,5] +Output: 3 +Explanation: ++ ++It is not possible to put the two boxes of height 5 in the warehouse since there's only 1 room of height >= 5. +Other valid solutions are to put the green box in room 2 or to put the orange box first in room 2 before putting the green and red boxes. +
+
Constraints:
+ +n == warehouse.length1 <= boxes.length, warehouse.length <= 1051 <= boxes[i], warehouse[i] <= 109Given an m x n binary matrix mat, return the number of special positions in mat.
A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed).
+
Example 1:
+
+Input: mat = [[1,0,0],[0,0,1],[1,0,0]] +Output: 1 +Explanation: (1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0. ++ +
Example 2:
+
+Input: mat = [[1,0,0],[0,1,0],[0,0,1]] +Output: 3 +Explanation: (0, 0), (1, 1) and (2, 2) are special positions. ++ +
+
Constraints:
+ +m == mat.lengthn == mat[i].length1 <= m, n <= 100mat[i][j] is either 0 or 1.You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].
The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.
Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.
+ ++
Example 1:
+
+Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]] +Output: 20 +Explanation: ++ ++We can connect the points as shown above to get the minimum cost of 20. +Notice that there is a unique path between every pair of points. +
Example 2:
+ +Input: points = [[3,12],[-2,5],[-4,1]] +Output: 18 ++ +
+
Constraints:
+ +1 <= points.length <= 1000-106 <= xi, yi <= 106(xi, yi) are distinct.The Leetcode file system keeps a log each time some user performs a change folder operation.
+ +The operations are described below:
+ +"../" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder)."./" : Remain in the same folder."x/" : Move to the child folder named x (This folder is guaranteed to always exist).You are given a list of strings logs where logs[i] is the operation performed by the user at the ith step.
The file system starts in the main folder, then the operations in logs are performed.
Return the minimum number of operations needed to go back to the main folder after the change folder operations.
+ ++
Example 1:
+ +
Input: logs = ["d1/","d2/","../","d21/","./"] +Output: 2 +Explanation: Use this change folder operation "../" 2 times and go back to the main folder. ++ +
Example 2:
+ +
Input: logs = ["d1/","d2/","./","d3/","../","d31/"] +Output: 3 ++ +
Example 3:
+ +Input: logs = ["d1/","../","../","../"] +Output: 0 ++ +
+
Constraints:
+ +1 <= logs.length <= 1032 <= logs[i].length <= 10logs[i] contains lowercase English letters, digits, '.', and '/'.logs[i] follows the format described in the statement.You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column.
Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements.
Return a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at least one matrix that fulfills the requirements exists.
+ ++
Example 1:
+ +Input: rowSum = [3,8], colSum = [4,7] +Output: [[3,0], + [1,7]] +Explanation: +0th row: 3 + 0 = 3 == rowSum[0] +1st row: 1 + 7 = 8 == rowSum[1] +0th column: 3 + 1 = 4 == colSum[0] +1st column: 0 + 7 = 7 == colSum[1] +The row and column sums match, and all matrix elements are non-negative. +Another possible matrix is: [[1,2], + [3,5]] ++ +
Example 2:
+ +Input: rowSum = [5,7,10], colSum = [8,6,8] +Output: [[0,5,0], + [6,1,0], + [2,0,8]] ++ +
+
Constraints:
+ +1 <= rowSum.length, colSum.length <= 5000 <= rowSum[i], colSum[i] <= 108sum(rowSum) == sum(colSum)You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x.
Notice that x does not have to be an element in nums.
Return x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique.
+
Example 1:
+ +Input: nums = [3,5] +Output: 2 +Explanation: There are 2 values (3 and 5) that are greater than or equal to 2. ++ +
Example 2:
+ +Input: nums = [0,0] +Output: -1 +Explanation: No numbers fit the criteria for x. +If x = 0, there should be 0 numbers >= x, but there are 2. +If x = 1, there should be 1 number >= x, but there are 0. +If x = 2, there should be 2 numbers >= x, but there are 0. +x cannot be greater since there are only 2 numbers in nums. ++ +
Example 3:
+ +Input: nums = [0,4,3,0,4] +Output: 3 +Explanation: There are 3 values that are greater than or equal to 3. ++ +
+
Constraints:
+ +1 <= nums.length <= 1000 <= nums[i] <= 1000A binary tree is named Even-Odd if it meets the following conditions:
+ +0, its children are at level index 1, their children are at level index 2, etc.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:
+ +[1, 105].1 <= Node.val <= 106Given an integer n, you must transform it into 0 using the following operations any number of times:
0th) bit in the binary representation of n.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 <= 109A string is a valid parentheses string (denoted VPS) if it meets one of the following:
+ +"", or a single character not equal to "(" or ")",AB (A concatenated with B), where A and B are VPS's, or(A), where A is a VPS.We can similarly define the nesting depth depth(S) of any VPS S as follows:
depth("") = 0depth(C) = 0, where C is a string with a single character not equal to "(" or ")".depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's.depth("(" + A + ")") = 1 + depth(A), where A is a VPS.For example, "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's.
Given a VPS represented as string s, return the nesting depth of s.
+
Example 1:
+ +Input: s = "(1+(2*3)+((8)/4))+1" +Output: 3 +Explanation: Digit 8 is inside of 3 nested parentheses in the string. ++ +
Example 2:
+ +Input: s = "(1)+((2))+(((3)))" +Output: 3 ++ +
+
Constraints:
+ +1 <= s.length <= 100s consists of digits 0-9 and characters '+', '-', '*', '/', '(', and ')'.s is a VPS.There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi.
The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once.
+ +The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities.
+ +Given the integer n and the array roads, return the maximal network rank of the entire infrastructure.
+
Example 1:
+ +
Input: n = 4, roads = [[0,1],[0,3],[1,2],[1,3]] +Output: 4 +Explanation: The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once. ++ +
Example 2:
+ +
Input: n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]] +Output: 5 +Explanation: There are 5 roads that are connected to cities 1 or 2. ++ +
Example 3:
+ +Input: n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]] +Output: 5 +Explanation: The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected. ++ +
+
Constraints:
+ +2 <= n <= 1000 <= roads.length <= n * (n - 1) / 2roads[i].length == 20 <= ai, bi <= n-1ai != biGiven a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1.
A substring is a contiguous sequence of characters within a string.
+ ++
Example 1:
+ +Input: s = "aa"
+Output: 0
+Explanation: The optimal substring here is an empty substring between the two 'a's.
+
+Example 2:
+ +Input: s = "abca" +Output: 2 +Explanation: The optimal substring here is "bc". ++ +
Example 3:
+ +Input: s = "cbzxy" +Output: -1 +Explanation: There are no characters that appear twice in s. ++ +
+
Constraints:
+ +1 <= s.length <= 300s contains only lowercase English letters.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]. Thiscan 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.lengthm == l.lengthm == r.length2 <= n <= 5001 <= m <= 5000 <= l[i] < r[i] < n-105 <= nums[i] <= 105You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.
A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.
+ +Return the minimum effort required to travel from the top-left cell to the bottom-right cell.
+ ++
Example 1:
+ +
Input: heights = [[1,2,2],[3,8,2],[5,3,5]] +Output: 2 +Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells. +This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3. ++ +
Example 2:
+ +
Input: heights = [[1,2,3],[3,8,4],[5,3,5]] +Output: 1 +Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5]. ++ +
Example 3:
+
+Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]] +Output: 0 +Explanation: This route does not require any effort. ++ +
+
Constraints:
+ +rows == heights.lengthcolumns == heights[i].length1 <= rows, columns <= 1001 <= heights[i][j] <= 106Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order.
Return the sorted array.
+ ++
Example 1:
+ +Input: nums = [1,1,2,2,2,3] +Output: [3,1,1,2,2,2] +Explanation: '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3. ++ +
Example 2:
+ +Input: nums = [2,3,1,3,2] +Output: [1,3,3,2,2] +Explanation: '2' and '3' both have a frequency of 2, so they are sorted in decreasing order. ++ +
Example 3:
+ +Input: nums = [-1,1,-6,4,5,-6,1,4,1] +Output: [5,-1,4,4,-6,-6,1,1,1]+ +
+
Constraints:
+ +1 <= nums.length <= 100-100 <= nums[i] <= 100You 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),
(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 <= 1051 <= heights[i] <= 1060 <= bricks <= 1090 <= ladders <= heights.lengthA string s is called good if there are no two different characters in s that have the same frequency.
Given a string s, return the minimum number of characters you need to delete to make s good.
The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab", the frequency of 'a' is 2, while the frequency of 'b' is 1.
+
Example 1:
+ +Input: s = "aab"
+Output: 0
+Explanation: s is already good.
+
+
+Example 2:
+ +Input: s = "aaabbbcc" +Output: 2 +Explanation: You can delete two 'b's resulting in the good string "aaabcc". +Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc".+ +
Example 3:
+ +Input: s = "ceabaacb" +Output: 2 +Explanation: You can delete both 'c's resulting in the good string "eabaab". +Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored). ++ +
+
Constraints:
+ +1 <= s.length <= 105s contains only lowercase English letters.You are given a string s consisting only of characters 'a' and 'b'.
You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'.
Return the minimum number of deletions needed to make s balanced.
+
Example 1:
+ +Input: s = "aababbab"
+Output: 2
+Explanation: You can either:
+Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or
+Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb").
+
+
+Example 2:
+ +Input: s = "bbaaaaabb" +Output: 2 +Explanation: The only solution is to delete the first two characters. ++ +
+
Constraints:
+ +1 <= s.length <= 105s[i] is 'a' or 'b'.Two strings are considered close if you can attain one from the other using the following operations:
+ +abcde -> aecdbaacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)You can use the operations on either string as many times as necessary.
+ +Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.
+
Example 1:
+ +Input: word1 = "abc", word2 = "bca" +Output: true +Explanation: You can attain word2 from word1 in 2 operations. +Apply Operation 1: "abc" -> "acb" +Apply Operation 1: "acb" -> "bca" ++ +
Example 2:
+ +Input: word1 = "a", word2 = "aa" +Output: false +Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations. ++ +
Example 3:
+ +Input: word1 = "cabbba", word2 = "abbccc"
+Output: true
+Explanation: You can attain word2 from word1 in 3 operations.
+Apply Operation 1: "cabbba" -> "caabbb"
+Apply Operation 2: "caabbb" -> "baaccc"
+Apply Operation 2: "baaccc" -> "abbccc"
+
+
++
Constraints:
+ +1 <= word1.length, word2.length <= 105word1 and word2 contain only lowercase English letters.You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.
Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1.
+
Example 1:
+ +Input: nums = [1,1,4,2,3], x = 5 +Output: 2 +Explanation: The optimal solution is to remove the last two elements to reduce x to zero. ++ +
Example 2:
+ +Input: nums = [5,6,7,8,9], x = 4 +Output: -1 ++ +
Example 3:
+ +Input: nums = [3,2,20,1,1,3], x = 10 +Output: 5 +Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero. ++ +
+
Constraints:
+ +1 <= nums.length <= 1051 <= nums[i] <= 1041 <= x <= 109You have a binary tree with a small defect. There is exactly one invalid node where its right child incorrectly points to another node at the same depth but to the invalid node's right.
+ +Given the root of the binary tree with this defect, root, return the root of the binary tree after removing this invalid node and every node underneath it (minus the node it incorrectly points to).
Custom testing:
+ +The test input is read as 3 lines:
+ +TreeNode rootint fromNode (not available to correctBinaryTree)int toNode (not available to correctBinaryTree)After the binary tree rooted at root is parsed, the TreeNode with value of fromNode will have its right child pointer pointing to the TreeNode with a value of toNode. Then, root is passed to correctBinaryTree.
+
Example 1:
+ +
Input: root = [1,2,3], fromNode = 2, toNode = 3 +Output: [1,null,3] +Explanation: The node with value 2 is invalid, so remove it. ++ +
Example 2:
+ +
Input: root = [8,3,1,7,null,9,4,2,null,null,null,5,6], fromNode = 7, toNode = 4 +Output: [8,3,1,null,null,9,4,null,null,5,6] +Explanation: The node with value 7 is invalid, so remove it and the node underneath it, node 2. ++ +
+
Constraints:
+ +[3, 104].-109 <= Node.val <= 109Node.val are unique.fromNode != toNodefromNode and toNode will exist in the tree and will be on the same depth.toNode is to the right of fromNode.fromNode.right is null in the initial tree from the test data.Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.
A string is represented by an array if the array elements concatenated in order forms the string.
+ ++
Example 1:
+ +Input: word1 = ["ab", "c"], word2 = ["a", "bc"] +Output: true +Explanation: +word1 represents string "ab" + "c" -> "abc" +word2 represents string "a" + "bc" -> "abc" +The strings are the same, so return true.+ +
Example 2:
+ +Input: word1 = ["a", "cb"], word2 = ["ab", "c"] +Output: false ++ +
Example 3:
+ +Input: word1 = ["abc", "d", "defg"], word2 = ["abcddefg"] +Output: true ++ +
+
Constraints:
+ +1 <= word1.length, word2.length <= 1031 <= word1[i].length, word2[i].length <= 1031 <= sum(word1[i].length), sum(word2[i].length) <= 103word1[i] and word2[i] consist of lowercase letters.You are given two linked lists: list1 and list2 of sizes n and m respectively.
Remove list1's nodes from the ath node to the bth node, and put list2 in their place.
The blue edges and nodes in the following figure indicate the result:
+
+Build the result list and return its head.
+ ++
Example 1:
+
+Input: list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002] +Output: [10,1,13,1000000,1000001,1000002,5] +Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. ++ +
Example 2:
+
+Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004] +Output: [0,1,1000000,1000001,1000002,1000003,1000004,6] +Explanation: The blue edges and nodes in the above figure indicate the result. ++ +
+
Constraints:
+ +3 <= list1.length <= 1041 <= a <= b < list1.length - 11 <= list2.length <= 104Table: Tweets
+----------------+---------+ +| Column Name | Type | ++----------------+---------+ +| tweet_id | int | +| content | varchar | ++----------------+---------+ +tweet_id is the primary key (column with unique values) for this table. +This table contains all the tweets in a social media app. ++ +
+ +
Write a solution to find the IDs of the invalid tweets. The tweet is invalid if the number of characters used in the content of the tweet is strictly greater than 15.
Return the result table in any order.
+ +The result format is in the following example.
+ ++
Example 1:
+ +Input: +Tweets table: ++----------+----------------------------------+ +| tweet_id | content | ++----------+----------------------------------+ +| 1 | Vote for Biden | +| 2 | Let us make America great again! | ++----------+----------------------------------+ +Output: ++----------+ +| tweet_id | ++----------+ +| 2 | ++----------+ +Explanation: +Tweet 1 has length = 14. It is a valid tweet. +Tweet 2 has length = 32. It is an invalid tweet. ++
You are given an integer array nums sorted in non-decreasing order.
Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array.
In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i (0-indexed).
+
Example 1:
+ +Input: nums = [2,3,5] +Output: [4,3,5] +Explanation: Assuming the arrays are 0-indexed, then +result[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4, +result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3, +result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5. ++ +
Example 2:
+ +Input: nums = [1,4,6,8,10] +Output: [24,15,13,15,21] ++ +
+
Constraints:
+ +2 <= nums.length <= 1051 <= nums[i] <= nums[i + 1] <= 104You are given an integer n, the number of teams in a tournament that has strange rules:
n / 2 matches are played, and n / 2 teams advance to the next round.(n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round.Return the number of matches played in the tournament until a winner is decided.
+ ++
Example 1:
+ +Input: n = 7 +Output: 6 +Explanation: Details of the tournament: +- 1st Round: Teams = 7, Matches = 3, and 4 teams advance. +- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance. +- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner. +Total number of matches = 3 + 2 + 1 = 6. ++ +
Example 2:
+ +Input: n = 14 +Output: 13 +Explanation: Details of the tournament: +- 1st Round: Teams = 14, Matches = 7, and 7 teams advance. +- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance. +- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance. +- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner. +Total number of matches = 7 + 3 + 2 + 1 = 13. ++ +
+
Constraints:
+ +1 <= n <= 200The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.
The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step:
+ +This continues until none of the queue students want to take the top sandwich and are thus unable to eat.
+ +You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the ith sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the jth student in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat.
+
Example 1:
+ +Input: students = [1,1,0,0], sandwiches = [0,1,0,1] +Output: 0 +Explanation: +- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1]. +- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1]. +- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1]. +- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0]. +- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1]. +- Front student leaves the top sandwich and returns to the end of the line making students = [0,1]. +- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1]. +- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = []. +Hence all students are able to eat. ++ +
Example 2:
+ +Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1] +Output: 3 ++ +
+
Constraints:
+ +1 <= students.length, sandwiches.length <= 100students.length == sandwiches.lengthsandwiches[i] is 0 or 1.students[i] is 0 or 1.There is a restaurant with a single chef. You are given an array customers, where customers[i] = [arrivali, timei]:
arrivali is the arrival time of the ith customer. The arrival times are sorted in non-decreasing order.timei is the time needed to prepare the order of the ith customer.When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers in the order they were given in the input.
+ +Return the average waiting time of all customers. Solutions within 10-5 from the actual answer are considered accepted.
+
Example 1:
+ +Input: customers = [[1,2],[2,5],[4,3]] +Output: 5.00000 +Explanation: +1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. +2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. +3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. +So the average waiting time = (2 + 6 + 7) / 3 = 5. ++ +
Example 2:
+ +Input: customers = [[5,2],[5,4],[10,3],[20,1]] +Output: 3.25000 +Explanation: +1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. +2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. +3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. +4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. +So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. ++ +
+
Constraints:
+ +1 <= customers.length <= 1051 <= arrivali, timei <= 104arrivali <= arrivali+1You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.
Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters.
Return true if a and b are alike. Otherwise, return false.
+
Example 1:
+ +Input: s = "book" +Output: true +Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike. ++ +
Example 2:
+ +Input: s = "textbook" +Output: false +Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike. +Notice that the vowel o is counted twice. ++ +
+
Constraints:
+ +2 <= s.length <= 1000s.length is even.s consists of uppercase and lowercase letters.Hercy wants to save money for his first car. He puts money in the Leetcode bank every day.
+ +He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday.
Given n, return the total amount of money he will have in the Leetcode bank at the end of the nth day.
+
Example 1:
+ +Input: n = 4 +Output: 10 +Explanation: After the 4th day, the total is 1 + 2 + 3 + 4 = 10. ++ +
Example 2:
+ +Input: n = 10 +Output: 37 +Explanation: After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. ++ +
Example 3:
+ +Input: n = 20 +Output: 96 +Explanation: After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. ++ +
+
Constraints:
+ +1 <= n <= 1000You are given a string s and two integers x and y. You can perform two types of operations any number of times.
"ab" and gain x points.
+
+ "ab" from "cabxbae" it becomes "cxbae"."ba" and gain y points.
+ "ba" from "cabxbae" it becomes "cabxe".Return the maximum points you can gain after applying the above operations on s.
+
Example 1:
+ +Input: s = "cdbcbbaaabab", x = 4, y = 5 +Output: 19 +Explanation: +- Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score. +- Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score. +- Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score. +- Remove the "ba" underlined in "cdbcba". Now, s = "cdbc" and 5 points are added to the score. +Total score = 5 + 4 + 5 + 5 = 19.+ +
Example 2:
+ +Input: s = "aabbaaxybbaabb", x = 5, y = 4 +Output: 20 ++ +
+
Constraints:
+ +1 <= s.length <= 1051 <= x, y <= 104s consists of lowercase English letters.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.lengthn == matrix[i].length1 <= m * n <= 105matrix[i][j] is either 0 or 1.Given the root of a binary tree and two integers p and q, return the distance between the nodes of value p and value q in the tree.
The distance between two nodes is the number of edges on the path from one to the other.
+ ++
Example 1:
+
+Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 0 +Output: 3 +Explanation: There are 3 edges between 5 and 0: 5-3-1-0.+ +
Example 2:
+
+Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 7 +Output: 2 +Explanation: There are 2 edges between 5 and 7: 5-2-7.+ +
Example 3:
+
+Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 5 +Output: 0 +Explanation: The distance between a node and itself is 0.+ +
+
Constraints:
+ +[1, 104].0 <= Node.val <= 109Node.val are unique.p and q are values in the tree.There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums.
You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums.
It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order.
Return the original array nums. If there are multiple solutions, return any of them.
+
Example 1:
+ +Input: adjacentPairs = [[2,1],[3,4],[3,2]] +Output: [1,2,3,4] +Explanation: This array has all its adjacent pairs in adjacentPairs. +Notice that adjacentPairs[i] may not be in left-to-right order. ++ +
Example 2:
+ +Input: adjacentPairs = [[4,-2],[1,4],[-3,1]] +Output: [-2,4,1,-3] +Explanation: There can be negative numbers. +Another solution is [-3,1,4,-2], which would also be accepted. ++ +
Example 3:
+ +Input: adjacentPairs = [[100000,-100000]] +Output: [100000,-100000] ++ +
+
Constraints:
+ +nums.length == nadjacentPairs.length == n - 1adjacentPairs[i].length == 22 <= n <= 105-105 <= nums[i], ui, vi <= 105nums that has adjacentPairs as its pairs.Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times:
s where all the characters in the prefix are equal.s where all the characters in this suffix are equal.Return the minimum length of s after performing the above operation any number of times (possibly zero times).
+
Example 1:
+ +Input: s = "ca" +Output: 2 +Explanation: You can't remove any characters, so the string stays as is. ++ +
Example 2:
+ +Input: s = "cabaabac" +Output: 0 +Explanation: An optimal sequence of operations is: +- Take prefix = "c" and suffix = "c" and remove them, s = "abaaba". +- Take prefix = "a" and suffix = "a" and remove them, s = "baab". +- Take prefix = "b" and suffix = "b" and remove them, s = "aa". +- Take prefix = "a" and suffix = "a" and remove them, s = "".+ +
Example 3:
+ +Input: s = "aabccabba" +Output: 3 +Explanation: An optimal sequence of operations is: +- Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb". +- Take prefix = "b" and suffix = "bb" and remove them, s = "cca". ++ +
+
Constraints:
+ +1 <= s.length <= 105s only consists of characters 'a', 'b', and 'c'.Table: Products
+-------------+---------+
+| Column Name | Type |
++-------------+---------+
+| product_id | int |
+| low_fats | enum |
+| recyclable | enum |
++-------------+---------+
+In SQL, product_id is the primary key for this table.
+low_fats is an ENUM of type ('Y', 'N') where 'Y' means this product is low fat and 'N' means it is not.
+recyclable is an ENUM of types ('Y', 'N') where 'Y' means this product is recyclable and 'N' means it is not.
+
++ +
Find the ids of products that are both low fat and recyclable.
+ +Return the result table in any order.
+ +The result format is in the following example.
+ ++
Example 1:
+ +Input: +Products table: ++-------------+----------+------------+ +| product_id | low_fats | recyclable | ++-------------+----------+------------+ +| 0 | Y | N | +| 1 | Y | Y | +| 2 | N | Y | +| 3 | Y | Y | +| 4 | N | N | ++-------------+----------+------------+ +Output: ++-------------+ +| product_id | ++-------------+ +| 1 | +| 3 | ++-------------+ +Explanation: Only products 1 and 3 are both low fat and recyclable. ++
You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not.
Return the minimum number of operations needed to make s alternating.
+
Example 1:
+ +Input: s = "0100" +Output: 1 +Explanation: If you change the last character to '1', s will be "0101", which is alternating. ++ +
Example 2:
+ +Input: s = "10" +Output: 0 +Explanation: s is already alternating. ++ +
Example 3:
+ +Input: s = "1111" +Output: 2 +Explanation: You need two operations to reach "0101" or "1010". ++ +
+
Constraints:
+ +1 <= s.length <= 104s[i] is either '0' or '1'.Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.
A string is homogenous if all the characters of the string are the same.
+ +A substring is a contiguous sequence of characters within a string.
+ ++
Example 1:
+ +Input: s = "abbcccaa" +Output: 13 +Explanation: The homogenous substrings are listed as below: +"a" appears 3 times. +"aa" appears 1 time. +"b" appears 2 times. +"bb" appears 1 time. +"c" appears 3 times. +"cc" appears 2 times. +"ccc" appears 1 time. +3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.+ +
Example 2:
+ +Input: s = "xy" +Output: 2 +Explanation: The homogenous substrings are "x" and "y".+ +
Example 3:
+ +Input: s = "zzzzz" +Output: 15 ++ +
+
Constraints:
+ +1 <= s.length <= 105s consists of lowercase letters.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 <= 100word1 and word2 consist of lowercase English letters.There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node.
You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph.
+
Example 1:
+
+Input: edges = [[1,2],[2,3],[4,2]] +Output: 2 +Explanation: As shown in the figure above, node 2 is connected to every other node, so 2 is the center. ++ +
Example 2:
+ +Input: edges = [[1,2],[5,1],[1,3],[1,4]] +Output: 1 ++ +
+
Constraints:
+ +3 <= n <= 105edges.length == n - 1edges[i].length == 21 <= ui, vi <= nui != viedges represent a valid star graph.You are given an array of integers nums (0-indexed) and an integer k.
The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j.
Return the maximum possible score of a good subarray.
+ ++
Example 1:
+ +Input: nums = [1,4,3,7,4,5], k = 3 +Output: 15 +Explanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15. ++ +
Example 2:
+ +Input: nums = [5,5,4,5,4,1,1,1], k = 0 +Output: 20 +Explanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20. ++ +
+
Constraints:
+ +1 <= nums.length <= 1051 <= nums[i] <= 2 * 1040 <= k < nums.lengthYou 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 == nnums[i] is a positive integer where 0 <= i < n.abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1.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 <= 1090 <= index < nA 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.int countWordsEqualTo(String word) Returns the number of instances of the string word in the trie.int countWordsStartingWith(String prefix) Returns the number of strings in the trie that have the string prefix as a prefix.void erase(String word) Erases the string word from the trie.+
Example 1:
+ +Input
+["Trie", "insert", "insert", "countWordsEqualTo", "countWordsStartingWith", "erase", "countWordsEqualTo", "countWordsStartingWith", "erase", "countWordsStartingWith"]
+[[], ["apple"], ["apple"], ["apple"], ["app"], ["apple"], ["apple"], ["app"], ["apple"], ["app"]]
+Output
+[null, null, null, 2, 2, null, 1, 1, null, 0]
+
+Explanation
+Trie trie = new Trie();
+trie.insert("apple"); // Inserts "apple".
+trie.insert("apple"); // Inserts another "apple".
+trie.countWordsEqualTo("apple"); // There are two instances of "apple" so return 2.
+trie.countWordsStartingWith("app"); // "app" is a prefix of "apple" so return 2.
+trie.erase("apple"); // Erases one "apple".
+trie.countWordsEqualTo("apple"); // Now there is only one instance of "apple" so return 1.
+trie.countWordsStartingWith("app"); // return 1
+trie.erase("apple"); // Erases "apple". Now the trie is empty.
+trie.countWordsStartingWith("app"); // return 0
+
+
++
Constraints:
+ +1 <= word.length, prefix.length <= 2000word and prefix consist only of lowercase English letters.3 * 104 calls in total will be made to insert, countWordsEqualTo, countWordsStartingWith, and erase.erase, the string word will exist in the trie.You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions:
0 <= i < j < nums.lengthnums[i] + rev(nums[j]) == nums[j] + rev(nums[i])Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7.
+
Example 1:
+ +Input: nums = [42,11,1,97] +Output: 2 +Explanation: The two pairs are: + - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121. + - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12. ++ +
Example 2:
+ +Input: nums = [13,10,35,24,76] +Output: 4 ++ +
+
Constraints:
+ +1 <= nums.length <= 1050 <= nums[i] <= 109There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend.
The rules of the game are as follows:
+ +1st friend.k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once.2 starting from the friend immediately clockwise of the friend who just lost and repeat.Given the number of friends, n, and an integer k, return the winner of the game.
+
Example 1:
+
+Input: n = 5, k = 2 +Output: 3 +Explanation: Here are the steps of the game: +1) Start at friend 1. +2) Count 2 friends clockwise, which are friends 1 and 2. +3) Friend 2 leaves the circle. Next start is friend 3. +4) Count 2 friends clockwise, which are friends 3 and 4. +5) Friend 4 leaves the circle. Next start is friend 5. +6) Count 2 friends clockwise, which are friends 5 and 1. +7) Friend 1 leaves the circle. Next start is friend 3. +8) Count 2 friends clockwise, which are friends 3 and 5. +9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.+ +
Example 2:
+ +Input: n = 6, k = 5 +Output: 1 +Explanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1. ++ +
+
Constraints:
+ +1 <= k <= n <= 500+
Follow up:
+ +Could you solve this problem in linear time with constant space?
+Given the head of a linked list, find all the values that appear more than once in the list and delete the nodes that have any of those values.
Return the linked list after the deletions.
+ ++
Example 1:
+
+Input: head = [1,2,3,2] +Output: [1,3] +Explanation: 2 appears twice in the linked list, so all 2's should be deleted. After deleting all 2's, we are left with [1,3]. ++ +
Example 2:
+
+Input: head = [2,1,1,2] +Output: [] +Explanation: 2 and 1 both appear twice. All the elements should be deleted. ++ +
Example 3:
+
+Input: head = [3,2,2,1,3,2,4] +Output: [1,4] +Explanation: 3 appears twice and 2 appears three times. After deleting all 3's and 2's, we are left with [1,4]. ++ +
+
Constraints:
+ +[1, 105]1 <= Node.val <= 105The frequency of an element is the number of times it occurs in an array.
+ +You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.
Return the maximum possible frequency of an element after performing at most k operations.
+
Example 1:
+ +Input: nums = [1,2,4], k = 5 +Output: 3 +Explanation: Increment the first element three times and the second element two times to make nums = [4,4,4]. +4 has a frequency of 3.+ +
Example 2:
+ +Input: nums = [1,4,8,13], k = 5 +Output: 2 +Explanation: There are multiple optimal solutions: +- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2. +- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2. +- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2. ++ +
Example 3:
+ +Input: nums = [3,9,6], k = 2 +Output: 1 ++ +
+
Constraints:
+ +1 <= nums.length <= 1051 <= nums[i] <= 1051 <= k <= 105Design a system that manages the reservation state of n seats that are numbered from 1 to n.
Implement the SeatManager class:
SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from 1 to n. All seats are initially available.int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its number.void unreserve(int seatNumber) Unreserves the seat with the given seatNumber.+
Example 1:
+ +Input +["SeatManager", "reserve", "reserve", "unreserve", "reserve", "reserve", "reserve", "reserve", "unreserve"] +[[5], [], [], [2], [], [], [], [], [5]] +Output +[null, 1, 2, null, 2, 3, 4, 5, null] + +Explanation +SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats. +seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1. +seatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2. +seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5]. +seatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2. +seatManager.reserve(); // The available seats are [3,4,5], so return the lowest of them, which is 3. +seatManager.reserve(); // The available seats are [4,5], so return the lowest of them, which is 4. +seatManager.reserve(); // The only available seat is seat 5, so return 5. +seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5]. ++ +
+
Constraints:
+ +1 <= n <= 1051 <= seatNumber <= nreserve, it is guaranteed that there will be at least one unreserved seat.unreserve, it is guaranteed that seatNumber will be reserved.105 calls in total will be made to reserve and unreserve.You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
arr must be 1.1. In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length (0-indexed). abs(x) is the absolute value of x.There are 2 types of operations that you can perform any number of times:
+ +arr to a smaller positive integer.arr to be in any order.Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions.
+
Example 1:
+ +Input: arr = [2,2,1,2,1] +Output: 2 +Explanation: +We can satisfy the conditions by rearranging+ +arrso it becomes[1,2,2,2,1]. +The largest element inarris 2. +
Example 2:
+ +Input: arr = [100,1,1000] +Output: 3 +Explanation: +One possible way to satisfy the conditions is by doing the following: +1. Rearrange+ +arrso it becomes[1,100,1000]. +2. Decrease the value of the second element to 2. +3. Decrease the value of the third element to 3. +Nowarr = [1,2,3], whichsatisfies the conditions. +The largest element inarr is 3.+
Example 3:
+ +Input: arr = [1,2,3,4,5] +Output: 5 +Explanation: The array already satisfies the conditions, and the largest element is 5. ++ +
+
Constraints:
+ +1 <= arr.length <= 1051 <= arr[i] <= 109The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty.
[2,5,6] is 2 XOR 5 XOR 6 = 1.Given an array nums, return the sum of all XOR totals for every subset of nums.
Note: Subsets with the same elements should be counted multiple times.
+ +An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b.
+
Example 1:
+ +Input: nums = [1,3] +Output: 6 +Explanation: The 4 subsets of [1,3] are: +- The empty subset has an XOR total of 0. +- [1] has an XOR total of 1. +- [3] has an XOR total of 3. +- [1,3] has an XOR total of 1 XOR 3 = 2. +0 + 1 + 3 + 2 = 6 ++ +
Example 2:
+ +Input: nums = [5,1,6] +Output: 28 +Explanation: The 8 subsets of [5,1,6] are: +- The empty subset has an XOR total of 0. +- [5] has an XOR total of 5. +- [1] has an XOR total of 1. +- [6] has an XOR total of 6. +- [5,1] has an XOR total of 5 XOR 1 = 4. +- [5,6] has an XOR total of 5 XOR 6 = 3. +- [1,6] has an XOR total of 1 XOR 6 = 7. +- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2. +0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28 ++ +
Example 3:
+ +Input: nums = [3,4,5,6,7,8] +Output: 480 +Explanation: The sum of all XOR totals for every subset is 480. ++ +
+
Constraints:
+ +1 <= nums.length <= 121 <= nums[i] <= 20You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride.
Each train can only depart at an integer hour, so you may need to wait in between each train ride.
+ +1st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2nd train ride at the 2 hour mark.Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time.
Tests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point.
+
Example 1:
+ +Input: dist = [1,3,2], hour = 6 +Output: 1 +Explanation: At speed 1: +- The first train ride takes 1/1 = 1 hour. +- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours. +- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours. +- You will arrive at exactly the 6 hour mark. ++ +
Example 2:
+ +Input: dist = [1,3,2], hour = 2.7 +Output: 3 +Explanation: At speed 3: +- The first train ride takes 1/3 = 0.33333 hours. +- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour. +- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours. +- You will arrive at the 2.66667 hour mark. ++ +
Example 3:
+ +Input: dist = [1,3,2], hour = 1.9 +Output: -1 +Explanation: It is impossible because the earliest the third train can depart is at the 2 hour mark. ++ +
+
Constraints:
+ +n == dist.length1 <= n <= 1051 <= dist[i] <= 1051 <= hour <= 109hour.The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs.
(1,5), (2,3), and (4,4), the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8.Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that:
nums is in exactly one pair, andReturn the minimized maximum pair sum after optimally pairing up the elements.
+ ++
Example 1:
+ +Input: nums = [3,5,2,3] +Output: 7 +Explanation: The elements can be paired up into pairs (3,3) and (5,2). +The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7. ++ +
Example 2:
+ +Input: nums = [3,5,4,2,4,6] +Output: 8 +Explanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2). +The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8. ++ +
+
Constraints:
+ +n == nums.length2 <= n <= 105n is even.1 <= nums[i] <= 105Given two integer arrays nums1 and nums2 of length n, count the pairs of indices (i, j) such that i < j and nums1[i] + nums1[j] > nums2[i] + nums2[j].
Return the number of pairs satisfying the condition.
+ ++
Example 1:
+ +Input: nums1 = [2,1,2,1], nums2 = [1,2,1,2] +Output: 1 +Explanation: The pairs satisfying the condition are: +- (0, 2) where 2 + 2 > 1 + 1.+ +
Example 2:
+ +Input: nums1 = [1,10,6,2], nums2 = [1,4,1,5] +Output: 5 +Explanation: The pairs satisfying the condition are: +- (0, 1) where 1 + 10 > 1 + 4. +- (0, 2) where 1 + 6 > 1 + 1. +- (1, 2) where 10 + 6 > 4 + 1. +- (1, 3) where 10 + 2 > 4 + 5. +- (2, 3) where 6 + 2 > 1 + 5. ++ +
+
Constraints:
+ +n == nums1.length == nums2.length1 <= n <= 1051 <= nums1[i], nums2[i] <= 105Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps:
nums. Let its index be i (0-indexed) and its value be largest. If there are multiple elements with the largest value, pick the smallest i.nums strictly smaller than largest. Let its value be nextLargest.nums[i] to nextLargest.Return the number of operations to make all elements in nums equal.
+
Example 1:
+ +Input: nums = [5,1,3] +Output: 3 +Explanation: It takes 3 operations to make all elements in nums equal: +1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3]. +2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3]. +3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1]. ++ +
Example 2:
+ +Input: nums = [1,1,1] +Output: 0 +Explanation: All elements in nums are already equal. ++ +
Example 3:
+ +Input: nums = [1,1,2,2,3] +Output: 4 +Explanation: It takes 4 operations to make all elements in nums equal: +1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2]. +2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2]. +3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2]. +4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1]. ++ +
+
Constraints:
+ +1 <= nums.length <= 5 * 1041 <= nums[i] <= 5 * 104You are given an array of strings words (0-indexed).
In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j].
Return true if you can make every string in words equal using any number of operations, and false otherwise.
+
Example 1:
+ +Input: words = ["abc","aabc","bc"] +Output: true +Explanation: Move the first 'a' in+ +words[1] to the front of words[2], +to makewords[1]= "abc" and words[2] = "abc". +All the strings are now equal to "abc", so returntrue. +
Example 2:
+ +Input: words = ["ab","a"] +Output: false +Explanation: It is impossible to make all the strings equal using the operation. ++ +
+
Constraints:
+ +1 <= words.length <= 1001 <= words[i].length <= 100words[i] consists of lowercase English letters.You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists.
A substring is a contiguous sequence of characters within a string.
+ ++
Example 1:
+ +Input: num = "52" +Output: "5" +Explanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number. ++ +
Example 2:
+ +Input: num = "4206" +Output: "" +Explanation: There are no odd numbers in "4206". ++ +
Example 3:
+ +Input: num = "35427" +Output: "35427" +Explanation: "35427" is already an odd number. ++ +
+
Constraints:
+ +1 <= num.length <= 105num only consists of digits and does not contain any leading zeros.The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).
(5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.
Return the maximum such product difference.
+ ++
Example 1:
+ +Input: nums = [5,6,2,7,4] +Output: 34 +Explanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4). +The product difference is (6 * 7) - (2 * 4) = 34. ++ +
Example 2:
+ +Input: nums = [4,2,5,9,7,4,8] +Output: 64 +Explanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4). +The product difference is (9 * 8) - (2 * 4) = 64. ++ +
+
Constraints:
+ +4 <= nums.length <= 1041 <= nums[i] <= 104A wonderful string is a string where at most one letter appears an odd number of times.
+ +"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 <= 105word consists of lowercase English letters from 'a' to 'j'.Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it.
A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).
+
Example 1:
+ +Input: nums = [0,2,1,5,3,4] +Output: [0,1,2,4,5,3] +Explanation: The array ans is built as follows: +ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]] + = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]] + = [0,1,2,4,5,3]+ +
Example 2:
+ +Input: nums = [5,0,1,2,3,4] +Output: [4,5,0,1,2,3] +Explanation: The array ans is built as follows: +ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]] + = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]] + = [4,5,0,1,2,3]+ +
+
Constraints:
+ +1 <= nums.length <= 10000 <= nums[i] < nums.lengthnums are distinct.+
Follow-up: Can you solve it without using an extra space (i.e., O(1) memory)?
You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city.
The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in kilometers per minute.
You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge. The weapon is fully charged at the very start.
+ +You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss, and the game ends before you can use your weapon.
+ +Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city.
+
Example 1:
+ +Input: dist = [1,3,4], speed = [1,1,1] +Output: 3 +Explanation: +In the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster. +After a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster. +After a minute, the distances of the monsters are [X,X,2]. You eliminate the thrid monster. +All 3 monsters can be eliminated.+ +
Example 2:
+ +Input: dist = [1,1,2,3], speed = [1,1,1,1] +Output: 1 +Explanation: +In the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster. +After a minute, the distances of the monsters are [X,0,1,2], so you lose. +You can only eliminate 1 monster. ++ +
Example 3:
+ +Input: dist = [3,2,4], speed = [5,3,2] +Output: 1 +Explanation: +In the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster. +After a minute, the distances of the monsters are [X,0,2], so you lose. +You can only eliminate 1 monster. ++ +
+
Constraints:
+ +n == dist.length == speed.length1 <= n <= 1051 <= dist[i], speed[i] <= 105Given a string s, return the number of unique palindromes of length three that are a subsequence of s.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once.
+ +A palindrome is a string that reads the same forwards and backwards.
+ +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.
+ +"ace" is a subsequence of "abcde".+
Example 1:
+ +Input: s = "aabca" +Output: 3 +Explanation: The 3 palindromic subsequences of length 3 are: +- "aba" (subsequence of "aabca") +- "aaa" (subsequence of "aabca") +- "aca" (subsequence of "aabca") ++ +
Example 2:
+ +Input: s = "adc" +Output: 0 +Explanation: There are no palindromic subsequences of length 3 in "adc". ++ +
Example 3:
+ +Input: s = "bbcbaba" +Output: 4 +Explanation: The 4 palindromic subsequences of length 3 are: +- "bbb" (subsequence of "bbcbaba") +- "bcb" (subsequence of "bbcbaba") +- "bab" (subsequence of "bbcbaba") +- "aba" (subsequence of "bbcbaba") ++ +
+
Constraints:
+ +3 <= s.length <= 105s consists of only lowercase English letters.You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix.
To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score.
However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score.
Return the maximum number of points you can achieve.
+ +abs(x) is defined as:
x for x >= 0.-x for x < 0.+
Example 1:
+
+Input: points = [[1,2,3],[1,5,1],[3,1,1]] +Output: 9 +Explanation: +The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0). +You add 3 + 5 + 3 = 11 to your score. +However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score. +Your final score is 11 - 2 = 9. ++ +
Example 2:
+
+Input: points = [[1,5],[2,3],[4,2]] +Output: 11 +Explanation: +The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0). +You add 5 + 3 + 4 = 12 to your score. +However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score. +Your final score is 12 - 1 = 11. ++ +
+
Constraints:
+ +m == points.lengthn == points[r].length1 <= m, n <= 1051 <= m * n <= 1050 <= points[r][c] <= 105Given an array of integer arrays arrays where each arrays[i] is sorted in strictly increasing order, return an integer array representing the longest common subsequence between all the arrays.
A subsequence is a sequence that can be derived from another sequence by deleting some elements (possibly none) without changing the order of the remaining elements.
+ ++
Example 1:
+ +Input: arrays = [[1,3,4], + [1,4,7,9]] +Output: [1,4] +Explanation: The longest common subsequence in the two arrays is [1,4]. ++ +
Example 2:
+ +Input: arrays = [[2,3,6,8], + [1,2,3,5,6,7,10], + [2,3,4,6,9]] +Output: [2,3,6] +Explanation: The longest common subsequence in all three arrays is [2,3,6]. ++ +
Example 3:
+ +Input: arrays = [[1,2,3,4,5], + [6,7,8]] +Output: [] +Explanation: There is no common subsequence between the two arrays. ++ +
+
Constraints:
+ +2 <= arrays.length <= 1001 <= arrays[i].length <= 1001 <= arrays[i][j] <= 100arrays[i] is sorted in strictly increasing order.There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.
You want to determine if there is a valid path that exists from vertex source to vertex destination.
Given edges and the integers n, source, and destination, return true if there is a valid path from source to destination, or false otherwise.
+
Example 1:
+
+Input: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2 +Output: true +Explanation: There are two paths from vertex 0 to vertex 2: +- 0 → 1 → 2 +- 0 → 2 ++ +
Example 2:
+
+Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5 +Output: false +Explanation: There is no path from vertex 0 to vertex 5. ++ +
+
Constraints:
+ +1 <= n <= 2 * 1050 <= edges.length <= 2 * 105edges[i].length == 20 <= ui, vi <= n - 1ui != vi0 <= source, destination <= n - 1Given the root of a binary tree, return the number of nodes where the value of the node is equal to the sum of the values of its descendants.
A descendant of a node x is any node that is on the path from node x to some leaf node. The sum is considered to be 0 if the node has no descendants.
+
Example 1:
+
+Input: root = [10,3,4,2,1] +Output: 2 +Explanation: +For the node with value 10: The sum of its descendants is 3+4+2+1 = 10. +For the node with value 3: The sum of its descendants is 2+1 = 3. ++ +
Example 2:
+
+Input: root = [2,3,null,2,null] +Output: 0 +Explanation: +No node has a value that is equal to the sum of its descendants. ++ +
Example 3:
+
+Input: root = [0] +Output: 1 +For the node with value 0: The sum of its descendants is 0 since it has no descendants. ++ +
+
Constraints:
+ +[1, 105].0 <= Node.val <= 105Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.
+
Example 1:
+ +Input: nums = ["01","10"] +Output: "11" +Explanation: "11" does not appear in nums. "00" would also be correct. ++ +
Example 2:
+ +Input: nums = ["00","01"] +Output: "11" +Explanation: "11" does not appear in nums. "10" would also be correct. ++ +
Example 3:
+ +Input: nums = ["111","011","001"] +Output: "101" +Explanation: "101" does not appear in nums. "000", "010", "100", and "110" would also be correct. ++ +
+
Constraints:
+ +n == nums.length1 <= n <= 16nums[i].length == nnums[i] is either '0' or '1'.nums are unique.You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland.
To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group.
+ +land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2].
Return a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order.
+
Example 1:
+
+Input: land = [[1,0,0],[0,1,1],[0,1,1]] +Output: [[0,0,0,0],[1,1,2,2]] +Explanation: +The first group has a top left corner at land[0][0] and a bottom right corner at land[0][0]. +The second group has a top left corner at land[1][1] and a bottom right corner at land[2][2]. ++ +
Example 2:
+
+Input: land = [[1,1],[1,1]] +Output: [[0,0,1,1]] +Explanation: +The first group has a top left corner at land[0][0] and a bottom right corner at land[1][1]. ++ +
Example 3:
+
+Input: land = [[0]] +Output: [] +Explanation: +There are no groups of farmland. ++ +
+
Constraints:
+ +m == land.lengthn == land[i].length1 <= m, n <= 300land consists of only 0's and 1's.Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.
word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd".Return the resulting string.
+ ++
Example 1:
+ +Input: word = "abcdefd", ch = "d" +Output: "dcbaefd" +Explanation: The first occurrence of "d" is at index 3. +Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd". ++ +
Example 2:
+ +Input: word = "xyxzxe", ch = "z" +Output: "zxyxxe" +Explanation: The first and only occurrence of "z" is at index 3. +Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe". ++ +
Example 3:
+ +Input: word = "abcd", ch = "z" +Output: "abcd" +Explanation: "z" does not exist in word. +You should not do any reverse operation, the resulting string is "abcd". ++ +
+
Constraints:
+ +1 <= word.length <= 250word consists of lowercase English letters.ch is a lowercase English letter.You are given an integer array nums. In one operation, you can replace any element in nums with any integer.
nums is considered continuous if both of the following conditions are fulfilled:
nums are unique.nums equals nums.length - 1.For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous.
Return the minimum number of operations to make nums continuous.
+
Example 1:
+ +Input: nums = [4,2,5,3] +Output: 0 +Explanation: nums is already continuous. ++ +
Example 2:
+ +Input: nums = [1,2,3,5,6] +Output: 1 +Explanation: One possible solution is to change the last element to 4. +The resulting array is [1,2,3,5,4], which is continuous. ++ +
Example 3:
+ +Input: nums = [1,10,100,1000] +Output: 3 +Explanation: One possible solution is to: +- Change the second element to 2. +- Change the third element to 3. +- Change the fourth element to 4. +The resulting array is [1,2,3,4], which is continuous. ++ +
+
Constraints:
+ +1 <= nums.length <= 1051 <= nums[i] <= 109There are n seats and n students in a room. You are given an array seats of length n, where seats[i] is the position of the ith seat. You are also given the array students of length n, where students[j] is the position of the jth student.
You may perform the following move any number of times:
+ +ith student by 1 (i.e., moving the ith student from position x to x + 1 or x - 1)Return the minimum number of moves required to move each student to a seat such that no two students are in the same seat.
+ +Note that there may be multiple seats or students in the same position at the beginning.
+ ++
Example 1:
+ +Input: seats = [3,1,5], students = [2,7,4] +Output: 4 +Explanation: The students are moved as follows: +- The first student is moved from from position 2 to position 1 using 1 move. +- The second student is moved from from position 7 to position 5 using 2 moves. +- The third student is moved from from position 4 to position 3 using 1 move. +In total, 1 + 2 + 1 = 4 moves were used. ++ +
Example 2:
+ +Input: seats = [4,1,5,9], students = [1,3,2,6] +Output: 7 +Explanation: The students are moved as follows: +- The first student is not moved. +- The second student is moved from from position 3 to position 4 using 1 move. +- The third student is moved from from position 2 to position 5 using 3 moves. +- The fourth student is moved from from position 6 to position 9 using 3 moves. +In total, 0 + 1 + 3 + 3 = 7 moves were used. ++ +
Example 3:
+ +Input: seats = [2,2,6,6], students = [1,3,2,6] +Output: 4 +Explanation: Note that there are two seats at position 2 and two seats at position 6. +The students are moved as follows: +- The first student is moved from from position 1 to position 2 using 1 move. +- The second student is moved from from position 3 to position 6 using 3 moves. +- The third student is not moved. +- The fourth student is not moved. +In total, 1 + 3 + 0 + 0 = 4 moves were used. ++ +
+
Constraints:
+ +n == seats.length == students.length1 <= n <= 1001 <= seats[i], students[j] <= 100There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece.
Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first.
+ +'A' if both its neighbors are also colored 'A'. She is not allowed to remove pieces that are colored 'B'.'B' if both its neighbors are also colored 'B'. He is not allowed to remove pieces that are colored 'A'.Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins.
+
Example 1:
+ +Input: colors = "AAABABB" +Output: true +Explanation: +AAABABB -> AABABB +Alice moves first. +She removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'. + +Now it's Bob's turn. +Bob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'. +Thus, Alice wins, so return true. ++ +
Example 2:
+ +Input: colors = "AA" +Output: false +Explanation: +Alice has her turn first. +There are only two 'A's and both are on the edge of the line, so she cannot move on her turn. +Thus, Bob wins, so return false. ++ +
Example 3:
+ +Input: colors = "ABBBBBBBAAA" +Output: false +Explanation: +ABBBBBBBAAA -> ABBBBBBBAA +Alice moves first. +Her only option is to remove the second to last 'A' from the right. + +ABBBBBBBAA -> ABBBBBBAA +Next is Bob's turn. +He has many options for which 'B' piece to remove. He can pick any. + +On Alice's second turn, she has no more pieces that she can remove. +Thus, Bob wins, so return false. ++ +
+
Constraints:
+ +1 <= colors.length <= 105colors consists of only the letters 'A' and 'B'A city is represented as a bi-directional connected graph with n vertices where each vertex is labeled from 1 to n (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. The time taken to traverse any edge is time minutes.
Each vertex has a traffic signal which changes its color from green to red and vice versa every change minutes. All signals change at the same time. You can enter a vertex at any time, but can leave a vertex only when the signal is green. You cannot wait at a vertex if the signal is green.
The second minimum value is defined as the smallest value strictly larger than the minimum value.
+ +[2, 3, 4] is 3, and the second minimum value of [2, 2, 4] is 4.Given n, edges, time, and change, return the second minimum time it will take to go from vertex 1 to vertex n.
Notes:
+ +1 and n.+
Example 1:
+
+Input: n = 5, edges = [[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5 +Output: 13 +Explanation: +The figure on the left shows the given graph. +The blue path in the figure on the right is the minimum time path. +The time taken is: +- Start at 1, time elapsed=0 +- 1 -> 4: 3 minutes, time elapsed=3 +- 4 -> 5: 3 minutes, time elapsed=6 +Hence the minimum time needed is 6 minutes. + +The red path shows the path to get the second minimum time. +- Start at 1, time elapsed=0 +- 1 -> 3: 3 minutes, time elapsed=3 +- 3 -> 4: 3 minutes, time elapsed=6 +- Wait at 4 for 4 minutes, time elapsed=10 +- 4 -> 5: 3 minutes, time elapsed=13 +Hence the second minimum time is 13 minutes. ++ +
Example 2:
+
+Input: n = 2, edges = [[1,2]], time = 3, change = 2 +Output: 11 +Explanation: +The minimum time path is 1 -> 2 with time = 3 minutes. +The second minimum time path is 1 -> 2 -> 1 -> 2 with time = 11 minutes.+ +
+
Constraints:
+ +2 <= n <= 104n - 1 <= edges.length <= min(2 * 104, n * (n - 1) / 2)edges[i].length == 21 <= ui, vi <= nui != vi1 <= time, change <= 103You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1)th course.
You must find the minimum number of months needed to complete all the courses following these rules:
+ +Return the minimum number of months needed to complete all the courses.
+ +Note: The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph).
+ ++
Example 1:
+
+
+Input: n = 3, relations = [[1,3],[2,3]], time = [3,2,5] +Output: 8 +Explanation: The figure above represents the given graph and the time required to complete each course. +We start course 1 and course 2 simultaneously at month 0. +Course 1 takes 3 months and course 2 takes 2 months to complete respectively. +Thus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months. ++ +
Example 2:
+
+
+Input: n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5] +Output: 12 +Explanation: The figure above represents the given graph and the time required to complete each course. +You can start courses 1, 2, and 3 at month 0. +You can complete them after 1, 2, and 3 months respectively. +Course 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months. +Course 5 can be taken only after courses 1, 2, 3, and 4 have been completed, i.e., after max(1,2,3,7) = 7 months. +Thus, the minimum time needed to complete all the courses is 7 + 5 = 12 months. ++ +
+
Constraints:
+ +1 <= n <= 5 * 1040 <= relations.length <= min(n * (n - 1) / 2, 5 * 104)relations[j].length == 21 <= prevCoursej, nextCoursej <= nprevCoursej != nextCoursej[prevCoursej, nextCoursej] are unique.time.length == n1 <= time[i] <= 104A distinct string is a string that is present only once in an array.
+ +Given an array of strings arr, and an integer k, return the kth distinct string present in arr. If there are fewer than k distinct strings, return an empty string "".
Note that the strings are considered in the order in which they appear in the array.
+ ++
Example 1:
+ +Input: arr = ["d","b","c","b","c","a"], k = 2 +Output: "a" +Explanation: +The only distinct strings in arr are "d" and "a". +"d" appears 1st, so it is the 1st distinct string. +"a" appears 2nd, so it is the 2nd distinct string. +Since k == 2, "a" is returned. ++ +
Example 2:
+ +Input: arr = ["aaa","aa","a"], k = 1 +Output: "aaa" +Explanation: +All strings in arr are distinct, so the 1st string "aaa" is returned. ++ +
Example 3:
+ +Input: arr = ["a","b","a"], k = 3 +Output: "" +Explanation: +The only distinct string is "b". Since there are fewer than 3 distinct strings, we return an empty string "". ++ +
+
Constraints:
+ +1 <= k <= arr.length <= 10001 <= arr[i].length <= 5arr[i] consists of lowercase English letters.A critical point in a linked list is defined as either a local maxima or a local minima.
+ +A node is a local maxima if the current node has a value strictly greater than the previous node and the next node.
+ +A node is a local minima if the current node has a value strictly smaller than the previous node and the next node.
+ +Note that a node can only be a local maxima/minima if there exists both a previous node and a next node.
+ +Given a linked list head, return an array of length 2 containing [minDistance, maxDistance] where minDistance is the minimum distance between any two distinct critical points and maxDistance is the maximum distance between any two distinct critical points. If there are fewer than two critical points, return [-1, -1].
+
Example 1:
+
+Input: head = [3,1] +Output: [-1,-1] +Explanation: There are no critical points in [3,1]. ++ +
Example 2:
+
+Input: head = [5,3,1,2,5,1,2] +Output: [1,3] +Explanation: There are three critical points: +- [5,3,1,2,5,1,2]: The third node is a local minima because 1 is less than 3 and 2. +- [5,3,1,2,5,1,2]: The fifth node is a local maxima because 5 is greater than 2 and 1. +- [5,3,1,2,5,1,2]: The sixth node is a local minima because 1 is less than 5 and 2. +The minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1. +The maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3. ++ +
Example 3:
+
+Input: head = [1,3,2,2,3,2,2,2,7] +Output: [3,3] +Explanation: There are two critical points: +- [1,3,2,2,3,2,2,2,7]: The second node is a local maxima because 3 is greater than 1 and 2. +- [1,3,2,2,3,2,2,2,7]: The fifth node is a local maxima because 3 is greater than 2 and 2. +Both the minimum and maximum distances are between the second and the fifth node. +Thus, minDistance and maxDistance is 5 - 2 = 3. +Note that the last node is not considered a local maxima because it does not have a next node. ++ +
+
Constraints:
+ +[2, 105].1 <= Node.val <= 105A room is represented by a 0-indexed 2D binary matrix room where a 0 represents an empty space and a 1 represents a space with an object. The top left corner of the room will be empty in all test cases.
A cleaning robot starts at the top left corner of the room and is facing right. The robot will continue heading straight until it reaches the edge of the room or it hits an object, after which it will turn 90 degrees clockwise and repeat this process. The starting space and all spaces that the robot visits are cleaned by it.
+ +Return the number of clean spaces in the room if the robot runs indefinetely.
+ ++
Example 1:
+
++ +
Input: room = [[0,0,0],[1,1,0],[0,0,0]]
+ +Output: 7
+ +Explanation:
+ +Example 2:
+
++ +
Input: room = [[0,1,0],[1,0,0],[0,0,0]]
+ +Output: 1
+ +Explanation:
+ +Example 3:
+ +Input: room = [[0,0,0],[0,0,0],[0,0,0]]
+ +Output: 8
+ ++
+
Constraints:
+ +m == room.lengthn == room[r].length1 <= m, n <= 300room[r][c] is either 0 or 1.room[0][0] == 0There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line.
You are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i].
Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line.
+ +Return the time taken for the person at position k (0-indexed) to finish buying tickets.
+
Example 1:
+ +Input: tickets = [2,3,2], k = 2 +Output: 6 +Explanation: +- In the first pass, everyone in the line buys a ticket and the line becomes [1, 2, 1]. +- In the second pass, everyone in the line buys a ticket and the line becomes [0, 1, 0]. +The person at position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds. ++ +
Example 2:
+ +Input: tickets = [5,1,1,1], k = 0 +Output: 8 +Explanation: +- In the first pass, everyone in the line buys a ticket and the line becomes [4, 0, 0, 0]. +- In the next 4 passes, only the person in position 0 is buying tickets. +The person at position 0 has successfully bought 5 tickets and it took 4 + 1 + 1 + 1 + 1 = 8 seconds. ++ +
+
Constraints:
+ +n == tickets.length1 <= n <= 1001 <= tickets[i] <= 1000 <= k < nYou are given a 0-indexed string s consisting of only lowercase English letters. Return the number of substrings in s that begin and end with the same character.
A substring is a contiguous non-empty sequence of characters within a string.
+ ++
Example 1:
+ +Input: s = "abcba" +Output: 7 +Explanation: +The substrings of length 1 that start and end with the same letter are: "a", "b", "c", "b", and "a". +The substring of length 3 that starts and ends with the same letter is: "bcb". +The substring of length 5 that starts and ends with the same letter is: "abcba". ++ +
Example 2:
+ +Input: s = "abacad" +Output: 9 +Explanation: +The substrings of length 1 that start and end with the same letter are: "a", "b", "a", "c", "a", and "d". +The substrings of length 3 that start and end with the same letter are: "aba" and "aca". +The substring of length 5 that starts and ends with the same letter is: "abaca". ++ +
Example 3:
+ +Input: s = "a" +Output: 1 +Explanation: +The substring of length 1 that starts and ends with the same letter is: "a". ++ +
+
Constraints:
+ +1 <= s.length <= 105s consists only of lowercase English letters.You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson.
Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa.
The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame.
+ +Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order.
+ ++
Example 1:
+ +Input: n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1 +Output: [0,1,2,3,5] +Explanation: +At time 0, person 0 shares the secret with person 1. +At time 5, person 1 shares the secret with person 2. +At time 8, person 2 shares the secret with person 3. +At time 10, person 1 shares the secret with person 5. +Thus, people 0, 1, 2, 3, and 5 know the secret after all the meetings. ++ +
Example 2:
+ +Input: n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3 +Output: [0,1,3] +Explanation: +At time 0, person 0 shares the secret with person 3. +At time 2, neither person 1 nor person 2 know the secret. +At time 3, person 3 shares the secret with person 0 and person 1. +Thus, people 0, 1, and 3 know the secret after all the meetings. ++ +
Example 3:
+ +Input: n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1 +Output: [0,1,2,3,4] +Explanation: +At time 0, person 0 shares the secret with person 1. +At time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3. +Note that person 2 can share the secret at the same time as receiving it. +At time 2, person 3 shares the secret with person 4. +Thus, people 0, 1, 2, 3, and 4 know the secret after all the meetings. ++ +
+
Constraints:
+ +2 <= n <= 1051 <= meetings.length <= 105meetings[i].length == 30 <= xi, yi <= n - 1xi != yi1 <= timei <= 1051 <= firstPerson <= n - 1Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "".
A string is palindromic if it reads the same forward and backward.
+ ++
Example 1:
+ +Input: words = ["abc","car","ada","racecar","cool"] +Output: "ada" +Explanation: The first string that is palindromic is "ada". +Note that "racecar" is also palindromic, but it is not the first. ++ +
Example 2:
+ +Input: words = ["notapalindrome","racecar"] +Output: "racecar" +Explanation: The first and only string that is palindromic is "racecar". ++ +
Example 3:
+ +Input: words = ["def","ghi"] +Output: "" +Explanation: There are no palindromic strings, so the empty string is returned. ++ +
+
Constraints:
+ +1 <= words.length <= 1001 <= words[i].length <= 100words[i] consists only of lowercase English letters.Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device.
There is one laser beam between any two security devices if both conditions are met:
+ +r1 and r2, where r1 < r2.i where r1 < i < r2, there are no security devices in the ith row.Laser beams are independent, i.e., one beam does not interfere nor join with another.
+ +Return the total number of laser beams in the bank.
+ ++
Example 1:
+
+Input: bank = ["011001","000000","010100","001000"] +Output: 8 +Explanation: Between each of the following device pairs, there is one beam. In total, there are 8 beams: + * bank[0][1] -- bank[2][1] + * bank[0][1] -- bank[2][3] + * bank[0][2] -- bank[2][1] + * bank[0][2] -- bank[2][3] + * bank[0][5] -- bank[2][1] + * bank[0][5] -- bank[2][3] + * bank[2][1] -- bank[3][2] + * bank[2][3] -- bank[3][2] +Note that there is no beam between any device on the 0th row with any on the 3rd row. +This is because the 2nd row contains security devices, which breaks the second condition. ++ +
Example 2:
+
+Input: bank = ["000","111","000"] +Output: 0 +Explanation: There does not exist two devices located on two different rows. ++ +
+
Constraints:
+ +m == bank.lengthn == bank[i].length1 <= m, n <= 500bank[i][j] is either '0' or '1'.A swap is defined as taking two distinct positions in an array and swapping the values in them.
+ +A circular array is defined as an array where we consider the first element and the last element to be adjacent.
+ +Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location.
+
Example 1:
+ +Input: nums = [0,1,0,1,1,0,0] +Output: 1 +Explanation: Here are a few of the ways to group all the 1's together: +[0,0,1,1,1,0,0] using 1 swap. +[0,1,1,1,0,0,0] using 1 swap. +[1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array). +There is no way to group all 1's together with 0 swaps. +Thus, the minimum number of swaps required is 1. ++ +
Example 2:
+ +Input: nums = [0,1,1,1,0,0,1,1,0] +Output: 2 +Explanation: Here are a few of the ways to group all the 1's together: +[1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array). +[1,1,1,1,1,0,0,0,0] using 2 swaps. +There is no way to group all 1's together with 0 or 1 swaps. +Thus, the minimum number of swaps required is 2. ++ +
Example 3:
+ +Input: nums = [1,1,0,0,1] +Output: 0 +Explanation: All the 1's are already grouped together due to the circular property of the array. +Thus, the minimum number of swaps required is 0. ++ +
+
Constraints:
+ +1 <= nums.length <= 105nums[i] is either 0 or 1.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 <= 1051 <= batteries[i] <= 109Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant.
One room divider has already been installed to the left of index 0, and another to the right of index n - 1. Additional room dividers can be installed. For each position between indices i - 1 and i (1 <= i <= n - 1), at most one divider can be installed.
Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way.
+ +Return the number of ways to divide the corridor. Since the answer may be very large, return it modulo 109 + 7. If there is no way, return 0.
+
Example 1:
+
+Input: corridor = "SSPPSPS" +Output: 3 +Explanation: There are 3 different ways to divide the corridor. +The black bars in the above image indicate the two room dividers already installed. +Note that in each of the ways, each section has exactly two seats. ++ +
Example 2:
+
+Input: corridor = "PPSPSP" +Output: 1 +Explanation: There is only 1 way to divide the corridor, by not installing any additional dividers. +Installing any would create some section that does not have exactly two seats. ++ +
Example 3:
+
+Input: corridor = "S" +Output: 0 +Explanation: There is no way to divide the corridor because there will always be a section that does not have exactly two seats. ++ +
+
Constraints:
+ +n == corridor.length1 <= n <= 105corridor[i] is either 'S' or 'P'.You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.
You should rearrange the elements of nums such that the modified array follows the given conditions:
nums is preserved.Return the modified array after rearranging the elements to satisfy the aforementioned conditions.
+ ++
Example 1:
+ +Input: nums = [3,1,-2,-5,2,-4] +Output: [3,-2,1,-5,2,-4] +Explanation: +The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4]. +The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4]. +Other ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions. ++ +
Example 2:
+ +Input: nums = [-1,1] +Output: [1,-1] +Explanation: +1 is the only positive integer and -1 the only negative integer in nums. +So nums is rearranged to [1,-1]. ++ +
+
Constraints:
+ +2 <= nums.length <= 2 * 105nums.length is even1 <= |nums[i]| <= 105nums consists of equal number of positive and negative integers.You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0.
For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's.
Return the head of the modified linked list.
+
Example 1:
+
+Input: head = [0,3,1,0,4,5,2,0] +Output: [4,11] +Explanation: +The above figure represents the given linked list. The modified list contains +- The sum of the nodes marked in green: 3 + 1 = 4. +- The sum of the nodes marked in red: 4 + 5 + 2 = 11. ++ +
Example 2:
+
+Input: head = [0,1,0,3,0,2,2,0] +Output: [1,3,4] +Explanation: +The above figure represents the given linked list. The modified list contains +- The sum of the nodes marked in green: 1 = 1. +- The sum of the nodes marked in red: 3 = 3. +- The sum of the nodes marked in yellow: 2 + 2 = 4. ++ +
+
Constraints:
+ +[3, 2 * 105].0 <= Node.val <= 1000Node.val == 0.Node.val == 0.You are given a 0-indexed integer array mapping which represents the mapping rule of a shuffled decimal system. mapping[i] = j means digit i should be mapped to digit j in this system.
The mapped value of an integer is the new integer obtained by replacing each occurrence of digit i in the integer with mapping[i] for all 0 <= i <= 9.
You are also given another integer array nums. Return the array nums sorted in non-decreasing order based on the mapped values of its elements.
Notes:
+ +nums should only be sorted based on their mapped values and not be replaced by them.+
Example 1:
+ +Input: mapping = [8,9,4,0,2,1,3,5,7,6], nums = [991,338,38] +Output: [338,38,991] +Explanation: +Map the number 991 as follows: +1. mapping[9] = 6, so all occurrences of the digit 9 will become 6. +2. mapping[1] = 9, so all occurrences of the digit 1 will become 9. +Therefore, the mapped value of 991 is 669. +338 maps to 007, or 7 after removing the leading zeros. +38 maps to 07, which is also 7 after removing leading zeros. +Since 338 and 38 share the same mapped value, they should remain in the same relative order, so 338 comes before 38. +Thus, the sorted array is [338,38,991]. ++ +
Example 2:
+ +Input: mapping = [0,1,2,3,4,5,6,7,8,9], nums = [789,456,123] +Output: [123,456,789] +Explanation: 789 maps to 789, 456 maps to 456, and 123 maps to 123. Thus, the sorted array is [123,456,789]. ++ +
+
Constraints:
+ +mapping.length == 100 <= mapping[i] <= 9mapping[i] are unique.1 <= nums.length <= 3 * 1040 <= nums[i] < 109You 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 <= 10000 <= edges.length <= min(2000, n * (n - 1) / 2)edges[i].length == 20 <= fromi, toi <= n - 1fromi != toiYou are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore,
isLefti == 1, then childi is the left child of parenti.isLefti == 0, then childi is the right child of parenti.Construct the binary tree described by descriptions and return its root.
The test cases will be generated such that the binary tree is valid.
+ ++
Example 1:
+
+Input: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]] +Output: [50,20,80,15,17,19] +Explanation: The root node is the node with value 50 since it has no parent. +The resulting binary tree is shown in the diagram. ++ +
Example 2:
+
+Input: descriptions = [[1,2,1],[2,3,0],[3,4,1]] +Output: [1,2,null,null,3,4] +Explanation: The root node is the node with value 1 since it has no parent. +The resulting binary tree is shown in the diagram. ++ +
+
Constraints:
+ +1 <= descriptions.length <= 104descriptions[i].length == 31 <= parenti, childi <= 1050 <= isLefti <= 1descriptions is valid.You are given an integer array matches where matches[i] = [winneri, loseri] indicates that the player winneri defeated player loseri in a match.
Return a list answer of size 2 where:
answer[0] is a list of all players that have not lost any matches.answer[1] is a list of all players that have lost exactly one match.The values in the two lists should be returned in increasing order.
+ +Note:
+ ++
Example 1:
+ +Input: matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]] +Output: [[1,2,10],[4,5,7,8]] +Explanation: +Players 1, 2, and 10 have not lost any matches. +Players 4, 5, 7, and 8 each have lost one match. +Players 3, 6, and 9 each have lost two matches. +Thus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8]. ++ +
Example 2:
+ +Input: matches = [[2,3],[1,3],[5,4],[6,4]] +Output: [[1,2,5,6],[]] +Explanation: +Players 1, 2, 5, and 6 have not lost any matches. +Players 3 and 4 each have lost two matches. +Thus, answer[0] = [1,2,5,6] and answer[1] = []. ++ +
+
Constraints:
+ +1 <= matches.length <= 105matches[i].length == 21 <= winneri, loseri <= 105winneri != loserimatches[i] are unique.You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array people of size n, where people[i] is the time that the ith person will arrive to see the flowers.
Return an integer array answer of size n, where answer[i] is the number of flowers that are in full bloom when the ith person arrives.
+
Example 1:
+
+Input: flowers = [[1,6],[3,7],[9,12],[4,13]], people = [2,3,7,11] +Output: [1,2,2,2] +Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive. +For each person, we return the number of flowers in full bloom during their arrival. ++ +
Example 2:
+
+Input: flowers = [[1,10],[3,3]], people = [3,3,2] +Output: [2,2,1] +Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive. +For each person, we return the number of flowers in full bloom during their arrival. ++ +
+
Constraints:
+ +1 <= flowers.length <= 5 * 104flowers[i].length == 21 <= starti <= endi <= 1091 <= people.length <= 5 * 1041 <= people[i] <= 109You are given a string num representing a large integer. An integer is good if it meets the following conditions:
num with length 3.Return the maximum good integer as a string or an empty string "" if no such integer exists.
Note:
+ +num or a good integer.+
Example 1:
+ +Input: num = "6777133339" +Output: "777" +Explanation: There are two distinct good integers: "777" and "333". +"777" is the largest, so we return "777". ++ +
Example 2:
+ +Input: num = "2300019" +Output: "000" +Explanation: "000" is the only good integer. ++ +
Example 3:
+ +Input: num = "42352338" +Output: "" +Explanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers. ++ +
+
Constraints:
+ +3 <= num.length <= 1000num only consists of digits.Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree.
Note:
+ +n elements is the sum of the n elements divided by n and rounded down to the nearest integer.root is a tree consisting of root and all of its descendants.+
Example 1:
+
+Input: root = [4,8,5,0,1,null,6] +Output: 5 +Explanation: +For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4. +For the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5. +For the node with value 0: The average of its subtree is 0 / 1 = 0. +For the node with value 1: The average of its subtree is 1 / 1 = 1. +For the node with value 6: The average of its subtree is 6 / 1 = 6. ++ +
Example 2:
+
+Input: root = [1] +Output: 1 +Explanation: For the node with value 1: The average of its subtree is 1 / 1 = 1. ++ +
+
Constraints:
+ +[1, 1000].0 <= Node.val <= 1000You are given the root of a full binary tree with the following properties:
0 or 1, where 0 represents False and 1 represents True.2 or 3, where 2 represents the boolean OR and 3 represents the boolean AND.The evaluation of a node is as follows:
+ +True or False.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:
+ +[1, 1000].0 <= Node.val <= 30 or 2 children.0 or 1.2 or 3.Design a food rating system that can do the following:
+ +Implement the FoodRatings class:
FoodRatings(String[] foods, String[] cuisines, int[] ratings) Initializes the system. The food items are described by foods, cuisines and ratings, all of which have a length of n.
+
+ foods[i] is the name of the ith food,cuisines[i] is the type of cuisine of the ith food, andratings[i] is the initial rating of the ith food.void changeRating(String food, int newRating) Changes the rating of the food item with the name food.String highestRated(String cuisine) Returns the name of the food item that has the highest rating for the given type of cuisine. If there is a tie, return the item with the lexicographically smaller name.Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order.
+
Example 1:
+ +Input
+["FoodRatings", "highestRated", "highestRated", "changeRating", "highestRated", "changeRating", "highestRated"]
+[[["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]], ["korean"], ["japanese"], ["sushi", 16], ["japanese"], ["ramen", 16], ["japanese"]]
+Output
+[null, "kimchi", "ramen", null, "sushi", null, "ramen"]
+
+Explanation
+FoodRatings foodRatings = new FoodRatings(["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]);
+foodRatings.highestRated("korean"); // return "kimchi"
+ // "kimchi" is the highest rated korean food with a rating of 9.
+foodRatings.highestRated("japanese"); // return "ramen"
+ // "ramen" is the highest rated japanese food with a rating of 14.
+foodRatings.changeRating("sushi", 16); // "sushi" now has a rating of 16.
+foodRatings.highestRated("japanese"); // return "sushi"
+ // "sushi" is the highest rated japanese food with a rating of 16.
+foodRatings.changeRating("ramen", 16); // "ramen" now has a rating of 16.
+foodRatings.highestRated("japanese"); // return "ramen"
+ // Both "sushi" and "ramen" have a rating of 16.
+ // However, "ramen" is lexicographically smaller than "sushi".
+
+
++
Constraints:
+ +1 <= n <= 2 * 104n == foods.length == cuisines.length == ratings.length1 <= foods[i].length, cuisines[i].length <= 10foods[i], cuisines[i] consist of lowercase English letters.1 <= ratings[i] <= 108foods are distinct.food will be the name of a food item in the system across all calls to changeRating.cuisine will be a type of cuisine of at least one food item in the system across all calls to highestRated.2 * 104 calls in total will be made to changeRating and highestRated.You are given a 0-indexed integer array books of length n where books[i] denotes the number of books on the ith shelf of a bookshelf.
You are going to take books from a contiguous section of the bookshelf spanning from l to r where 0 <= l <= r < n. For each index i in the range l <= i < r, you must take strictly fewer books from shelf i than shelf i + 1.
Return the maximum number of books you can take from the bookshelf.
+ ++
Example 1:
+ +Input: books = [8,5,2,7,9] +Output: 19 +Explanation: +- Take 1 book from shelf 1. +- Take 2 books from shelf 2. +- Take 7 books from shelf 3. +- Take 9 books from shelf 4. +You have taken 19 books, so return 19. +It can be proven that 19 is the maximum number of books you can take. ++ +
Example 2:
+ +Input: books = [7,0,3,4,5] +Output: 12 +Explanation: +- Take 3 books from shelf 2. +- Take 4 books from shelf 3. +- Take 5 books from shelf 4. +You have taken 12 books so return 12. +It can be proven that 12 is the maximum number of books you can take. ++ +
Example 3:
+ +Input: books = [8,2,3,7,3,4,0,1,4,3] +Output: 13 +Explanation: +- Take 1 book from shelf 0. +- Take 2 books from shelf 1. +- Take 3 books from shelf 2. +- Take 7 books from shelf 3. +You have taken 13 books so return 13. +It can be proven that 13 is the maximum number of books you can take. ++ +
+
Constraints:
+ +1 <= books.length <= 1050 <= books[i] <= 105A train line going through a city has two routes, the regular route and the express route. Both routes go through the same n + 1 stops labeled from 0 to n. Initially, you start on the regular route at stop 0.
You are given two 1-indexed integer arrays regular and express, both of length n. regular[i] describes the cost it takes to go from stop i - 1 to stop i using the regular route, and express[i] describes the cost it takes to go from stop i - 1 to stop i using the express route.
You are also given an integer expressCost which represents the cost to transfer from the regular route to the express route.
Note that:
+ +expressCost every time you transfer from the regular route to the express route.Return a 1-indexed array costs of length n, where costs[i] is the minimum cost to reach stop i from stop 0.
Note that a stop can be counted as reached from either route.
+ ++
Example 1:
+
+Input: regular = [1,6,9,5], express = [5,2,3,10], expressCost = 8 +Output: [1,7,14,19] +Explanation: The diagram above shows how to reach stop 4 from stop 0 with minimum cost. +- Take the regular route from stop 0 to stop 1, costing 1. +- Take the express route from stop 1 to stop 2, costing 8 + 2 = 10. +- Take the express route from stop 2 to stop 3, costing 3. +- Take the regular route from stop 3 to stop 4, costing 5. +The total cost is 1 + 10 + 3 + 5 = 19. +Note that a different route could be taken to reach the other stops with minimum cost. ++ +
Example 2:
+
+Input: regular = [11,5,13], express = [7,10,6], expressCost = 3 +Output: [10,15,24] +Explanation: The diagram above shows how to reach stop 3 from stop 0 with minimum cost. +- Take the express route from stop 0 to stop 1, costing 3 + 7 = 10. +- Take the regular route from stop 1 to stop 2, costing 5. +- Take the express route from stop 2 to stop 3, costing 3 + 6 = 9. +The total cost is 10 + 5 + 9 = 24. +Note that the expressCost is paid again to transfer back to the express route. ++ +
+
Constraints:
+ +n == regular.length == express.length1 <= n <= 1051 <= regular[i], express[i], expressCost <= 105You are given a 0-indexed integer array nums. In one operation you can replace any element of the array with any two elements that sum to it.
nums = [5,6,7]. In one operation, we can replace nums[1] with 2 and 4 and convert nums to [5,2,4,7].Return the minimum number of operations to make an array that is sorted in non-decreasing order.
+ ++
Example 1:
+ +Input: nums = [3,9,3] +Output: 2 +Explanation: Here are the steps to sort the array in non-decreasing order: +- From [3,9,3], replace the 9 with 3 and 6 so the array becomes [3,3,6,3] +- From [3,3,6,3], replace the 6 with 3 and 3 so the array becomes [3,3,3,3,3] +There are 2 steps to sort the array in non-decreasing order. Therefore, we return 2. + ++ +
Example 2:
+ +Input: nums = [1,2,3,4,5] +Output: 0 +Explanation: The array is already in non-decreasing order. Therefore, we return 0. ++ +
+
Constraints:
+ +1 <= nums.length <= 1051 <= nums[i] <= 109You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays.
We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions:
+ +2 equal elements. For example, the subarray [2,2] is good.3 equal elements. For example, the subarray [4,4,4] is good.3 consecutive increasing elements, that is, the difference between adjacent elements is 1. For example, the subarray [3,4,5] is good, but the subarray [1,3,5] is not.Return true if the array has at least one valid partition. Otherwise, return false.
+
Example 1:
+ +Input: nums = [4,4,4,5,6] +Output: true +Explanation: The array can be partitioned into the subarrays [4,4] and [4,5,6]. +This partition is valid, so we return true. ++ +
Example 2:
+ +Input: nums = [1,1,1,2] +Output: false +Explanation: There is no valid partition for this array. ++ +
+
Constraints:
+ +2 <= nums.length <= 1051 <= nums[i] <= 106You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if the following conditions are satisfied:
t is a subsequence of the string s.t is less than or equal to k.Return the length of the longest ideal string.
+ +A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
+ +Note that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25, not 1.
+
Example 1:
+ +Input: s = "acfgbd", k = 2 +Output: 4 +Explanation: The longest ideal string is "acbd". The length of this string is 4, so 4 is returned. +Note that "acfgbd" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order.+ +
Example 2:
+ +Input: s = "abcd", k = 3 +Output: 4 +Explanation: The longest ideal string is "abcd". The length of this string is 4, so 4 is returned. ++ +
+
Constraints:
+ +1 <= s.length <= 1050 <= k <= 25s consists of lowercase English letters.You are given an n x n integer matrix grid.
Generate an integer matrix maxLocal of size (n - 2) x (n - 2) such that:
maxLocal[i][j] is equal to the largest value of the 3 x 3 matrix in grid centered around row i + 1 and column j + 1.In other words, we want to find the largest value in every contiguous 3 x 3 matrix in grid.
Return the generated matrix.
+ ++
Example 1:
+
+Input: grid = [[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]] +Output: [[9,9],[8,6]] +Explanation: The diagram above shows the original matrix and the generated matrix. +Notice that each value in the generated matrix corresponds to the largest value of a contiguous 3 x 3 matrix in grid.+ +
Example 2:
+
+Input: grid = [[1,1,1,1,1],[1,1,1,1,1],[1,1,2,1,1],[1,1,1,1,1],[1,1,1,1,1]] +Output: [[2,2,2],[2,2,2],[2,2,2]] +Explanation: Notice that the 2 is contained within every contiguous 3 x 3 matrix in grid. ++ +
+
Constraints:
+ +n == grid.length == grid[i].length3 <= n <= 1001 <= grid[i][j] <= 100You are given the root of a binary tree with unique values, and an integer start. At minute 0, an infection starts from the node with value start.
Each minute, a node becomes infected if:
+ +Return the number of minutes needed for the entire tree to be infected.
+ ++
Example 1:
+
+Input: root = [1,5,3,null,4,10,6,9,2], start = 3 +Output: 4 +Explanation: The following nodes are infected during: +- Minute 0: Node 3 +- Minute 1: Nodes 1, 10 and 6 +- Minute 2: Node 5 +- Minute 3: Node 4 +- Minute 4: Nodes 9 and 2 +It takes 4 minutes for the whole tree to be infected so we return 4. ++ +
Example 2:
+
+Input: root = [1], start = 1 +Output: 0 +Explanation: At minute 0, the only node in the tree is infected so we return 0. ++ +
+
Constraints:
+ +[1, 105].1 <= Node.val <= 105start exists in the tree.You are given a 0-indexed array of strings garbage where garbage[i] represents the assortment of garbage at the ith house. garbage[i] consists only of the characters 'M', 'P' and 'G' representing one unit of metal, paper and glass garbage respectively. Picking up one unit of any type of garbage takes 1 minute.
You are also given a 0-indexed integer array travel where travel[i] is the number of minutes needed to go from house i to house i + 1.
There are three garbage trucks in the city, each responsible for picking up one type of garbage. Each garbage truck starts at house 0 and must visit each house in order; however, they do not need to visit every house.
Only one garbage truck may be used at any given moment. While one truck is driving or picking up garbage, the other two trucks cannot do anything.
+ +Return the minimum number of minutes needed to pick up all the garbage.
+ ++
Example 1:
+ +Input: garbage = ["G","P","GP","GG"], travel = [2,4,3] +Output: 21 +Explanation: +The paper garbage truck: +1. Travels from house 0 to house 1 +2. Collects the paper garbage at house 1 +3. Travels from house 1 to house 2 +4. Collects the paper garbage at house 2 +Altogether, it takes 8 minutes to pick up all the paper garbage. +The glass garbage truck: +1. Collects the glass garbage at house 0 +2. Travels from house 0 to house 1 +3. Travels from house 1 to house 2 +4. Collects the glass garbage at house 2 +5. Travels from house 2 to house 3 +6. Collects the glass garbage at house 3 +Altogether, it takes 13 minutes to pick up all the glass garbage. +Since there is no metal garbage, we do not need to consider the metal garbage truck. +Therefore, it takes a total of 8 + 13 = 21 minutes to collect all the garbage. ++ +
Example 2:
+ +Input: garbage = ["MMM","PGM","GP"], travel = [3,10] +Output: 37 +Explanation: +The metal garbage truck takes 7 minutes to pick up all the metal garbage. +The paper garbage truck takes 15 minutes to pick up all the paper garbage. +The glass garbage truck takes 15 minutes to pick up all the glass garbage. +It takes a total of 7 + 15 + 15 = 37 minutes to collect all the garbage. ++ +
+
Constraints:
+ +2 <= garbage.length <= 105garbage[i] consists of only the letters 'M', 'P', and 'G'.1 <= garbage[i].length <= 10travel.length == garbage.length - 11 <= travel[i] <= 100You are given a positive integer k. You are also given:
rowConditions of size n where rowConditions[i] = [abovei, belowi], andcolConditions of size m where colConditions[i] = [lefti, righti].The two arrays contain integers from 1 to k.
You have to build a k x k matrix that contains each of the numbers from 1 to k exactly once. The remaining cells should have the value 0.
The matrix should also satisfy the following conditions:
+ +abovei should appear in a row that is strictly above the row at which the number belowi appears for all i from 0 to n - 1.lefti should appear in a column that is strictly left of the column at which the number righti appears for all i from 0 to m - 1.Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix.
+ ++
Example 1:
+
+Input: k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]] +Output: [[3,0,0],[0,0,1],[0,2,0]] +Explanation: The diagram above shows a valid example of a matrix that satisfies all the conditions. +The row conditions are the following: +- Number 1 is in row 1, and number 2 is in row 2, so 1 is above 2 in the matrix. +- Number 3 is in row 0, and number 2 is in row 2, so 3 is above 2 in the matrix. +The column conditions are the following: +- Number 2 is in column 1, and number 1 is in column 2, so 2 is left of 1 in the matrix. +- Number 3 is in column 0, and number 2 is in column 1, so 3 is left of 2 in the matrix. +Note that there may be multiple correct answers. ++ +
Example 2:
+ +Input: k = 3, rowConditions = [[1,2],[2,3],[3,1],[2,3]], colConditions = [[2,1]] +Output: [] +Explanation: From the first two conditions, 3 has to be below 1 but the third conditions needs 3 to be above 1 to be satisfied. +No matrix can satisfy all the conditions, so we return the empty matrix. ++ +
+
Constraints:
+ +2 <= k <= 4001 <= rowConditions.length, colConditions.length <= 104rowConditions[i].length == colConditions[i].length == 21 <= abovei, belowi, lefti, righti <= kabovei != belowilefti != rightiYou are given an array nums consisting of positive integers.
Return the number of subarrays of nums that are in strictly increasing order.
A subarray is a contiguous part of an array.
+ ++
Example 1:
+ +Input: nums = [1,3,5,4,4,6] +Output: 10 +Explanation: The strictly increasing subarrays are the following: +- Subarrays of length 1: [1], [3], [5], [4], [4], [6]. +- Subarrays of length 2: [1,3], [3,5], [4,6]. +- Subarrays of length 3: [1,3,5]. +The total number of subarrays is 6 + 3 + 1 = 10. ++ +
Example 2:
+ +Input: nums = [1,2,3,4,5] +Output: 15 +Explanation: Every subarray is strictly increasing. There are 15 possible subarrays that we can take. ++ +
+
Constraints:
+ +1 <= nums.length <= 1051 <= nums[i] <= 106You are given an integer n. There are n rooms numbered from 0 to n - 1.
You are given a 2D integer array meetings where meetings[i] = [starti, endi] means that a meeting will be held during the half-closed time interval [starti, endi). All the values of starti are unique.
Meetings are allocated to rooms in the following manner:
+ +Return the number of the room that held the most meetings. If there are multiple rooms, return the room with the lowest number.
+ +A half-closed interval [a, b) is the interval between a and b including a and not including b.
+
Example 1:
+ +Input: n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]] +Output: 0 +Explanation: +- At time 0, both rooms are not being used. The first meeting starts in room 0. +- At time 1, only room 1 is not being used. The second meeting starts in room 1. +- At time 2, both rooms are being used. The third meeting is delayed. +- At time 3, both rooms are being used. The fourth meeting is delayed. +- At time 5, the meeting in room 1 finishes. The third meeting starts in room 1 for the time period [5,10). +- At time 10, the meetings in both rooms finish. The fourth meeting starts in room 0 for the time period [10,11). +Both rooms 0 and 1 held 2 meetings, so we return 0. ++ +
Example 2:
+ +Input: n = 3, meetings = [[1,20],[2,10],[3,5],[4,9],[6,8]] +Output: 1 +Explanation: +- At time 1, all three rooms are not being used. The first meeting starts in room 0. +- At time 2, rooms 1 and 2 are not being used. The second meeting starts in room 1. +- At time 3, only room 2 is not being used. The third meeting starts in room 2. +- At time 4, all three rooms are being used. The fourth meeting is delayed. +- At time 5, the meeting in room 2 finishes. The fourth meeting starts in room 2 for the time period [5,10). +- At time 6, all three rooms are being used. The fifth meeting is delayed. +- At time 10, the meetings in rooms 1 and 2 finish. The fifth meeting starts in room 1 for the time period [10,12). +Room 0 held 1 meeting while rooms 1 and 2 each held 2 meetings, so we return 1. ++ +
+
Constraints:
+ +1 <= n <= 1001 <= meetings.length <= 105meetings[i].length == 20 <= starti < endi <= 5 * 105starti are unique.You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n.
For each index i, names[i] and heights[i] denote the name and height of the ith person.
Return names sorted in descending order by the people's heights.
+
Example 1:
+ +Input: names = ["Mary","John","Emma"], heights = [180,165,170] +Output: ["Mary","Emma","John"] +Explanation: Mary is the tallest, followed by Emma and John. ++ +
Example 2:
+ +Input: names = ["Alice","Bob","Bob"], heights = [155,185,150] +Output: ["Bob","Alice","Bob"] +Explanation: The first Bob is the tallest, followed by Alice and the second Bob. ++ +
+
Constraints:
+ +n == names.length == heights.length1 <= n <= 1031 <= names[i].length <= 201 <= heights[i] <= 105names[i] consists of lower and upper case English letters.heights are distinct.You are given an integer array pref of size n. Find and return the array arr of size n that satisfies:
pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].Note that ^ denotes the bitwise-xor operation.
It can be proven that the answer is unique.
+ ++
Example 1:
+ +Input: pref = [5,2,0,3,1] +Output: [5,7,2,3,2] +Explanation: From the array [5,7,2,3,2] we have the following: +- pref[0] = 5. +- pref[1] = 5 ^ 7 = 2. +- pref[2] = 5 ^ 7 ^ 2 = 0. +- pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3. +- pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1. ++ +
Example 2:
+ +Input: pref = [13] +Output: [13] +Explanation: We have pref[0] = arr[0] = 13. ++ +
+
Constraints:
+ +1 <= pref.length <= 1050 <= pref[i] <= 106Given an integer array nums that does not contain any zeros, find the largest positive integer k such that -k also exists in the array.
Return the positive integer k. If there is no such integer, return -1.
+
Example 1:
+ +Input: nums = [-1,2,-3,3] +Output: 3 +Explanation: 3 is the only valid k we can find in the array. ++ +
Example 2:
+ +Input: nums = [-1,10,6,7,-7,1] +Output: 7 +Explanation: Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value. ++ +
Example 3:
+ +Input: nums = [-10,8,6,7,-2,-3] +Output: -1 +Explanation: There is no a single valid k, we return -1. ++ +
+
Constraints:
+ +1 <= nums.length <= 1000-1000 <= nums[i] <= 1000nums[i] != 0You are given an integer array nums and two integers minK and maxK.
A fixed-bound subarray of nums is a subarray that satisfies the following conditions:
minK.maxK.Return the number of fixed-bound subarrays.
+ +A subarray is a contiguous part of an array.
+ ++
Example 1:
+ +Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5 +Output: 2 +Explanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2]. ++ +
Example 2:
+ +Input: nums = [1,1,1,1], minK = 1, maxK = 1 +Output: 10 +Explanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays. ++ +
+
Constraints:
+ +2 <= nums.length <= 1051 <= nums[i], minK, maxK <= 106You are given a positive integer n representing n cities numbered from 1 to n. You are also given a 2D array roads, where roads[i] = [ai, bi, costi] indicates that there is a bidirectional road between cities ai and bi with a cost of traveling equal to costi.
You can buy apples in any city you want, but some cities have different costs to buy apples. You are given the 1-based array appleCost where appleCost[i] is the cost of buying one apple from city i.
You start at some city, traverse through various roads, and eventually buy exactly one apple from any city. After you buy that apple, you have to return back to the city you started at, but now the cost of all the roads will be multiplied by a given factor k.
Given the integer k, return a 1-based array answer of size n where answer[i] is the minimum total cost to buy an apple if you start at city i.
+
Example 1:
+
+Input: n = 4, roads = [[1,2,4],[2,3,2],[2,4,5],[3,4,1],[1,3,4]], appleCost = [56,42,102,301], k = 2 +Output: [54,42,48,51] +Explanation: The minimum cost for each starting city is the following: +- Starting at city 1: You take the path 1 -> 2, buy an apple at city 2, and finally take the path 2 -> 1. The total cost is 4 + 42 + 4 * 2 = 54. +- Starting at city 2: You directly buy an apple at city 2. The total cost is 42. +- Starting at city 3: You take the path 3 -> 2, buy an apple at city 2, and finally take the path 2 -> 3. The total cost is 2 + 42 + 2 * 2 = 48. +- Starting at city 4: You take the path 4 -> 3 -> 2 then you buy at city 2, and finally take the path 2 -> 3 -> 4. The total cost is 1 + 2 + 42 + 1 * 2 + 2 * 2 = 51. ++ +
Example 2:
+
+Input: n = 3, roads = [[1,2,5],[2,3,1],[3,1,2]], appleCost = [2,3,1], k = 3 +Output: [2,3,1] +Explanation: It is always optimal to buy the apple in the starting city. ++ +
+
Constraints:
+ +2 <= n <= 10001 <= roads.length <= 10001 <= ai, bi <= nai != bi1 <= costi <= 105appleCost.length == n1 <= appleCost[i] <= 1051 <= k <= 100You are given a 0-indexed m x n binary matrix grid.
A 0-indexed m x n difference matrix diff is created with the following procedure:
ith row be onesRowi.jth column be onesColj.ith row be zerosRowi.jth column be zerosColj.diff[i][j] = onesRowi + onesColj - zerosRowi - zerosColjReturn the difference matrix diff.
+
Example 1:
+
+Input: grid = [[0,1,1],[1,0,1],[0,0,1]] +Output: [[0,0,4],[0,0,4],[-2,-2,2]] +Explanation: +- diff[0][0] =+ +onesRow0 + onesCol0 - zerosRow0 - zerosCol0= 2 + 1 - 1 - 2 = 0 +- diff[0][1] =onesRow0 + onesCol1 - zerosRow0 - zerosCol1= 2 + 1 - 1 - 2 = 0 +- diff[0][2] =onesRow0 + onesCol2 - zerosRow0 - zerosCol2= 2 + 3 - 1 - 0 = 4 +- diff[1][0] =onesRow1 + onesCol0 - zerosRow1 - zerosCol0= 2 + 1 - 1 - 2 = 0 +- diff[1][1] =onesRow1 + onesCol1 - zerosRow1 - zerosCol1= 2 + 1 - 1 - 2 = 0 +- diff[1][2] =onesRow1 + onesCol2 - zerosRow1 - zerosCol2= 2 + 3 - 1 - 0 = 4 +- diff[2][0] =onesRow2 + onesCol0 - zerosRow2 - zerosCol0= 1 + 1 - 2 - 2 = -2 +- diff[2][1] =onesRow2 + onesCol1 - zerosRow2 - zerosCol1= 1 + 1 - 2 - 2 = -2 +- diff[2][2] =onesRow2 + onesCol2 - zerosRow2 - zerosCol2= 1 + 3 - 2 - 0 = 2 +
Example 2:
+
+Input: grid = [[1,1,1],[1,1,1]] +Output: [[5,5,5],[5,5,5]] +Explanation: +- diff[0][0] = onesRow0 + onesCol0 - zerosRow0 - zerosCol0 = 3 + 2 - 0 - 0 = 5 +- diff[0][1] = onesRow0 + onesCol1 - zerosRow0 - zerosCol1 = 3 + 2 - 0 - 0 = 5 +- diff[0][2] = onesRow0 + onesCol2 - zerosRow0 - zerosCol2 = 3 + 2 - 0 - 0 = 5 +- diff[1][0] = onesRow1 + onesCol0 - zerosRow1 - zerosCol0 = 3 + 2 - 0 - 0 = 5 +- diff[1][1] = onesRow1 + onesCol1 - zerosRow1 - zerosCol1 = 3 + 2 - 0 - 0 = 5 +- diff[1][2] = onesRow1 + onesCol2 - zerosRow1 - zerosCol2 = 3 + 2 - 0 - 0 = 5 ++ +
+
Constraints:
+ +m == grid.lengthn == grid[i].length1 <= m, n <= 1051 <= m * n <= 105grid[i][j] is either 0 or 1.You are given the customer visit log of a shop represented by a 0-indexed string customers consisting only of characters 'N' and 'Y':
ith character is 'Y', it means that customers come at the ith hour'N' indicates that no customers come at the ith hour.If the shop closes at the jth hour (0 <= j <= n), the penalty is calculated as follows:
1.1.Return the earliest hour at which the shop must be closed to incur a minimum penalty.
+ +Note that if a shop closes at the jth hour, it means the shop is closed at the hour j.
+
Example 1:
+ +Input: customers = "YYNY" +Output: 2 +Explanation: +- Closing the shop at the 0th hour incurs in 1+1+0+1 = 3 penalty. +- Closing the shop at the 1st hour incurs in 0+1+0+1 = 2 penalty. +- Closing the shop at the 2nd hour incurs in 0+0+0+1 = 1 penalty. +- Closing the shop at the 3rd hour incurs in 0+0+1+1 = 2 penalty. +- Closing the shop at the 4th hour incurs in 0+0+1+0 = 1 penalty. +Closing the shop at 2nd or 4th hour gives a minimum penalty. Since 2 is earlier, the optimal closing time is 2. ++ +
Example 2:
+ +Input: customers = "NNNNN" +Output: 0 +Explanation: It is best to close the shop at the 0th hour as no customers arrive.+ +
Example 3:
+ +Input: customers = "YYYY" +Output: 4 +Explanation: It is best to close the shop at the 4th hour as customers arrive at each hour. ++ +
+
Constraints:
+ +1 <= customers.length <= 105customers consists only of characters 'Y' and 'N'.Given a positive integer n, find the pivot integer x such that:
1 and x inclusively equals the sum of all elements between x and n inclusively.Return the pivot integer x. If no such integer exists, return -1. It is guaranteed that there will be at most one pivot index for the given input.
+
Example 1:
+ +Input: n = 8 +Output: 6 +Explanation: 6 is the pivot integer since: 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21. ++ +
Example 2:
+ +Input: n = 1 +Output: 1 +Explanation: 1 is the pivot integer since: 1 = 1. ++ +
Example 3:
+ +Input: n = 4 +Output: -1 +Explanation: It can be proved that no such integer exist. ++ +
+
Constraints:
+ +1 <= n <= 1000You are given two strings s and t consisting of only lowercase English letters.
Return the minimum number of characters that need to be appended to the end of s so that t becomes a subsequence of s.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
+ ++
Example 1:
+ +Input: s = "coaching", t = "coding"
+Output: 4
+Explanation: Append the characters "ding" to the end of s so that s = "coachingding".
+Now, t is a subsequence of s ("coachingding").
+It can be shown that appending any 3 characters to the end of s will never make t a subsequence.
+
+
+Example 2:
+ +Input: s = "abcde", t = "a"
+Output: 0
+Explanation: t is already a subsequence of s ("abcde").
+
+
+Example 3:
+ +Input: s = "z", t = "abcde"
+Output: 5
+Explanation: Append the characters "abcde" to the end of s so that s = "zabcde".
+Now, t is a subsequence of s ("zabcde").
+It can be shown that appending any 4 characters to the end of s will never make t a subsequence.
+
+
++
Constraints:
+ +1 <= s.length, t.length <= 105s and t consist only of lowercase English letters.Given an integer array nums, return the value of the bitwise OR of the sum of all possible subsequences in the array.
A subsequence is a sequence that can be derived from another sequence by removing zero or more elements without changing the order of the remaining elements.
+ ++
Example 1:
+ +Input: nums = [2,1,0,3] +Output: 7 +Explanation: All possible subsequence sums that we can have are: 0, 1, 2, 3, 4, 5, 6. +And we have 0 OR 1 OR 2 OR 3 OR 4 OR 5 OR 6 = 7, so we return 7. ++ +
Example 2:
+ +Input: nums = [0,0,0] +Output: 0 +Explanation: 0 is the only possible subsequence sum we can have, so we return 0. ++ +
+
Constraints:
+ +1 <= nums.length <= 1050 <= nums[i] <= 109There are n people standing in a line labeled from 1 to n. The first person in the line is holding a pillow initially. Every second, the person holding the pillow passes it to the next person standing in the line. Once the pillow reaches the end of the line, the direction changes, and people continue passing the pillow in the opposite direction.
nth person they pass it to the n - 1th person, then to the n - 2th person and so on.Given the two positive integers n and time, return the index of the person holding the pillow after time seconds.
+
Example 1:
+ +Input: n = 4, time = 5 +Output: 2 +Explanation: People pass the pillow in the following way: 1 -> 2 -> 3 -> 4 -> 3 -> 2. +After five seconds, the 2nd person is holding the pillow. ++ +
Example 2:
+ +Input: n = 3, time = 2 +Output: 3 +Explanation: People pass the pillow in the following way: 1 -> 2 -> 3. +After two seconds, the 3rd person is holding the pillow. ++ +
+
Constraints:
+ +2 <= n <= 10001 <= time <= 1000You 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 <= 201 <= nums[i], k <= 1000You are given an integer array nums. You need to create a 2D array from nums satisfying the following conditions:
nums.Return the resulting array. If there are multiple answers, return any of them.
+ +Note that the 2D array can have a different number of elements on each row.
+ ++
Example 1:
+ +Input: nums = [1,3,4,1,2,3,1] +Output: [[1,3,4,2],[1,3],[1]] +Explanation: We can create a 2D array that contains the following rows: +- 1,3,4,2 +- 1,3 +- 1 +All elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer. +It can be shown that we cannot have less than 3 rows in a valid array.+ +
Example 2:
+ +Input: nums = [1,2,3,4] +Output: [[4,3,2,1]] +Explanation: All elements of the array are distinct, so we can keep all of them in the first row of the 2D array. ++ +
+
Constraints:
+ +1 <= nums.length <= 2001 <= nums[i] <= nums.lengthYou are given a 0-indexed integer array nums and an integer p. Find p pairs of indices of nums such that the maximum difference amongst all the pairs is minimized. Also, ensure no index appears more than once amongst the p pairs.
Note that for a pair of elements at the index i and j, the difference of this pair is |nums[i] - nums[j]|, where |x| represents the absolute value of x.
Return the minimum maximum difference among all p pairs. We define the maximum of an empty set to be zero.
+
Example 1:
+ +Input: nums = [10,1,2,7,1,3], p = 2 +Output: 1 +Explanation: The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. +The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1. ++ +
Example 2:
+ +Input: nums = [4,2,1,2], p = 1 +Output: 0 +Explanation: Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain. ++ +
+
Constraints:
+ +1 <= nums.length <= 1050 <= nums[i] <= 1090 <= p <= (nums.length)/2Write a function that checks if a given value is an instance of a given class or superclass. For this problem, an object is considered an instance of a given class if that object has access to that class's methods.
+ +There are no constraints on the data types that can be passed to the function. For example, the value or the class could be undefined.
+
Example 1:
+ +Input: func = () => checkIfInstanceOf(new Date(), Date) +Output: true +Explanation: The object returned by the Date constructor is, by definition, an instance of Date. ++ +
Example 2:
+ +Input: func = () => { class Animal {}; class Dog extends Animal {}; return checkIfInstanceOf(new Dog(), Animal); }
+Output: true
+Explanation:
+class Animal {};
+class Dog extends Animal {};
+checkIfInstanceOf(new Dog(), Animal); // true
+
+Dog is a subclass of Animal. Therefore, a Dog object is an instance of both Dog and Animal.
+
+Example 3:
+ +Input: func = () => checkIfInstanceOf(Date, Date) +Output: false +Explanation: A date constructor cannot logically be an instance of itself. ++ +
Example 4:
+ +Input: func = () => checkIfInstanceOf(5, Number) +Output: true +Explanation: 5 is a Number. Note that the "instanceof" keyword would return false. However, it is still considered an instance of Number because it accesses the Number methods. For example "toFixed()". ++
Write code that enhances all arrays such that you can call the array.last() method on any array and it will return the last element. If there are no elements in the array, it should return -1.
You may assume the array is the output of JSON.parse.
+
Example 1:
+ +Input: nums = [null, {}, 3]
+Output: 3
+Explanation: Calling nums.last() should return the last element: 3.
+
+
+Example 2:
+ +Input: nums = [] +Output: -1 +Explanation: Because there are no elements, return -1. ++ +
+
Constraints:
+ +0 <= arr.length <= 1000Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (n, n + 1, n + 2, etc).
+
Example 1:
+ +Input: +n = 10 +["call","call","call"] +Output: [10,11,12] +Explanation: +counter() = 10 // The first time counter() is called, it returns n. +counter() = 11 // Returns 1 more than the previous time. +counter() = 12 // Returns 1 more than the previous time. ++ +
Example 2:
+ +Input: +n = -2 +["call","call","call","call","call"] +Output: [-2,-1,0,1,2] +Explanation: counter() initially returns -2. Then increases after each sebsequent call. ++ +
+
Constraints:
+ +-1000 <= n <= 1000At most 1000 calls to counter() will be madeGiven a positive integer millis, write an asynchronous function that sleeps for millis milliseconds. It can resolve any value.
+
Example 1:
+ +Input: millis = 100
+Output: 100
+Explanation: It should return a promise that resolves after 100ms.
+let t = Date.now();
+sleep(100).then(() => {
+ console.log(Date.now() - t); // 100
+});
+
+
+Example 2:
+ +Input: millis = 200 +Output: 200 +Explanation: It should return a promise that resolves after 200ms. ++ +
+
Constraints:
+ +1 <= millis <= 1000Write a class that allows getting and setting key-value pairs, however a time until expiration is associated with each key.
+ +The class has three public methods:
+ +set(key, value, duration): accepts an integer key, an integer value, and a duration in milliseconds. Once the duration has elapsed, the key should be inaccessible. The method should return true if the same un-expired key already exists and false otherwise. Both the value and duration should be overwritten if the key already exists.
get(key): if an un-expired key exists, it should return the associated value. Otherwise it should return -1.
count(): returns the count of un-expired keys.
+
Example 1:
+ +Input: +["TimeLimitedCache", "set", "get", "count", "get"] +[[], [1, 42, 100], [1], [], [1]] +[0, 0, 50, 50, 150] +Output: [null, false, 42, 1, -1] +Explanation: +At t=0, the cache is constructed. +At t=0, a key-value pair (1: 42) is added with a time limit of 100ms. The value doesn't exist so false is returned. +At t=50, key=1 is requested and the value of 42 is returned. +At t=50, count() is called and there is one active key in the cache. +At t=100, key=1 expires. +At t=150, get(1) is called but -1 is returned because the cache is empty. ++ +
Example 2:
+ +Input: +["TimeLimitedCache", "set", "set", "get", "get", "get", "count"] +[[], [1, 42, 50], [1, 50, 100], [1], [1], [1], []] +[0, 0, 40, 50, 120, 200, 250] +Output: [null, false, true, 50, 50, -1, 0] +Explanation: +At t=0, the cache is constructed. +At t=0, a key-value pair (1: 42) is added with a time limit of 50ms. The value doesn't exist so false is returned. +At t=40, a key-value pair (1: 50) is added with a time limit of 100ms. A non-expired value already existed so true is returned and the old value was overwritten. +At t=50, get(1) is called which returned 50. +At t=120, get(1) is called which returned 50. +At t=140, key=1 expires. +At t=200, get(1) is called but the cache is empty so -1 is returned. +At t=250, count() returns 0 because the cache is empty. ++ +
+
Constraints:
+ +0 <= key <= 1090 <= value <= 1090 <= duration <= 1000Given a function fn, return a memoized version of that function.
A memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value.
+ +You can assume there are 3 possible input functions: sum, fib, and factorial.
sum accepts two integers a and b and returns a + b.fib accepts a single integer n and returns 1 if n <= 1 or fib(n - 1) + fib(n - 2) otherwise.factorial accepts a single integer n and returns 1 if n <= 1 or factorial(n - 1) * n otherwise.+
Example 1:
+ +Input +"sum" +["call","call","getCallCount","call","getCallCount"] +[[2,2],[2,2],[],[1,2],[]] +Output +[4,4,1,3,2] + +Explanation +const sum = (a, b) => a + b; +const memoizedSum = memoize(sum); +memoizedSum(2, 2); // Returns 4. sum() was called as (2, 2) was not seen before. +memoizedSum(2, 2); // Returns 4. However sum() was not called because the same inputs were seen before. +// Total call count: 1 +memoizedSum(1, 2); // Returns 3. sum() was called as (1, 2) was not seen before. +// Total call count: 2 ++ +
Example 2:
+ +Input +"factorial" +["call","call","call","getCallCount","call","getCallCount"] +[[2],[3],[2],[],[3],[]] +Output +[2,6,2,2,6,2] + +Explanation +const factorial = (n) => (n <= 1) ? 1 : (n * factorial(n - 1)); +const memoFactorial = memoize(factorial); +memoFactorial(2); // Returns 2. +memoFactorial(3); // Returns 6. +memoFactorial(2); // Returns 2. However factorial was not called because 2 was seen before. +// Total call count: 2 +memoFactorial(3); // Returns 6. However factorial was not called because 3 was seen before. +// Total call count: 2 ++ +
Example 3:
+ +Input +"fib" +["call","getCallCount"] +[[5],[]] +Output +[8,1] + +Explanation +fib(5) = 8 +// Total call count: 1 + ++ +
+
Constraints:
+ +0 <= a, b <= 1051 <= n <= 10at most 105 function callsat most 105 attempts to access callCountinput function is sum, fib, or factorialWrite code that enhances all arrays such that you can call the snail(rowsCount, colsCount) method that transforms the 1D array into a 2D array organised in the pattern known as snail traversal order. Invalid input values should output an empty array. If rowsCount * colsCount !== nums.length, the input is considered invalid.
Snail traversal order starts at the top left cell with the first value of the current array. It then moves through the entire first column from top to bottom, followed by moving to the next column on the right and traversing it from bottom to top. This pattern continues, alternating the direction of traversal with each column, until the entire current array is covered. For example, when given the input array [19, 10, 3, 7, 9, 8, 5, 2, 1, 17, 16, 14, 12, 18, 6, 13, 11, 20, 4, 15] with rowsCount = 5 and colsCount = 4, the desired output matrix is shown below. Note that iterating the matrix following the arrows corresponds to the order of numbers in the original array.
+ +

+
Example 1:
+ +Input: +nums = [19, 10, 3, 7, 9, 8, 5, 2, 1, 17, 16, 14, 12, 18, 6, 13, 11, 20, 4, 15] +rowsCount = 5 +colsCount = 4 +Output: +[ + [19,17,16,15], + [10,1,14,4], + [3,2,12,20], + [7,5,18,11], + [9,8,6,13] +] ++ +
Example 2:
+ +Input: +nums = [1,2,3,4] +rowsCount = 1 +colsCount = 4 +Output: [[1, 2, 3, 4]] ++ +
Example 3:
+ +Input: +nums = [1,3] +rowsCount = 2 +colsCount = 2 +Output: [] +Explanation: 2 multiplied by 2 is 4, and the original array [1,3] has a length of 2; therefore, the input is invalid. ++ +
+
Constraints:
+ +0 <= nums.length <= 2501 <= nums[i] <= 10001 <= rowsCount <= 2501 <= colsCount <= 250+
Given a multi-dimensional array arr and a depth n, return a flattened version of that array.
A multi-dimensional array is a recursive data structure that contains integers or other multi-dimensional arrays.
+ +A flattened array is a version of that array with some or all of the sub-arrays removed and replaced with the actual elements in that sub-array. This flattening operation should only be done if the current depth of nesting is less than n. The depth of the elements in the first array are considered to be 0.
Please solve it without the built-in Array.flat method.
+
Example 1:
+ +Input +arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]] +n = 0 +Output +[1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]] + +Explanation +Passing a depth of n=0 will always result in the original array. This is because the smallest possible depth of a subarray (0) is not less than n=0. Thus, no subarray should be flattened.+ +
Example 2:
+ +Input +arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]] +n = 1 +Output +[1, 2, 3, 4, 5, 6, 7, 8, [9, 10, 11], 12, 13, 14, 15] + +Explanation +The subarrays starting with 4, 7, and 13 are all flattened. This is because their depth of 0 is less than 1. However [9, 10, 11] remains unflattened because its depth is 1.+ +
Example 3:
+ +Input +arr = [[1, 2, 3], [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]] +n = 2 +Output +[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + +Explanation +The maximum depth of any subarray is 1. Thus, all of them are flattened.+ +
+
Constraints:
+ +0 <= count of numbers in arr <= 1050 <= count of subarrays in arr <= 105maxDepth <= 1000-1000 <= each number <= 10000 <= n <= 1000Given an integer array nums, a reducer function fn, and an initial value init, return a reduced array.
A reduced array is created by applying the following operation: val = fn(init, nums[0]), val = fn(val, nums[1]), val = fn(val, nums[2]), ... until every element in the array has been processed. The final value of val is returned.
If the length of the array is 0, it should return init.
Please solve it without using the built-in Array.reduce method.
+
Example 1:
+ +Input:
+nums = [1,2,3,4]
+fn = function sum(accum, curr) { return accum + curr; }
+init = 0
+Output: 10
+Explanation:
+initially, the value is init=0.
+(0) + nums[0] = 1
+(1) + nums[1] = 3
+(3) + nums[2] = 6
+(6) + nums[3] = 10
+The final answer is 10.
+
+
+Example 2:
+ +Input:
+nums = [1,2,3,4]
+fn = function sum(accum, curr) { return accum + curr * curr; }
+init = 100
+Output: 130
+Explanation:
+initially, the value is init=100.
+(100) + nums[0]^2 = 101
+(101) + nums[1]^2 = 105
+(105) + nums[2]^2 = 114
+(114) + nums[3]^2 = 130
+The final answer is 130.
+
+
+Example 3:
+ +Input:
+nums = []
+fn = function sum(accum, curr) { return 0; }
+init = 25
+Output: 25
+Explanation: For empty arrays, the answer is always init.
+
+
++
Constraints:
+ +0 <= nums.length <= 10000 <= nums[i] <= 10000 <= init <= 1000Given a function fn and a time in milliseconds t, return a debounced version of that function.
A debounced function is a function whose execution is delayed by t milliseconds and whose execution is cancelled if it is called again within that window of time. The debounced function should also receive the passed parameters.
For example, let's say t = 50ms, and the function was called at 30ms, 60ms, and 100ms. The first 2 function calls would be cancelled, and the 3rd function call would be executed at 150ms. If instead t = 35ms, The 1st call would be cancelled, the 2nd would be executed at 95ms, and the 3rd would be executed at 135ms.

The above diagram shows how debounce will transform events. Each rectangle represents 100ms and the debounce time is 400ms. Each color represents a different set of inputs.
+ +Please solve it without using lodash's _.debounce() function.
+
Example 1:
+ +Input:
+t = 50
+calls = [
+ {"t": 50, inputs: [1]},
+ {"t": 75, inputs: [2]}
+]
+Output: [{"t": 125, inputs: [2]}]
+Explanation:
+let start = Date.now();
+function log(...inputs) {
+ console.log([Date.now() - start, inputs ])
+}
+const dlog = debounce(log, 50);
+setTimeout(() => dlog(1), 50);
+setTimeout(() => dlog(2), 75);
+
+The 1st call is cancelled by the 2nd call because the 2nd call occurred before 100ms
+The 2nd call is delayed by 50ms and executed at 125ms. The inputs were (2).
+
+
+Example 2:
+ +Input:
+t = 20
+calls = [
+ {"t": 50, inputs: [1]},
+ {"t": 100, inputs: [2]}
+]
+Output: [{"t": 70, inputs: [1]}, {"t": 120, inputs: [2]}]
+Explanation:
+The 1st call is delayed until 70ms. The inputs were (1).
+The 2nd call is delayed until 120ms. The inputs were (2).
+
+
+Example 3:
+ +Input:
+t = 150
+calls = [
+ {"t": 50, inputs: [1, 2]},
+ {"t": 300, inputs: [3, 4]},
+ {"t": 300, inputs: [5, 6]}
+]
+Output: [{"t": 200, inputs: [1,2]}, {"t": 450, inputs: [5, 6]}]
+Explanation:
+The 1st call is delayed by 150ms and ran at 200ms. The inputs were (1, 2).
+The 2nd call is cancelled by the 3rd call
+The 3rd call is delayed by 150ms and ran at 450ms. The inputs were (5, 6).
+
+
++
Constraints:
+ +0 <= t <= 10001 <= calls.length <= 100 <= calls[i].t <= 10000 <= calls[i].inputs.length <= 10Given two objects o1 and o2, check if they are deeply equal.
For two objects to be deeply equal, they must contain the same keys, and the associated values must also be deeply equal. Two objects are also considered deeply equal if they pass the === equality check.
You may assume both objects are the output of JSON.parse. In other words, they are valid JSON.
Please solve it without using lodash's _.isEqual() function.
+
Example 1:
+ +Input: o1 = {"x":1,"y":2}, o2 = {"x":1,"y":2}
+Output: true
+Explanation: The keys and values match exactly.
+
+
+Example 2:
+ +Input: o1 = {"y":2,"x":1}, o2 = {"x":1,"y":2}
+Output: true
+Explanation: Although the keys are in a different order, they still match exactly.
+
+
+Example 3:
+ +Input: o1 = {"x":null,"L":[1,2,3]}, o2 = {"x":null,"L":["1","2","3"]}
+Output: false
+Explanation: The array of numbers is different from the array of strings.
+
+
+Example 4:
+ +Input: o1 = true, o2 = false +Output: false +Explanation: true !== false+ +
+
Constraints:
+ +1 <= JSON.stringify(o1).length <= 1051 <= JSON.stringify(o2).length <= 105maxNestingDepth <= 1000Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions.
The function composition of [f(x), g(x), h(x)] is fn(x) = f(g(h(x))).
The function composition of an empty list of functions is the identity function f(x) = x.
You may assume each function in the array accepts one integer as input and returns one integer as output.
+ ++
Example 1:
+ +Input: functions = [x => x + 1, x => x * x, x => 2 * x], x = 4 +Output: 65 +Explanation: +Evaluating from right to left ... +Starting with x = 4. +2 * (4) = 8 +(8) * (8) = 64 +(64) + 1 = 65 ++ +
Example 2:
+ +Input: functions = [x => 10 * x, x => 10 * x, x => 10 * x], x = 1 +Output: 1000 +Explanation: +Evaluating from right to left ... +10 * (1) = 10 +10 * (10) = 100 +10 * (100) = 1000 ++ +
Example 3:
+ +Input: functions = [], x = 42 +Output: 42 +Explanation: +The composition of zero functions is the identity function+ +
+
Constraints:
+ +-1000 <= x <= 10000 <= functions.length <= 1000all functions accept and return a single integerGiven a function fn, return a memoized version of that function.
A memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value.
+ +fn can be any function and there are no constraints on what type of values it accepts. Inputs are considered identical if they are === to each other.
+
Example 1:
+ +Input:
+getInputs = () => [[2,2],[2,2],[1,2]]
+fn = function (a, b) { return a + b; }
+Output: [{"val":4,"calls":1},{"val":4,"calls":1},{"val":3,"calls":2}]
+Explanation:
+const inputs = getInputs();
+const memoized = memoize(fn);
+for (const arr of inputs) {
+ memoized(...arr);
+}
+
+For the inputs of (2, 2): 2 + 2 = 4, and it required a call to fn().
+For the inputs of (2, 2): 2 + 2 = 4, but those inputs were seen before so no call to fn() was required.
+For the inputs of (1, 2): 1 + 2 = 3, and it required another call to fn() for a total of 2.
+
+
+Example 2:
+ +Input:
+getInputs = () => [[{},{}],[{},{}],[{},{}]]
+fn = function (a, b) { return ({...a, ...b}); }
+Output: [{"val":{},"calls":1},{"val":{},"calls":2},{"val":{},"calls":3}]
+Explanation:
+Merging two empty objects will always result in an empty object. It may seem like there should only be 1 call to fn() because of cache-hits, however none of those objects are === to each other.
+
+
+Example 3:
+ +Input:
+getInputs = () => { const o = {}; return [[o,o],[o,o],[o,o]]; }
+fn = function (a, b) { return ({...a, ...b}); }
+Output: [{"val":{},"calls":1},{"val":{},"calls":1},{"val":{},"calls":1}]
+Explanation:
+Merging two empty objects will always result in an empty object. The 2nd and 3rd third function calls result in a cache-hit. This is because every object passed in is identical.
+
+
++
Constraints:
+ +1 <= inputs.length <= 1050 <= inputs.flat().length <= 105inputs[i][j] != NaNWrite code that enhances all arrays such that you can call the array.groupBy(fn) method on any array and it will return a grouped version of the array.
A grouped array is an object where each key is the output of fn(arr[i]) and each value is an array containing all items in the original array with that key.
The provided callback fn will accept an item in the array and return a string key.
The order of each value list should be the order the items appear in the array. Any order of keys is acceptable.
+ +Please solve it without lodash's _.groupBy function.
+
Example 1:
+ +Input:
+array = [
+ {"id":"1"},
+ {"id":"1"},
+ {"id":"2"}
+],
+fn = function (item) {
+ return item.id;
+}
+Output:
+{
+ "1": [{"id": "1"}, {"id": "1"}],
+ "2": [{"id": "2"}]
+}
+Explanation:
+Output is from array.groupBy(fn).
+The selector function gets the "id" out of each item in the array.
+There are two objects with an "id" of 1. Both of those objects are put in the first array.
+There is one object with an "id" of 2. That object is put in the second array.
+
+
+Example 2:
+ +Input:
+array = [
+ [1, 2, 3],
+ [1, 3, 5],
+ [1, 5, 9]
+]
+fn = function (list) {
+ return String(list[0]);
+}
+Output:
+{
+ "1": [[1, 2, 3], [1, 3, 5], [1, 5, 9]]
+}
+Explanation:
+The array can be of any type. In this case, the selector function defines the key as being the first element in the array.
+All the arrays have 1 as their first element so they are grouped together.
+{
+ "1": [[1, 2, 3], [1, 3, 5], [1, 5, 9]]
+}
+
+
+Example 3:
+ +Input:
+array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+fn = function (n) {
+ return String(n > 5);
+}
+Output:
+{
+ "true": [6, 7, 8, 9, 10],
+ "false": [1, 2, 3, 4, 5]
+}
+Explanation:
+The selector function splits the array by whether each number is greater than 5.
+
+
++
Constraints:
+ +0 <= array.length <= 105fn returns a stringGiven a function fn, return a curried version of that function.
A curried function is a function that accepts fewer or an equal number of parameters as the original function and returns either another curried function or the same value the original function would have returned.
+ +In practical terms, if you called the original function like sum(1,2,3), you would call the curried version like csum(1)(2)(3), csum(1)(2,3), csum(1,2)(3), or csum(1,2,3). All these methods of calling the curried function should return the same value as the original.
+
Example 1:
+ +Input:
+fn = function sum(a, b, c) { return a + b + c; }
+inputs = [[1],[2],[3]]
+Output: 6
+Explanation:
+The code being executed is:
+const curriedSum = curry(fn);
+curriedSum(1)(2)(3) === 6;
+curriedSum(1)(2)(3) should return the same value as sum(1, 2, 3).
+
+
+Example 2:
+ +Input:
+fn = function sum(a, b, c) { return a + b + c; }
+inputs = [[1,2],[3]]
+Output: 6
+Explanation:
+curriedSum(1, 2)(3) should return the same value as sum(1, 2, 3).
+
+Example 3:
+ +Input:
+fn = function sum(a, b, c) { return a + b + c; }
+inputs = [[],[],[1,2,3]]
+Output: 6
+Explanation:
+You should be able to pass the parameters in any way, including all at once or none at all.
+curriedSum()()(1, 2, 3) should return the same value as sum(1, 2, 3).
+
+
+Example 4:
+ +Input:
+fn = function life() { return 42; }
+inputs = [[]]
+Output: 42
+Explanation:
+currying a function that accepts zero parameters should effectively do nothing.
+curriedLife() === 42
+
+
++
Constraints:
+ +1 <= inputs.length <= 10000 <= inputs[i][j] <= 1050 <= fn.length <= 1000inputs.flat().length == fn.lengthfn.length > 0 then the last array in inputs is not emptyfn.length === 0 then inputs.length === 1 Given an object, return a valid JSON string of that object. You may assume the object only includes strings, integers, arrays, objects, booleans, and null. The returned string should not include extra spaces. The order of keys should be the same as the order returned by Object.keys().
Please solve it without using the built-in JSON.stringify method.
+
Example 1:
+ +Input: object = {"y":1,"x":2}
+Output: {"y":1,"x":2}
+Explanation:
+Return the JSON representation.
+Note that the order of keys should be the same as the order returned by Object.keys().
+
+Example 2:
+ +Input: object = {"a":"str","b":-12,"c":true,"d":null}
+Output: {"a":"str","b":-12,"c":true,"d":null}
+Explanation:
+The primitives of JSON are strings, numbers, booleans, and null.
+
+
+Example 3:
+ +Input: object = {"key":{"a":1,"b":[{},null,"Hello"]}}
+Output: {"key":{"a":1,"b":[{},null,"Hello"]}}
+Explanation:
+Objects and arrays can include other objects and arrays.
+
+
+Example 4:
+ +Input: object = true +Output: true +Explanation: +Primitive types are valid inputs.+ +
+
Constraints:
+ +object includes strings, integers, booleans, arrays, objects, and null1 <= JSON.stringify(object).length <= 105maxNestingLevel <= 1000all strings will only contain alphanumeric charactersGiven an integer array arr and a filtering function fn, return a filtered array filteredArr.
The fn function takes one or two arguments:
arr[i] - number from the arri - index of arr[i]filteredArr should only contain the elements from the arr for which the expression fn(arr[i], i) evaluates to a truthy value. A truthy value is a value where Boolean(value) returns true.
Please solve it without the built-in Array.filter method.
+ ++
Example 1:
+ +Input: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; }
+Output: [20,30]
+Explanation:
+const newArray = filter(arr, fn); // [20, 30]
+The function filters out values that are not greater than 10
+
+Example 2:
+ +Input: arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; }
+Output: [1]
+Explanation:
+fn can also accept the index of each element
+In this case, the function removes elements not at index 0
+
+
+Example 3:
+ +Input: arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 }
+Output: [-2,0,1,2]
+Explanation:
+Falsey values such as 0 should be filtered out
+
+
++
Constraints:
+ +0 <= arr.length <= 1000-109 <= arr[i] <= 109Given an integer array arr and a mapping function fn, return a new array with a transformation applied to each element.
The returned array should be created such that returnedArray[i] = fn(arr[i], i).
Please solve it without the built-in Array.map method.
+
Example 1:
+ +Input: arr = [1,2,3], fn = function plusone(n) { return n + 1; }
+Output: [2,3,4]
+Explanation:
+const newArray = map(arr, plusone); // [2,3,4]
+The function increases each value in the array by one.
+
+
+Example 2:
+ +Input: arr = [1,2,3], fn = function plusI(n, i) { return n + i; }
+Output: [1,3,5]
+Explanation: The function increases each value by the index it resides in.
+
+
+Example 3:
+ +Input: arr = [10,20,30], fn = function constant() { return 42; }
+Output: [42,42,42]
+Explanation: The function always returns 42.
+
+
++
Constraints:
+ +0 <= arr.length <= 1000-109 <= arr[i] <= 109fn returns a numberGiven an array of asynchronous functions functions and a pool limit n, return an asynchronous function promisePool. It should return a promise that resolves when all the input functions resolve.
Pool limit is defined as the maximum number promises that can be pending at once. promisePool should begin execution of as many functions as possible and continue executing new functions when old promises resolve. promisePool should execute functions[i] then functions[i + 1] then functions[i + 2], etc. When the last promise resolves, promisePool should also resolve.
For example, if n = 1, promisePool will execute one function at a time in series. However, if n = 2, it first executes two functions. When either of the two functions resolve, a 3rd function should be executed (if available), and so on until there are no functions left to execute.
You can assume all functions never reject. It is acceptable for promisePool to return a promise that resolves any value.
+
Example 1:
+ +Input: +functions = [ + () => new Promise(res => setTimeout(res, 300)), + () => new Promise(res => setTimeout(res, 400)), + () => new Promise(res => setTimeout(res, 200)) +] +n = 2 +Output: [[300,400,500],500] +Explanation: +Three functions are passed in. They sleep for 300ms, 400ms, and 200ms respectively. +They resolve at 300ms, 400ms, and 500ms respectively. The returned promise resolves at 500ms. +At t=0, the first 2 functions are executed. The pool size limit of 2 is reached. +At t=300, the 1st function resolves, and the 3rd function is executed. Pool size is 2. +At t=400, the 2nd function resolves. There is nothing left to execute. Pool size is 1. +At t=500, the 3rd function resolves. Pool size is zero so the returned promise also resolves. ++ +
Example 2:
+ +Input: +functions = [ + () => new Promise(res => setTimeout(res, 300)), + () => new Promise(res => setTimeout(res, 400)), + () => new Promise(res => setTimeout(res, 200)) +] +n = 5 +Output: [[300,400,200],400] +Explanation: +The three input promises resolve at 300ms, 400ms, and 200ms respectively. +The returned promise resolves at 400ms. +At t=0, all 3 functions are executed. The pool limit of 5 is never met. +At t=200, the 3rd function resolves. Pool size is 2. +At t=300, the 1st function resolved. Pool size is 1. +At t=400, the 2nd function resolves. Pool size is 0, so the returned promise also resolves. ++ +
Example 3:
+ +Input: +functions = [ + () => new Promise(res => setTimeout(res, 300)), + () => new Promise(res => setTimeout(res, 400)), + () => new Promise(res => setTimeout(res, 200)) +] +n = 1 +Output: [[300,700,900],900] +Explanation: +The three input promises resolve at 300ms, 700ms, and 900ms respectively. +The returned promise resolves at 900ms. +At t=0, the 1st function is executed. Pool size is 1. +At t=300, the 1st function resolves and the 2nd function is executed. Pool size is 1. +At t=700, the 2nd function resolves and the 3rd function is executed. Pool size is 1. +At t=900, the 3rd function resolves. Pool size is 0 so the returned promise resolves. ++ +
+
Constraints:
+ +0 <= functions.length <= 101 <= n <= 10Given an asynchronous function fn and a time t in milliseconds, return a new time limited version of the input function. fn takes arguments provided to the time limited function.
The time limited function should follow these rules:
+ +fn completes within the time limit of t milliseconds, the time limited function should resolve with the result.fn exceeds the time limit, the time limited function should reject with the string "Time Limit Exceeded".+
Example 1:
+ +Input:
+fn = async (n) => {
+ await new Promise(res => setTimeout(res, 100));
+ return n * n;
+}
+inputs = [5]
+t = 50
+Output: {"rejected":"Time Limit Exceeded","time":50}
+Explanation:
+const limited = timeLimit(fn, t)
+const start = performance.now()
+let result;
+try {
+ const res = await limited(...inputs)
+ result = {"resolved": res, "time": Math.floor(performance.now() - start)};
+} catch (err) {
+ result = {"rejected": err, "time": Math.floor(performance.now() - start)};
+}
+console.log(result) // Output
+
+The provided function is set to resolve after 100ms. However, the time limit is set to 50ms. It rejects at t=50ms because the time limit was reached.
+
+
+Example 2:
+ +Input:
+fn = async (n) => {
+ await new Promise(res => setTimeout(res, 100));
+ return n * n;
+}
+inputs = [5]
+t = 150
+Output: {"resolved":25,"time":100}
+Explanation:
+The function resolved 5 * 5 = 25 at t=100ms. The time limit is never reached.
+
+
+Example 3:
+ +Input:
+fn = async (a, b) => {
+ await new Promise(res => setTimeout(res, 120));
+ return a + b;
+}
+inputs = [5,10]
+t = 150
+Output: {"resolved":15,"time":120}
+Explanation:
+The function resolved 5 + 10 = 15 at t=120ms. The time limit is never reached.
+
+
+Example 4:
+ +Input:
+fn = async () => {
+ throw "Error";
+}
+inputs = []
+t = 1000
+Output: {"rejected":"Error","time":0}
+Explanation:
+The function immediately throws an error.
+
++
Constraints:
+ +0 <= inputs.length <= 100 <= t <= 1000fn returns a promiseThere is a directed weighted graph that consists of n nodes numbered from 0 to n - 1. The edges of the graph are initially represented by the given array edges where edges[i] = [fromi, toi, edgeCosti] meaning that there is an edge from fromi to toi with the cost edgeCosti.
Implement the Graph class:
Graph(int n, int[][] edges) initializes the object with n nodes and the given edges.addEdge(int[] edge) adds an edge to the list of edges where edge = [from, to, edgeCost]. It is guaranteed that there is no edge between the two nodes before adding this one.int shortestPath(int node1, int node2) returns the minimum cost of a path from node1 to node2. If no path exists, return -1. The cost of a path is the sum of the costs of the edges in the path.+
Example 1:
+
+Input +["Graph", "shortestPath", "shortestPath", "addEdge", "shortestPath"] +[[4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]], [3, 2], [0, 3], [[1, 3, 4]], [0, 3]] +Output +[null, 6, -1, null, 6] + +Explanation +Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]); +g.shortestPath(3, 2); // return 6. The shortest path from 3 to 2 in the first diagram above is 3 -> 0 -> 1 -> 2 with a total cost of 3 + 2 + 1 = 6. +g.shortestPath(0, 3); // return -1. There is no path from 0 to 3. +g.addEdge([1, 3, 4]); // We add an edge from node 1 to node 3, and we get the second diagram above. +g.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -> 1 -> 3 with a total cost of 2 + 4 = 6. ++ +
+
Constraints:
+ +1 <= n <= 1000 <= edges.length <= n * (n - 1)edges[i].length == edge.length == 30 <= fromi, toi, from, to, node1, node2 <= n - 11 <= edgeCosti, edgeCost <= 106100 calls will be made for addEdge.100 calls will be made for shortestPath.Write a generator function that returns a generator object which yields the fibonacci sequence.
+ +The fibonacci sequence is defined by the relation Xn = Xn-1 + Xn-2.
The first few numbers of the series are 0, 1, 1, 2, 3, 5, 8, 13.
+
Example 1:
+ +Input: callCount = 5 +Output: [0,1,1,2,3] +Explanation: +const gen = fibGenerator(); +gen.next().value; // 0 +gen.next().value; // 1 +gen.next().value; // 1 +gen.next().value; // 2 +gen.next().value; // 3 ++ +
Example 2:
+ +Input: callCount = 0 +Output: [] +Explanation: gen.next() is never called so nothing is outputted ++ +
+
Constraints:
+ +0 <= callCount <= 50Given a multi-dimensional array of integers, return a generator object which yields integers in the same order as inorder traversal.
+ +A multi-dimensional array is a recursive data structure that contains both integers and other multi-dimensional arrays.
+ +inorder traversal iterates over each array from left to right, yielding any integers it encounters or applying inorder traversal to any arrays it encounters.
+ ++
Example 1:
+ +Input: arr = [[[6]],[1,3],[]] +Output: [6,1,3] +Explanation: +const generator = inorderTraversal(arr); +generator.next().value; // 6 +generator.next().value; // 1 +generator.next().value; // 3 +generator.next().done; // true ++ +
Example 2:
+ +Input: arr = [] +Output: [] +Explanation: There are no integers so the generator doesn't yield anything. ++ +
+
Constraints:
+ +0 <= arr.flat().length <= 1050 <= arr.flat()[i] <= 105maxNestingDepth <= 105+Can you solve this without creating a new flattened version of the array?
Sometimes you have a long running task, and you may wish to cancel it before it completes. To help with this goal, write a function cancellable that accepts a generator object and returns an array of two values: a cancel function and a promise.
You may assume the generator function will only yield promises. It is your function's responsibility to pass the values resolved by the promise back to the generator. If the promise rejects, your function should throw that error back to the generator.
+ +If the cancel callback is called before the generator is done, your function should throw an error back to the generator. That error should be the string "Cancelled" (Not an Error object). If the error was caught, the returned promise should resolve with the next value that was yielded or returned. Otherwise, the promise should reject with the thrown error. No more code should be executed.
When the generator is done, the promise your function returned should resolve the value the generator returned. If, however, the generator throws an error, the returned promise should reject with the error.
+ +An example of how your code would be used:
+ +function* tasks() {
+ const val = yield new Promise(resolve => resolve(2 + 2));
+ yield new Promise(resolve => setTimeout(resolve, 100));
+ return val + 1; // calculation shouldn't be done.
+}
+const [cancel, promise] = cancellable(tasks());
+setTimeout(cancel, 50);
+promise.catch(console.log); // logs "Cancelled" at t=50ms
+
+
+If instead cancel() was not called or was called after t=100ms, the promise would have resolved 5.
+
Example 1:
+ +Input:
+generatorFunction = function*() {
+ return 42;
+}
+cancelledAt = 100
+Output: {"resolved": 42}
+Explanation:
+const generator = generatorFunction();
+const [cancel, promise] = cancellable(generator);
+setTimeout(cancel, 100);
+promise.then(console.log); // resolves 42 at t=0ms
+
+The generator immediately yields 42 and finishes. Because of that, the returned promise immediately resolves 42. Note that cancelling a finished generator does nothing.
+
+
+Example 2:
+ +Input:
+generatorFunction = function*() {
+ const msg = yield new Promise(res => res("Hello"));
+ throw `Error: ${msg}`;
+}
+cancelledAt = null
+Output: {"rejected": "Error: Hello"}
+Explanation:
+A promise is yielded. The function handles this by waiting for it to resolve and then passes the resolved value back to the generator. Then an error is thrown which has the effect of causing the promise to reject with the same thrown error.
+
+
+Example 3:
+ +Input:
+generatorFunction = function*() {
+ yield new Promise(res => setTimeout(res, 200));
+ return "Success";
+}
+cancelledAt = 100
+Output: {"rejected": "Cancelled"}
+Explanation:
+While the function is waiting for the yielded promise to resolve, cancel() is called. This causes an error message to be sent back to the generator. Since this error is uncaught, the returned promise rejected with this error.
+
+
+Example 4:
+ +Input:
+generatorFunction = function*() {
+ let result = 0;
+ yield new Promise(res => setTimeout(res, 100));
+ result += yield new Promise(res => res(1));
+ yield new Promise(res => setTimeout(res, 100));
+ result += yield new Promise(res => res(1));
+ return result;
+}
+cancelledAt = null
+Output: {"resolved": 2}
+Explanation:
+4 promises are yielded. Two of those promises have their values added to the result. After 200ms, the generator finishes with a value of 2, and that value is resolved by the returned promise.
+
+
+Example 5:
+ +Input:
+generatorFunction = function*() {
+ let result = 0;
+ try {
+ yield new Promise(res => setTimeout(res, 100));
+ result += yield new Promise(res => res(1));
+ yield new Promise(res => setTimeout(res, 100));
+ result += yield new Promise(res => res(1));
+ } catch(e) {
+ return result;
+ }
+ return result;
+}
+cancelledAt = 150
+Output: {"resolved": 1}
+Explanation:
+The first two yielded promises resolve and cause the result to increment. However, at t=150ms, the generator is cancelled. The error sent to the generator is caught and the result is returned and finally resolved by the returned promise.
+
+
+Example 6:
+ +Input:
+generatorFunction = function*() {
+ try {
+ yield new Promise((resolve, reject) => reject("Promise Rejected"));
+ } catch(e) {
+ let a = yield new Promise(resolve => resolve(2));
+ let b = yield new Promise(resolve => resolve(2));
+ return a + b;
+ };
+}
+cancelledAt = null
+Output: {"resolved": 4}
+Explanation:
+The first yielded promise immediately rejects. This error is caught. Because the generator hasn't been cancelled, execution continues as usual. It ends up resolving 2 + 2 = 4.
+
++
Constraints:
+ +cancelledAt == null or 0 <= cancelledAt <= 1000generatorFunction returns a generator objectWrite a function createCounter. It should accept an initial integer init. It should return an object with three functions.
The three functions are:
+ +increment() increases the current value by 1 and then returns it.decrement() reduces the current value by 1 and then returns it.reset() sets the current value to init and then returns it.+
Example 1:
+ +Input: init = 5, calls = ["increment","reset","decrement"] +Output: [6,5,4] +Explanation: +const counter = createCounter(5); +counter.increment(); // 6 +counter.reset(); // 5 +counter.decrement(); // 4 ++ +
Example 2:
+ +Input: init = 0, calls = ["increment","increment","decrement","reset","reset"] +Output: [1,2,1,0,0] +Explanation: +const counter = createCounter(0); +counter.increment(); // 1 +counter.increment(); // 2 +counter.decrement(); // 1 +counter.reset(); // 0 +counter.reset(); // 0 ++ +
+
Constraints:
+ +-1000 <= init <= 1000total calls not to exceed 1000Given a function fn, return a new function that is identical to the original function except that it ensures fn is called at most once.
fn.undefined.+
Example 1:
+ +Input: fn = (a,b,c) => (a + b + c), calls = [[1,2,3],[2,3,6]]
+Output: [{"calls":1,"value":6}]
+Explanation:
+const onceFn = once(fn);
+onceFn(1, 2, 3); // 6
+onceFn(2, 3, 6); // undefined, fn was not called
+
+
+Example 2:
+ +Input: fn = (a,b,c) => (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]]
+Output: [{"calls":1,"value":140}]
+Explanation:
+const onceFn = once(fn);
+onceFn(5, 7, 4); // 140
+onceFn(2, 3, 6); // undefined, fn was not called
+onceFn(4, 6, 8); // undefined, fn was not called
+
+
++
Constraints:
+ +1 <= calls.length <= 101 <= calls[i].length <= 1002 <= JSON.stringify(calls).length <= 1000createHelloWorld. It should return a new function that always returns "Hello World".
++
Example 1:
+ +Input: args = [] +Output: "Hello World" +Explanation: +const f = createHelloWorld(); +f(); // "Hello World" + +The function returned by createHelloWorld should always return "Hello World". ++ +
Example 2:
+ +Input: args = [{},null,42]
+Output: "Hello World"
+Explanation:
+const f = createHelloWorld();
+f({}, null, 42); // "Hello World"
+
+Any arguments could be passed to the function but it should still always return "Hello World".
+
+
++
Constraints:
+ +0 <= args.length <= 10Write a function that converts an array of objects arr into a matrix m.
arr is an array of objects or arrays. Each item in the array can be deeply nested with child arrays and child objects. It can also contain numbers, strings, booleans, and null values.
The first row m should be the column names. If there is no nesting, the column names are the unique keys within the objects. If there is nesting, the column names are the respective paths in the object separated by ".".
Each of the remaining rows corresponds to an object in arr. Each value in the matrix corresponds to a value in an object. If a given object doesn't contain a value for a given column, the cell should contain an empty string "".
The columns in the matrix should be in lexographically ascending order.
+ ++
Example 1:
+ +Input:
+arr = [
+ {"b": 1, "a": 2},
+ {"b": 3, "a": 4}
+]
+Output:
+[
+ ["a", "b"],
+ [2, 1],
+ [4, 3]
+]
+
+Explanation:
+There are two unique column names in the two objects: "a" and "b".
+"a" corresponds with [2, 4].
+"b" coresponds with [1, 3].
+
+
+Example 2:
+ +Input:
+arr = [
+ {"a": 1, "b": 2},
+ {"c": 3, "d": 4},
+ {}
+]
+Output:
+[
+ ["a", "b", "c", "d"],
+ [1, 2, "", ""],
+ ["", "", 3, 4],
+ ["", "", "", ""]
+]
+
+Explanation:
+There are 4 unique column names: "a", "b", "c", "d".
+The first object has values associated with "a" and "b".
+The second object has values associated with "c" and "d".
+The third object has no keys, so it is just a row of empty strings.
+
+
+Example 3:
+ +Input:
+arr = [
+ {"a": {"b": 1, "c": 2}},
+ {"a": {"b": 3, "d": 4}}
+]
+Output:
+[
+ ["a.b", "a.c", "a.d"],
+ [1, 2, ""],
+ [3, "", 4]
+]
+
+Explanation:
+In this example, the objects are nested. The keys represent the full path to each value separated by periods.
+There are three paths: "a.b", "a.c", "a.d".
+
+
+Example 4:
+ +Input:
+arr = [
+ [{"a": null}],
+ [{"b": true}],
+ [{"c": "x"}]
+]
+Output:
+[
+ ["0.a", "0.b", "0.c"],
+ [null, "", ""],
+ ["", true, ""],
+ ["", "", "x"]
+]
+
+Explanation:
+Arrays are also considered objects with their keys being their indices.
+Each array has one element so the keys are "0.a", "0.b", and "0.c".
+
+
+Example 5:
+ +Input:
+arr = [
+ {},
+ {},
+ {},
+]
+Output:
+[
+ [],
+ [],
+ [],
+ []
+]
+
+Explanation:
+There are no keys so every row is an empty array.
+
++
Constraints:
+ +1 <= arr.length <= 1000unique keys <= 1000Given a function fn and a time in milliseconds t, return a throttled version of that function.
A throttled function is first called without delay and then, for a time interval of t milliseconds, can't be executed but should store the latest function arguments provided to call fn with them after the end of the delay.
For instance, t = 50ms, and the function was called at 30ms, 40ms, and 60ms. The first function call would block calling functions for the following t milliseconds. The second function call would save arguments, and the third call arguments should overwrite currently stored arguments from the second call because the second and third calls are called before 80ms. Once the delay has passed, the throttled function should be called with the latest arguments provided during the delay period, and it should also create another delay period of 80ms + t.
The above diagram shows how throttle will transform events. Each rectangle represents 100ms and the throttle time is 400ms. Each color represents a different set of inputs.
+
Example 1:
+ +Input: t = 100, calls = [{"t":20,"inputs":[1]}]
+Output: [{"t":20,"inputs":[1]}]
+Explanation: The 1st call is always called without delay
+
+
+Example 2:
+ +Input: t = 50, calls = [{"t":50,"inputs":[1]},{"t":75,"inputs":[2]}]
+Output: [{"t":50,"inputs":[1]},{"t":100,"inputs":[2]}]
+Explanation:
+The 1st is called a function with arguments (1) without delay.
+The 2nd is called at 75ms, within the delay period because 50ms + 50ms = 100ms, so the next call can be reached at 100ms. Therefore, we save arguments from the 2nd call to use them at the callback of the 1st call.
+
+
+Example 3:
+ +Input: t = 70, calls = [{"t":50,"inputs":[1]},{"t":75,"inputs":[2]},{"t":90,"inputs":[8]},{"t": 140, "inputs":[5,7]},{"t": 300, "inputs": [9,4]}]
+Output: [{"t":50,"inputs":[1]},{"t":120,"inputs":[8]},{"t":190,"inputs":[5,7]},{"t":300,"inputs":[9,4]}]
+Explanation:
+The 1st is called a function with arguments (1) without delay.
+The 2nd is called at 75ms within the delay period because 50ms + 70ms = 120ms, so it should only save arguments.
+The 3rd is also called within the delay period, and because we need just the latest function arguments, we overwrite previous ones. After the delay period, we do a callback at 120ms with saved arguments. That callback makes another delay period of 120ms + 70ms = 190ms so that the next function can be called at 190ms.
+The 4th is called at 140ms in the delay period, so it should be called as a callback at 190ms. That will create another delay period of 190ms + 70ms = 260ms.
+The 5th is called at 300ms, but it is after 260ms, so it should be called immediately and should create another delay period of 300ms + 70ms = 370ms.
+
++
Constraints:
+ +0 <= t <= 10001 <= calls.length <= 100 <= calls[i].t <= 10000 <= calls[i].inputs[j], calls[i].inputs.length <= 10Given an array arr and a chunk size size, return a chunked array. A chunked array contains the original elements in arr, but consists of subarrays each of length size. The length of the last subarray may be less than size if arr.length is not evenly divisible by size.
You may assume the array is the output of JSON.parse. In other words, it is valid JSON.
Please solve it without using lodash's _.chunk function.
+
Example 1:
+ +Input: arr = [1,2,3,4,5], size = 1 +Output: [[1],[2],[3],[4],[5]] +Explanation: The arr has been split into subarrays each with 1 element. ++ +
Example 2:
+ +Input: arr = [1,9,6,3,2], size = 3 +Output: [[1,9,6],[3,2]] +Explanation: The arr has been split into subarrays with 3 elements. However, only two elements are left for the 2nd subarray. ++ +
Example 3:
+ +Input: arr = [8,5,3,2,6], size = 6 +Output: [[8,5,3,2,6]] +Explanation: Size is greater than arr.length thus all elements are in the first subarray. ++ +
Example 4:
+ +Input: arr = [], size = 1 +Output: [] +Explanation: There are no elements to be chunked so an empty array is returned.+ +
+
Constraints:
+ +arr is a valid JSON array2 <= JSON.stringify(arr).length <= 1051 <= size <= arr.length + 1You are given a 0-indexed array of strings details. Each element of details provides information about a given passenger compressed into a string of length 15. The system is such that:
Return the number of passengers who are strictly more than 60 years old.
+ ++
Example 1:
+ +Input: details = ["7868190130M7522","5303914400F9211","9273338290F4010"] +Output: 2 +Explanation: The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old. ++ +
Example 2:
+ +Input: details = ["1313579440F2036","2921522980M5644"] +Output: 0 +Explanation: None of the passengers are older than 60. ++ +
+
Constraints:
+ +1 <= details.length <= 100details[i].length == 15details[i] consists of digits from '0' to '9'.details[i][10] is either 'M' or 'F' or 'O'.Write a function that returns an infinite-method object.
+ +An infinite-method object is defined as an object that allows you to call any method and it will always return the name of the method.
+ +For example, if you execute obj.abc123(), it will return "abc123".
+
Example 1:
+ +Input: method = "abc123" +Output: "abc123" +Explanation: +const obj = createInfiniteObject(); +obj['abc123'](); // "abc123" +The returned string should always match the method name.+ +
Example 2:
+ +Input: method = ".-qw73n|^2It" +Output: ".-qw73n|^2It" +Explanation: The returned string should always match the method name.+ +
+
Constraints:
+ +0 <= method.length <= 1000Write a function that takes an object obj and returns a new immutable version of this object.
An immutable object is an object that can't be altered and will throw an error if any attempt is made to alter it.
+ +There are three types of error messages that can be produced from this new object.
+ +`Error Modifying: ${key}`.`Error Modifying Index: ${index}`.`Error Calling Method: ${methodName}`. You may assume the only methods that can mutate an array are ['pop', 'push', 'shift', 'unshift', 'splice', 'sort', 'reverse'].obj is a valid JSON object or array, meaning it is the output of JSON.parse().
Note that a string literal should be thrown, not an Error.
+
Example 1:
+ +Input:
+obj = {
+ "x": 5
+}
+fn = (obj) => {
+ obj.x = 5;
+ return obj.x;
+}
+Output: {"value": null, "error": "Error Modifying: x"}
+Explanation: Attempting to modify a key on an object resuts in a thrown error. Note that it doesn't matter that the value was set to the same value as it was before.
+
+
+Example 2:
+ +Input:
+obj = [1, 2, 3]
+fn = (arr) => {
+ arr[1] = {};
+ return arr[2];
+}
+Output: {"value": null, "error": "Error Modifying Index: 1"}
+Explanation: Attempting to modify an array results in a thrown error.
+
+
+Example 3:
+ +Input:
+obj = {
+ "arr": [1, 2, 3]
+}
+fn = (obj) => {
+ obj.arr.push(4);
+ return 42;
+}
+Output: { "value": null, "error": "Error Calling Method: push"}
+Explanation: Calling a method that can result in a mutation results in a thrown error.
+
+
+Example 4:
+ +Input:
+obj = {
+ "x": 2,
+ "y": 2
+}
+fn = (obj) => {
+ return Object.keys(obj);
+}
+Output: {"value": ["x", "y"], "error": null}
+Explanation: No mutations were attempted so the function returns as normal.
+
+
++
Constraints:
+ +2 <= JSON.stringify(obj).length <= 105Design an EventEmitter class. This interface is similar (but with some differences) to the one found in Node.js or the Event Target interface of the DOM. The EventEmitter should allow for subscribing to events and emitting them.
Your EventEmitter class should have the following two methods:
subscribe are referentially identical.subscribe method should also return an object with an unsubscribe method that enables the user to unsubscribe. When it is called, the callback should be removed from the list of subscriptions and undefined should be returned.+
Example 1:
+ +Input: actions = ["EventEmitter", "emit", "subscribe", "subscribe", "emit"], values = [[], ["firstEvent", "function cb1() { return 5; }"], ["firstEvent", "function cb1() { return 5; }"], ["firstEvent"]]
+Output: [[],["emitted",[]],["subscribed"],["subscribed"],["emitted",[5,6]]]
+Explanation:
+const emitter = new EventEmitter();
+emitter.emit("firstEvent"); // [], no callback are subscribed yet
+emitter.subscribe("firstEvent", function cb1() { return 5; });
+emitter.subscribe("firstEvent", function cb2() { return 6; });
+emitter.emit("firstEvent"); // [5, 6], returns the output of cb1 and cb2
+
+
+Example 2:
+ +Input: actions = ["EventEmitter", "subscribe", "emit", "emit"], values = [[], ["firstEvent", "function cb1(...args) { return args.join(','); }"], ["firstEvent", [1,2,3]], ["firstEvent", [3,4,6]]]
+Output: [[],["subscribed"],["emitted",["1,2,3"]],["emitted",["3,4,6"]]]
+Explanation: Note that the emit method should be able to accept an OPTIONAL array of arguments.
+
+const emitter = new EventEmitter();
+emitter.subscribe("firstEvent, function cb1(...args) { return args.join(','); });
+emitter.emit("firstEvent", [1, 2, 3]); // ["1,2,3"]
+emitter.emit("firstEvent", [3, 4, 6]); // ["3,4,6"]
+
+
+Example 3:
+ +Input: actions = ["EventEmitter", "subscribe", "emit", "unsubscribe", "emit"], values = [[], ["firstEvent", "(...args) => args.join(',')"], ["firstEvent", [1,2,3]], [0], ["firstEvent", [4,5,6]]]
+Output: [[],["subscribed"],["emitted",["1,2,3"]],["unsubscribed",0],["emitted",[]]]
+Explanation:
+const emitter = new EventEmitter();
+const sub = emitter.subscribe("firstEvent", (...args) => args.join(','));
+emitter.emit("firstEvent", [1, 2, 3]); // ["1,2,3"]
+sub.unsubscribe(); // undefined
+emitter.emit("firstEvent", [4, 5, 6]); // [], there are no subscriptions
+
+
+Example 4:
+ +Input: actions = ["EventEmitter", "subscribe", "subscribe", "unsubscribe", "emit"], values = [[], ["firstEvent", "x => x + 1"], ["firstEvent", "x => x + 2"], [0], ["firstEvent", [5]]]
+Output: [[],["subscribed"],["emitted",["1,2,3"]],["unsubscribed",0],["emitted",[7]]]
+Explanation:
+const emitter = new EventEmitter();
+const sub1 = emitter.subscribe("firstEvent", x => x + 1);
+const sub2 = emitter.subscribe("firstEvent", x => x + 2);
+sub1.unsubscribe(); // undefined
+emitter.emit("firstEvent", [5]); // [7]
+
++
Constraints:
+ +1 <= actions.length <= 10values.length === actions.lengthEventEmitter, emit, subscribe, and unsubscribe.EventEmitter action doesn't take any arguments.emit action takes between either 1 or 2 arguments. The first argument is the name of the event we want to emit, and the 2nd argument is passed to the callback functions.subscribe action takes 2 arguments, where the first one is the event name and the second is the callback function.unsubscribe action takes one argument, which is the 0-indexed order of the subscription made before.Create a class ArrayWrapper that accepts an array of integers in its constructor. This class should have two features:
+ operator, the resulting value is the sum of all the elements in both arrays.String() function is called on the instance, it will return a comma separated string surrounded by brackets. For example, [1,2,3].+
Example 1:
+ +Input: nums = [[1,2],[3,4]], operation = "Add" +Output: 10 +Explanation: +const obj1 = new ArrayWrapper([1,2]); +const obj2 = new ArrayWrapper([3,4]); +obj1 + obj2; // 10 ++ +
Example 2:
+ +Input: nums = [[23,98,42,70]], operation = "String" +Output: "[23,98,42,70]" +Explanation: +const obj = new ArrayWrapper([23,98,42,70]); +String(obj); // "[23,98,42,70]" ++ +
Example 3:
+ +Input: nums = [[],[]], operation = "Add" +Output: 0 +Explanation: +const obj1 = new ArrayWrapper([]); +const obj2 = new ArrayWrapper([]); +obj1 + obj2; // 0 ++ +
+
Constraints:
+ +0 <= nums.length <= 10000 <= nums[i] <= 1000Note: nums is the array passed to the constructorargumentsLength that returns the count of arguments passed to it.
++
Example 1:
+ +Input: argsArr = [5] +Output: 1 +Explanation: +argumentsLength(5); // 1 + +One value was passed to the function so it should return 1. ++ +
Example 2:
+ +Input: argsArr = [{}, null, "3"]
+Output: 3
+Explanation:
+argumentsLength({}, null, "3"); // 3
+
+Three values were passed to the function so it should return 3.
+
+
++
Constraints:
+ +argsArr is a valid JSON array0 <= argsArr.length <= 100Write a function expect that helps developers test their code. It should take in any value val and return an object with the following two functions.
toBe(val) accepts another value and returns true if the two values === each other. If they are not equal, it should throw an error "Not Equal".notToBe(val) accepts another value and returns true if the two values !== each other. If they are equal, it should throw an error "Equal".+
Example 1:
+ +Input: func = () => expect(5).toBe(5)
+Output: {"value": true}
+Explanation: 5 === 5 so this expression returns true.
+
+
+Example 2:
+ +Input: func = () => expect(5).toBe(null)
+Output: {"error": "Not Equal"}
+Explanation: 5 !== null so this expression throw the error "Not Equal".
+
+
+Example 3:
+ +Input: func = () => expect(5).notToBe(null)
+Output: {"value": true}
+Explanation: 5 !== null so this expression returns true.
+
+Given an object or array obj, return a compact object. A compact object is the same as the original object, except with keys containing falsy values removed. This operation applies to the object and any nested objects. Arrays are considered objects where the indices are keys. A value is considered falsy when Boolean(value) returns false.
You may assume the obj is the output of JSON.parse. In other words, it is valid JSON.
+
Example 1:
+ +Input: obj = [null, 0, false, 1] +Output: [1] +Explanation: All falsy values have been removed from the array. ++ +
Example 2:
+ +Input: obj = {"a": null, "b": [false, 1]}
+Output: {"b": [1]}
+Explanation: obj["a"] and obj["b"][0] had falsy values and were removed.
+
+Example 3:
+ +Input: obj = [null, 0, 5, [0], [false, 16]] +Output: [5, [], [16]] +Explanation: obj[0], obj[1], obj[3][0], and obj[4][0] were falsy and removed. ++ +
+
Constraints:
+ +obj is a valid JSON object2 <= JSON.stringify(obj).length <= 106You are given an integer array prices representing the prices of various chocolates in a store. You are also given a single integer money, which represents your initial amount of money.
You must buy exactly two chocolates in such a way that you still have some non-negative leftover money. You would like to minimize the sum of the prices of the two chocolates you buy.
+ +Return the amount of money you will have leftover after buying the two chocolates. If there is no way for you to buy two chocolates without ending up in debt, return money. Note that the leftover must be non-negative.
+
Example 1:
+ +Input: prices = [1,2,2], money = 3 +Output: 0 +Explanation: Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0. ++ +
Example 2:
+ +Input: prices = [3,2,3], money = 3 +Output: 3 +Explanation: You cannot buy 2 chocolates without going in debt, so we return 3. ++ +
+
Constraints:
+ +2 <= prices.length <= 501 <= prices[i] <= 1001 <= money <= 100You are given a 0-indexed string s and a dictionary of words dictionary. You have to break s into one or more non-overlapping substrings such that each substring is present in dictionary. There may be some extra characters in s which are not present in any of the substrings.
Return the minimum number of extra characters left over if you break up s optimally.
+
Example 1:
+ +Input: s = "leetscode", dictionary = ["leet","code","leetcode"] +Output: 1 +Explanation: We can break s in two substrings: "leet" from index 0 to 3 and "code" from index 5 to 8. There is only 1 unused character (at index 4), so we return 1. + ++ +
Example 2:
+ +Input: s = "sayhelloworld", dictionary = ["hello","world"] +Output: 3 +Explanation: We can break s in two substrings: "hello" from index 3 to 7 and "world" from index 8 to 12. The characters at indices 0, 1, 2 are not used in any substring and thus are considered as extra characters. Hence, we return 3. ++ +
+
Constraints:
+ +1 <= s.length <= 501 <= dictionary.length <= 501 <= dictionary[i].length <= 50dictionary[i] and s consists of only lowercase English lettersdictionary contains distinct wordsYou are given a 0-indexed integer array nums, and you are allowed to traverse between its indices. You can traverse between index i and index j, i != j, if and only if gcd(nums[i], nums[j]) > 1, where gcd is the greatest common divisor.
Your task is to determine if for every pair of indices i and j in nums, where i < j, there exists a sequence of traversals that can take us from i to j.
Return true if it is possible to traverse between all such pairs of indices, or false otherwise.
+
Example 1:
+ +Input: nums = [2,3,6] +Output: true +Explanation: In this example, there are 3 possible pairs of indices: (0, 1), (0, 2), and (1, 2). +To go from index 0 to index 1, we can use the sequence of traversals 0 -> 2 -> 1, where we move from index 0 to index 2 because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 > 1, and then move from index 2 to index 1 because gcd(nums[2], nums[1]) = gcd(6, 3) = 3 > 1. +To go from index 0 to index 2, we can just go directly because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 > 1. Likewise, to go from index 1 to index 2, we can just go directly because gcd(nums[1], nums[2]) = gcd(3, 6) = 3 > 1. ++ +
Example 2:
+ +Input: nums = [3,9,5] +Output: false +Explanation: No sequence of traversals can take us from index 0 to index 2 in this example. So, we return false. ++ +
Example 3:
+ +Input: nums = [4,3,12,8] +Output: true +Explanation: There are 6 possible pairs of indices to traverse between: (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), and (2, 3). A valid sequence of traversals exists for each pair, so we return true. ++ +
+
Constraints:
+ +1 <= nums.length <= 1051 <= nums[i] <= 105Given a function fn, an array or arguments args, and a timeout t in milliseconds, return a cancel function cancelFn.
After a delay of t, fn should be called with args passed as parameters unless cancelFn was called first. In that case, fn should never be called.
+
Example 1:
+ +Input: fn = (x) => x * 5, args = [2], t = 20
+Output: [{"time": 20, "returned": 10}]
+Explanation:
+const cancelTime = 50
+const cancel = cancellable((x) => x * 5, [2], 20); // fn(2) called at t=20ms
+setTimeout(cancel, cancelTime);
+
+The cancellation was scheduled to occur after a delay of cancelTime (50ms), which happened after the execution of fn(2) at 20ms.
+
+
+Example 2:
+ +Input: fn = (x) => x**2, args = [2], t = 100 +Output: [] +Explanation: +const cancelTime = 50 +const cancel = cancellable((x) => x**2, [2], 100); // fn(2) not called +setTimeout(cancel, cancelTime); + +The cancellation was scheduled to occur after a delay of cancelTime (50ms), which happened before the execution of fn(2) at 100ms, resulting in fn(2) never being called. ++ +
Example 3:
+ +Input: fn = (x1, x2) => x1 * x2, args = [2,4], t = 30
+Output: [{"time": 30, "returned": 8}]
+Explanation:
+const cancelTime = 100
+const cancel = cancellable((x1, x2) => x1 * x2, [2,4], 30); // fn(2,4) called at t=30ms
+setTimeout(cancel, cancelTime);
+
+The cancellation was scheduled to occur after a delay of cancelTime (100ms), which happened after the execution of fn(2,4) at 30ms.
+
+
++
Constraints:
+ +fn is a functionargs is a valid JSON array1 <= args.length <= 1020 <= t <= 100010 <= cancelT <= 1000Given an array of asynchronous functions functions, return a new promise promise. Each function in the array accepts no arguments and returns a promise.
promise resolves:
functions were resolved successfully. 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.promise rejects:
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 promises1 <= functions.length <= 10Given two arrays arr1 and arr2, return a new array joinedArray. All the objects in each of the two inputs arrays will contain an id field that has an integer value. joinedArray is an array formed by merging arr1 and arr2 based on their id key. The length of joinedArray should be the length of unique values of id. The returned array should be sorted in ascending order based on the id key.
If a given id exists in one array but not the other, the single object with that id should be included in the result array without modification.
If two objects share an id, their properties should be merged into a single object:
arr2 should override the value from arr1.+
Example 1:
+ +Input:
+arr1 = [
+ {"id": 1, "x": 1},
+ {"id": 2, "x": 9}
+],
+arr2 = [
+ {"id": 3, "x": 5}
+]
+Output:
+[
+ {"id": 1, "x": 1},
+ {"id": 2, "x": 9},
+ {"id": 3, "x": 5}
+]
+Explanation: There are no duplicate ids so arr1 is simply concatenated with arr2.
+
+
+Example 2:
+ +Input:
+arr1 = [
+ {"id": 1, "x": 2, "y": 3},
+ {"id": 2, "x": 3, "y": 6}
+],
+arr2 = [
+ {"id": 2, "x": 10, "y": 20},
+ {"id": 3, "x": 0, "y": 0}
+]
+Output:
+[
+ {"id": 1, "x": 2, "y": 3},
+ {"id": 2, "x": 10, "y": 20},
+ {"id": 3, "x": 0, "y": 0}
+]
+Explanation: The two objects with id=1 and id=3 are included in the result array without modifiction. The two objects with id=2 are merged together. The keys from arr2 override the values in arr1.
+
+
+Example 3:
+ +Input:
+arr1 = [
+ {"id": 1, "b": {"b": 94},"v": [4, 3], "y": 48}
+]
+arr2 = [
+ {"id": 1, "b": {"c": 84}, "v": [1, 3]}
+]
+Output: [
+ {"id": 1, "b": {"c": 84}, "v": [1, 3], "y": 48}
+]
+Explanation: The two objects with id=1 are merged together. For the keys "b" and "v" the values from arr2 are used. Since the key "y" only exists in arr1, that value is taken form arr1.
+
++
Constraints:
+ +arr1 and arr2 are valid JSON arraysEach object in arr1 and arr2 has a unique integer id key2 <= JSON.stringify(arr1).length <= 1062 <= JSON.stringify(arr2).length <= 106promise1 and promise2, return a new promise. promise1 and promise2 will both resolve with a number. The returned promise should resolve with the sum of the two numbers.
++
Example 1:
+ +Input: +promise1 = new Promise(resolve => setTimeout(() => resolve(2), 20)), +promise2 = new Promise(resolve => setTimeout(() => resolve(5), 60)) +Output: 7 +Explanation: The two input promises resolve with the values of 2 and 5 respectively. The returned promise should resolve with a value of 2 + 5 = 7. The time the returned promise resolves is not judged for this problem. ++ +
Example 2:
+ +Input: +promise1 = new Promise(resolve => setTimeout(() => resolve(10), 50)), +promise2 = new Promise(resolve => setTimeout(() => resolve(-12), 30)) +Output: -2 +Explanation: The two input promises resolve with the values of 10 and -12 respectively. The returned promise should resolve with a value of 10 + -12 = -2. ++ +
+
Constraints:
+ +promise1 and promise2 are promises that resolve with a numberGiven an array arr and a function fn, return a sorted array sortedArr. You can assume fn only returns numbers and those numbers determine the sort order of sortedArr. sortedArray must be sorted in ascending order by fn output.
You may assume that fn will never duplicate numbers for a given array.
+
Example 1:
+ +Input: arr = [5, 4, 1, 2, 3], fn = (x) => x +Output: [1, 2, 3, 4, 5] +Explanation: fn simply returns the number passed to it so the array is sorted in ascending order. ++ +
Example 2:
+ +Input: arr = [{"x": 1}, {"x": 0}, {"x": -1}], fn = (d) => d.x
+Output: [{"x": -1}, {"x": 0}, {"x": 1}]
+Explanation: fn returns the value for the "x" key. So the array is sorted based on that value.
+
+
+Example 3:
+ +Input: arr = [[3, 4], [5, 2], [10, 1]], fn = (x) => x[1] +Output: [[10, 1], [5, 2], [3, 4]] +Explanation: arr is sorted in ascending order by number at index=1. ++ +
+
Constraints:
+ +arr is a valid JSON arrayfn is a function that returns a number1 <= arr.length <= 5 * 105Given a function fn, an array of arguments args, and an interval time t, return a cancel function cancelFn. The function fn should be called with args immediately and then called again every t milliseconds until cancelFn is called.
+
Example 1:
+ +Input: fn = (x) => x * 2, args = [4], t = 20
+Output:
+[
+ {"time": 0, "returned": 8},
+ {"time": 20, "returned": 8},
+ {"time": 40, "returned": 8},
+ {"time": 60, "returned": 8},
+ {"time": 80, "returned": 8},
+ {"time": 100, "returned": 8}
+]
+Explanation:
+const cancelT = 110
+const cancel = cancellable(x => x * 2, [4], 20);
+setTimeout(cancel, cancelT);
+
+Every 20ms, fn(4) is called. Until t=110ms, then it is cancelled.
+1st fn call is at 0ms. fn(4) returns 8.
+2nd fn call is at 20ms. fn(4) returns 8.
+3rd fn call is at 40ms. fn(4) returns 8.
+4th fn call is at 60ms. fn(4) returns 8.
+5th fn call is at 80ms. fn(4) returns 8.
+6th fn call is at 100ms. fn(4) returns 8.
+Cancelled at 110ms
+
+
+Example 2:
+ +Input: fn = (x1, x2) => (x1 * x2), args = [2, 5], t = 25
+Output:
+[
+ {"time": 0, "returned": 10},
+ {"time": 25, "returned": 10},
+ {"time": 50, "returned": 10},
+ {"time": 75, "returned": 10},
+ {"time": 100, "returned": 10},
+ {"time": 125, "returned": 10}
+]
+Explanation:
+const cancelT = 140
+const cancel = cancellable((x1, x2) => (x1 * x2), [2, 5], 25);
+setTimeout(cancel, cancelT);
+
+Every 25ms, fn(2, 5) is called. Until t=140ms, then it is cancelled.
+1st fn call is at 0ms
+2nd fn call is at 25ms
+3rd fn call is at 50ms
+4th fn call is at 75ms
+5th fn call is at 100ms
+6th fn call is at 125ms
+Cancelled at 140ms
+
+
+Example 3:
+ +Input: fn = (x1, x2, x3) => (x1 + x2 + x3), args = [5, 1, 3], t = 50
+Output:
+[
+ {"time": 0, "returned": 9},
+ {"time": 50, "returned": 9},
+ {"time": 100, "returned": 9},
+ {"time": 150, "returned": 9}
+]
+Explanation:
+const cancelT = 180
+const cancel = cancellable((x1, x2, x3) => (x1 + x2 + x3), [5, 1, 3], 50);
+setTimeout(cancel, cancelT);
+
+Every 50ms, fn(5, 1, 3) is called. Until t=180ms, then it is cancelled.
+1st fn call is at 0ms
+2nd fn call is at 50ms
+3rd fn call is at 100ms
+4th fn call is at 150ms
+Cancelled at 180ms
+
+
++
Constraints:
+ +fn is a functionargs is a valid JSON array1 <= args.length <= 1020 <= t <= 100010 <= cancelT <= 1000Design a Calculator class. The class should provide the mathematical operations of addition, subtraction, multiplication, division, and exponentiation. It should also allow consecutive operations to be performed using method chaining. The Calculator class constructor should accept a number which serves as the initial value of result.
Your Calculator class should have the following methods:
add - This method adds the given number value to the result and returns the updated Calculator.subtract - This method subtracts the given number value from the result and returns the updated Calculator.multiply - This method multiplies the result by the given number value and returns the updated Calculator.divide - This method divides the result by the given number value and returns the updated Calculator. If the passed value is 0, an error "Division by zero is not allowed" should be thrown.power - This method raises the result to the power of the given number value and returns the updated Calculator.getResult - This method returns the result.Solutions within 10-5 of the actual result are considered correct.
+
Example 1:
+ +Input: actions = ["Calculator", "add", "subtract", "getResult"], values = [10, 5, 7] +Output: 8 +Explanation: +new Calculator(10).add(5).subtract(7).getResult() // 10 + 5 - 7 = 8 ++ +
Example 2:
+ +Input: actions = ["Calculator", "multiply", "power", "getResult"], values = [2, 5, 2] +Output: 100 +Explanation: +new Calculator(2).multiply(5).power(2).getResult() // (2 * 5) ^ 2 = 100 ++ +
Example 3:
+ +Input: actions = ["Calculator", "divide", "getResult"], values = [20, 0] +Output: "Division by zero is not allowed" +Explanation: +new Calculator(20).divide(0).getResult() // 20 / 0 + +The error should be thrown because we cannot divide by zero. ++ +
+
Constraints:
+ +2 <= actions.length <= 2 * 1041 <= values.length <= 2 * 104 - 1actions[i] is one of "Calculator", "add", "subtract", "multiply", "divide", "power", and "getResult"Last action is always "getResult"values is a JSON array of numbersGiven an object or an array, return if it is empty.
+ +You may assume the object or array is the output of JSON.parse.
+
Example 1:
+ +Input: obj = {"x": 5, "y": 42}
+Output: false
+Explanation: The object has 2 key-value pairs so it is not empty.
+
+
+Example 2:
+ +Input: obj = {}
+Output: true
+Explanation: The object doesn't have any key-value pairs so it is empty.
+
+
+Example 3:
+ +Input: obj = [null, false, 0] +Output: false +Explanation: The array has 3 elements so it is not empty. ++ +
+
Constraints:
+ +2 <= JSON.stringify(obj).length <= 105+Can you solve it in O(1) time?
You are given two 0-indexed integer arrays, cost and time, of size n representing the costs and the time taken to paint n different walls respectively. There are two painters available:
ith wall in time[i] units of time and takes cost[i] units of money.1 unit of time at a cost of 0. But the free painter can only be used if the paid painter is already occupied.Return the minimum amount of money required to paint the n walls.
+
Example 1:
+ +Input: cost = [1,2,3,2], time = [1,2,3,2] +Output: 3 +Explanation: The walls at index 0 and 1 will be painted by the paid painter, and it will take 3 units of time; meanwhile, the free painter will paint the walls at index 2 and 3, free of cost in 2 units of time. Thus, the total cost is 1 + 2 = 3. ++ +
Example 2:
+ +Input: cost = [2,3,4,2], time = [1,1,1,1] +Output: 4 +Explanation: The walls at index 0 and 3 will be painted by the paid painter, and it will take 2 units of time; meanwhile, the free painter will paint the walls at index 1 and 2, free of cost in 2 units of time. Thus, the total cost is 2 + 2 = 4. ++ +
+
Constraints:
+ +1 <= cost.length <= 500cost.length == time.length1 <= cost[i] <= 1061 <= time[i] <= 500You are given a string s consisting only of lowercase English letters. We call a substring special if it contains no character which has occurred at least twice (in other words, it does not contain a repeating character). Your task is to count the number of special substrings. For example, in the string "pop", the substring "po" is a special substring, however, "pop" is not special (since 'p' has occurred twice).
Return the number of special substrings.
+ +A substring is a contiguous sequence of characters within a string. For example, "abc" is a substring of "abcd", but "acd" is not.
+
Example 1:
+ +Input: s = "abcd" +Output: 10 +Explanation: Since each character occurs once, every substring is a special substring. We have 4 substrings of length one, 3 of length two, 2 of length three, and 1 substring of length four. So overall there are 4 + 3 + 2 + 1 = 10 special substrings. ++ +
Example 2:
+ +Input: s = "ooo" +Output: 3 +Explanation: Any substring with a length of at least two contains a repeating character. So we have to count the number of substrings of length one, which is 3. ++ +
Example 3:
+ +Input: s = "abab" +Output: 7 +Explanation: Special substrings are as follows (sorted by their start positions): +Special substrings of length 1: "a", "b", "a", "b" +Special substrings of length 2: "ab", "ba", "ab" +And it can be shown that there are no special substrings with a length of at least three. So the answer would be 4 + 3 = 7.+ +
+
Constraints:
+ +1 <= s.length <= 105s consists of lowercase English lettersThere are n 1-indexed robots, each having a position on a line, health, and movement direction.
You are given 0-indexed integer arrays positions, healths, and a string directions (directions[i] is either 'L' for left or 'R' for right). All integers in positions are unique.
All robots start moving on the line simultaneously at the same speed in their given directions. If two robots ever share the same position while moving, they will collide.
+ +If two robots collide, the robot with lower health is removed from the line, and the health of the other robot decreases by one. The surviving robot continues in the same direction it was going. If both robots have the same health, they are both removed from the line.
+ +Your task is to determine the health of the robots that survive the collisions, in the same order that the robots were given, i.e. final heath of robot 1 (if survived), final health of robot 2 (if survived), and so on. If there are no survivors, return an empty array.
+ +Return an array containing the health of the remaining robots (in the order they were given in the input), after no further collisions can occur.
+ +Note: The positions may be unsorted.
+ ++
Example 1:
+ +
Input: positions = [5,4,3,2,1], healths = [2,17,9,15,10], directions = "RRRRR" +Output: [2,17,9,15,10] +Explanation: No collision occurs in this example, since all robots are moving in the same direction. So, the health of the robots in order from the first robot is returned, [2, 17, 9, 15, 10]. ++ +
Example 2:
+ +
Input: positions = [3,5,2,6], healths = [10,10,15,12], directions = "RLRL" +Output: [14] +Explanation: There are 2 collisions in this example. Firstly, robot 1 and robot 2 will collide, and since both have the same health, they will be removed from the line. Next, robot 3 and robot 4 will collide and since robot 4's health is smaller, it gets removed, and robot 3's health becomes 15 - 1 = 14. Only robot 3 remains, so we return [14]. ++ +
Example 3:
+ +
Input: positions = [1,2,5,6], healths = [10,10,11,11], directions = "RLRL" +Output: [] +Explanation: Robot 1 and robot 2 will collide and since both have the same health, they are both removed. Robot 3 and 4 will collide and since both have the same health, they are both removed. So, we return an empty array, [].+ +
+
Constraints:
+ +1 <= positions.length == healths.length == directions.length == n <= 1051 <= positions[i], healths[i] <= 109directions[i] == 'L' or directions[i] == 'R'positions are distinctYou are given a 0-indexed integer array nums. A subarray of nums is called continuous if:
i, i + 1, ..., j be the indices in the subarray. Then, for each pair of indices i <= i1, i2 <= j, 0 <= |nums[i1] - nums[i2]| <= 2.Return the total number of continuous subarrays.
+ +A subarray is a contiguous non-empty sequence of elements within an array.
+ ++
Example 1:
+ +Input: nums = [5,4,2,4] +Output: 8 +Explanation: +Continuous subarray of size 1: [5], [4], [2], [4]. +Continuous subarray of size 2: [5,4], [4,2], [2,4]. +Continuous subarray of size 3: [4,2,4]. +Thereare no subarrys of size 4. +Total continuous subarrays = 4 + 3 + 1 = 8. +It can be shown that there are no more continuous subarrays. ++ +
+ +
Example 2:
+ +Input: nums = [1,2,3] +Output: 6 +Explanation: +Continuous subarray of size 1: [1], [2], [3]. +Continuous subarray of size 2: [1,2], [2,3]. +Continuous subarray of size 3: [1,2,3]. +Total continuous subarrays = 3 + 2 + 1 = 6. ++ +
+
Constraints:
+ +1 <= nums.length <= 1051 <= nums[i] <= 109You are given a 1-indexed integer array nums of length n.
An element nums[i] of nums is called special if i divides n, i.e. n % i == 0.
Return the sum of the squares of all special elements of nums.
+
Example 1:
+ +Input: nums = [1,2,3,4] +Output: 21 +Explanation: There are exactly 3 special elements in nums: nums[1] since 1 divides 4, nums[2] since 2 divides 4, and nums[4] since 4 divides 4. +Hence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[4] * nums[4] = 1 * 1 + 2 * 2 + 4 * 4 = 21. ++ +
Example 2:
+ +Input: nums = [2,7,1,19,18,3] +Output: 63 +Explanation: There are exactly 4 special elements in nums: nums[1] since 1 divides 6, nums[2] since 2 divides 6, nums[3] since 3 divides 6, and nums[6] since 6 divides 6. +Hence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[3] * nums[3] + nums[6] * nums[6] = 2 * 2 + 7 * 7 + 1 * 1 + 3 * 3 = 63. ++ +
+
Constraints:
+ +1 <= nums.length == n <= 501 <= nums[i] <= 50You are given an integer array nums. We consider an array good if it is a permutation of an array base[n].
base[n] = [1, 2, ..., n - 1, n, n] (in other words, it is an array of length n + 1 which contains 1 to n - 1 exactly once, plus two occurrences of n). For example, base[1] = [1, 1] and base[3] = [1, 2, 3, 3].
Return true if the given array is good, otherwise return false.
Note: A permutation of integers represents an arrangement of these numbers.
+ ++
Example 1:
+ +Input: nums = [2, 1, 3] +Output: false +Explanation: Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. However, base[3] has four elements but array nums has three. Therefore, it can not be a permutation of base[3] = [1, 2, 3, 3]. So the answer is false. ++ +
Example 2:
+ +Input: nums = [1, 3, 3, 2] +Output: true +Explanation: Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. It can be seen that nums is a permutation of base[3] = [1, 2, 3, 3] (by swapping the second and fourth elements in nums, we reach base[3]). Therefore, the answer is true.+ +
Example 3:
+ +Input: nums = [1, 1] +Output: true +Explanation: Since the maximum element of the array is 1, the only candidate n for which this array could be a permutation of base[n], is n = 1. It can be seen that nums is a permutation of base[1] = [1, 1]. Therefore, the answer is true.+ +
Example 4:
+ +Input: nums = [3, 4, 4, 1, 2, 1] +Output: false +Explanation: Since the maximum element of the array is 4, the only candidate n for which this array could be a permutation of base[n], is n = 4. However, base[4] has five elements but array nums has six. Therefore, it can not be a permutation of base[4] = [1, 2, 3, 4, 4]. So the answer is false. ++ +
+
Constraints:
+ +1 <= nums.length <= 1001 <= num[i] <= 200Given a 0-indexed string s, permute s to get a new string t such that:
i with 0 <= i < s.length such that s[i] is a consonant, then t[i] = s[i].i, j with 0 <= i < j < s.length such that s[i] and s[j] are vowels, then t[i] must not have a higher ASCII value than t[j].Return the resulting string.
+ +The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels.
+
Example 1:
+ +Input: s = "lEetcOde" +Output: "lEOtcede" +Explanation: 'E', 'O', and 'e' are the vowels in s; 'l', 't', 'c', and 'd' are all consonants. The vowels are sorted according to their ASCII values, and the consonants remain in the same places. ++ +
Example 2:
+ +Input: s = "lYmpH" +Output: "lYmpH" +Explanation: There are no vowels in s (all characters in s are consonants), so we return "lYmpH". ++ +
+
Constraints:
+ +1 <= s.length <= 105s consists only of letters of the English alphabet in uppercase and lowercase.Given an array of strings words and a character separator, split each string in words by separator.
Return an array of strings containing the new strings formed after the splits, excluding empty strings.
+ +Notes
+ +separator is used to determine where the split should occur, but it is not included as part of the resulting strings.+
Example 1:
+ +Input: words = ["one.two.three","four.five","six"], separator = "." +Output: ["one","two","three","four","five","six"] +Explanation: In this example we split as follows: + +"one.two.three" splits into "one", "two", "three" +"four.five" splits into "four", "five" +"six" splits into "six" + +Hence, the resulting array is ["one","two","three","four","five","six"].+ +
Example 2:
+ +Input: words = ["$easy$","$problem$"], separator = "$" +Output: ["easy","problem"] +Explanation: In this example we split as follows: + +"$easy$" splits into "easy" (excluding empty strings) +"$problem$" splits into "problem" (excluding empty strings) + +Hence, the resulting array is ["easy","problem"]. ++ +
Example 3:
+ +Input: words = ["|||"], separator = "|" +Output: [] +Explanation: In this example the resulting split of "|||" will contain only empty strings, so we return an empty array [].+ +
+
Constraints:
+ +1 <= words.length <= 1001 <= words[i].length <= 20words[i] are either lowercase English letters or characters from the string ".,|$#@" (excluding the quotes)separator is a character from the string ".,|$#@" (excluding the quotes)You are given a 0-indexed array nums consisting of positive integers.
You can do the following operation on the array any number of times:
+ +i such that 0 <= i < nums.length - 1 and nums[i] <= nums[i + 1]. Replace the element nums[i + 1] with nums[i] + nums[i + 1] and delete the element nums[i] from the array.Return the value of the largest element that you can possibly obtain in the final array.
+ ++
Example 1:
+ +Input: nums = [2,3,7,9,3] +Output: 21 +Explanation: We can apply the following operations on the array: +- Choose i = 0. The resulting array will be nums = [5,7,9,3]. +- Choose i = 1. The resulting array will be nums = [5,16,3]. +- Choose i = 0. The resulting array will be nums = [21,3]. +The largest element in the final array is 21. It can be shown that we cannot obtain a larger element. ++ +
Example 2:
+ +Input: nums = [5,3,3] +Output: 11 +Explanation: We can do the following operations on the array: +- Choose i = 1. The resulting array will be nums = [5,6]. +- Choose i = 0. The resulting array will be nums = [11]. +There is only one element in the final array, which is 11. ++ +
+
Constraints:
+ +1 <= nums.length <= 1051 <= nums[i] <= 106There are n employees in a company, numbered from 0 to n - 1. Each employee i has worked for hours[i] hours in the company.
The company requires each employee to work for at least target hours.
You are given a 0-indexed array of non-negative integers hours of length n and a non-negative integer target.
Return the integer denoting the number of employees who worked at least target hours.
+
Example 1:
+ +Input: hours = [0,1,2,3,4], target = 2 +Output: 3 +Explanation: The company wants each employee to work for at least 2 hours. +- Employee 0 worked for 0 hours and didn't meet the target. +- Employee 1 worked for 1 hours and didn't meet the target. +- Employee 2 worked for 2 hours and met the target. +- Employee 3 worked for 3 hours and met the target. +- Employee 4 worked for 4 hours and met the target. +There are 3 employees who met the target. ++ +
Example 2:
+ +Input: hours = [5,1,4,2,2], target = 6 +Output: 0 +Explanation: The company wants each employee to work for at least 6 hours. +There are 0 employees who met the target. ++ +
+
Constraints:
+ +1 <= n == hours.length <= 500 <= hours[i], target <= 105We know that 4 and 7 are lucky digits. Also, a number is called lucky if it contains only lucky digits.
You are given an integer k, return the kth lucky number represented as a string.
+
Example 1:
+ +Input: k = 4 +Output: "47" +Explanation: The first lucky number is 4, the second one is 7, the third one is 44 and the fourth one is 47. ++ +
Example 2:
+ +Input: k = 10 +Output: "477" +Explanation: Here are lucky numbers sorted in increasing order: +4, 7, 44, 47, 74, 77, 444, 447, 474, 477. So the 10th lucky number is 477.+ +
Example 3:
+ +Input: k = 1000 +Output: "777747447" +Explanation: It can be shown that the 1000th lucky number is 777747447. ++ +
+
Constraints:
+ +1 <= k <= 109Initially, 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.
At the store where you will make the purchase, the purchase amount is rounded to the nearest multiple of 10. In other words, you pay a non-negative amount, roundedAmount, such that roundedAmount is a multiple of 10 and abs(roundedAmount - purchaseAmount) is minimized.
If there is more than one nearest multiple of 10, the largest multiple is chosen.
Return an integer denoting your account balance after making a purchase worth purchaseAmount dollars from the store.
Note: 0 is considered to be a multiple of 10 in this problem.
+
Example 1:
+ +Input: purchaseAmount = 9 +Output: 90 +Explanation: In this example, the nearest multiple of 10 to 9 is 10. Hence, your account balance becomes 100 - 10 = 90. ++ +
Example 2:
+ +Input: purchaseAmount = 15 +Output: 80 +Explanation: In this example, there are two nearest multiples of 10 to 15: 10 and 20. So, the larger multiple, 20, is chosen. +Hence, your account balance becomes 100 - 20 = 80. ++ +
+
Constraints:
+ +0 <= purchaseAmount <= 100Given the head of a linked list head, in which each node contains an integer value.
Between every pair of adjacent nodes, insert a new node with a value equal to the greatest common divisor of them.
+ +Return the linked list after insertion.
+ +The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.
+ ++
Example 1:
+
+Input: head = [18,6,10,3] +Output: [18,6,6,2,10,1,3] +Explanation: The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the new nodes (nodes in blue are the inserted nodes). +- We insert the greatest common divisor of 18 and 6 = 6 between the 1st and the 2nd nodes. +- We insert the greatest common divisor of 6 and 10 = 2 between the 2nd and the 3rd nodes. +- We insert the greatest common divisor of 10 and 3 = 1 between the 3rd and the 4th nodes. +There are no more adjacent nodes, so we return the linked list. ++ +
Example 2:
+
+Input: head = [7] +Output: [7] +Explanation: The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the new nodes. +There are no pairs of adjacent nodes, so we return the initial linked list. ++ +
+
Constraints:
+ +[1, 5000].1 <= Node.val <= 1000Your laptop keyboard is faulty, and whenever you type a character 'i' on it, it reverses the string that you have written. Typing other characters works as expected.
You are given a 0-indexed string s, and you type each character of s using your faulty keyboard.
Return the final string that will be present on your laptop screen.
+ ++
Example 1:
+ +Input: s = "string" +Output: "rtsng" +Explanation: +After typing first character, the text on the screen is "s". +After the second character, the text is "st". +After the third character, the text is "str". +Since the fourth character is an 'i', the text gets reversed and becomes "rts". +After the fifth character, the text is "rtsn". +After the sixth character, the text is "rtsng". +Therefore, we return "rtsng". ++ +
Example 2:
+ +Input: s = "poiinter" +Output: "ponter" +Explanation: +After the first character, the text on the screen is "p". +After the second character, the text is "po". +Since the third character you type is an 'i', the text gets reversed and becomes "op". +Since the fourth character you type is an 'i', the text gets reversed and becomes "po". +After the fifth character, the text is "pon". +After the sixth character, the text is "pont". +After the seventh character, the text is "ponte". +After the eighth character, the text is "ponter". +Therefore, we return "ponter".+ +
+
Constraints:
+ +1 <= s.length <= 100s consists of lowercase English letters.s[0] != 'i'You are given an array nums of length n and an integer m. You need to determine if it is possible to split the array into n non-empty arrays by performing a series of steps.
In each step, you can select an existing array (which may be the result of previous steps) with a length of at least two and split it into two subarrays, if, for each resulting subarray, at least one of the following holds:
+ +m.Return true if you can split the given array into n arrays, otherwise return false.
Note: A subarray is a contiguous non-empty sequence of elements within an array.
+ ++
Example 1:
+ +Input: nums = [2, 2, 1], m = 4 +Output: true +Explanation: We can split the array into [2, 2] and [1] in the first step. Then, in the second step, we can split [2, 2] into [2] and [2]. As a result, the answer is true.+ +
Example 2:
+ +Input: nums = [2, 1, 3], m = 5 +Output: false +Explanation: We can try splitting the array in two different ways: the first way is to have [2, 1] and [3], and the second way is to have [2] and [1, 3]. However, both of these ways are not valid. So, the answer is false.+ +
Example 3:
+ +Input: nums = [2, 3, 3, 2, 3], m = 6 +Output: true +Explanation: We can split the array into [2, 3, 3, 2] and [3] in the first step. Then, in the second step, we can split [2, 3, 3, 2] into [2, 3, 3] and [2]. Then, in the third step, we can split [2, 3, 3] into [2] and [3, 3]. And in the last step we can split [3, 3] into [3] and [3]. As a result, the answer is true. ++ +
+
Constraints:
+ +1 <= n == nums.length <= 1001 <= nums[i] <= 1001 <= m <= 200You are given a 0-indexed 2D matrix grid of size n x n, where (r, c) represents:
grid[r][c] = 1grid[r][c] = 0You 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 <= 400grid[i].length == ngrid[i][j] is either 0 or 1.grid.You are given the head of a non-empty linked list representing a non-negative integer without leading zeroes.
Return the head of the linked list after doubling it.
+
Example 1:
+
+Input: head = [1,8,9] +Output: [3,7,8] +Explanation: The figure above corresponds to the given linked list which represents the number 189. Hence, the returned linked list represents the number 189 * 2 = 378. ++ +
Example 2:
+
+Input: head = [9,9,9] +Output: [1,9,9,8] +Explanation: The figure above corresponds to the given linked list which represents the number 999. Hence, the returned linked list reprersents the number 999 * 2 = 1998. ++ +
+
Constraints:
+ +[1, 104]0 <= Node.val <= 90 itself.nums of length n and an integer target, return the number of pairs (i, j) where 0 <= i < j < n and nums[i] + nums[j] < target.
++
Example 1:
+ +Input: nums = [-1,1,2,3,1], target = 2 +Output: 3 +Explanation: There are 3 pairs of indices that satisfy the conditions in the statement: +- (0, 1) since 0 < 1 and nums[0] + nums[1] = 0 < target +- (0, 2) since 0 < 2 and nums[0] + nums[2] = 1 < target +- (0, 4) since 0 < 4 and nums[0] + nums[4] = 0 < target +Note that (0, 3) is not counted since nums[0] + nums[3] is not strictly less than the target. ++ +
Example 2:
+ +Input: nums = [-6,2,5,-2,-7,-1,3], target = -2 +Output: 10 +Explanation: There are 10 pairs of indices that satisfy the conditions in the statement: +- (0, 1) since 0 < 1 and nums[0] + nums[1] = -4 < target +- (0, 3) since 0 < 3 and nums[0] + nums[3] = -8 < target +- (0, 4) since 0 < 4 and nums[0] + nums[4] = -13 < target +- (0, 5) since 0 < 5 and nums[0] + nums[5] = -7 < target +- (0, 6) since 0 < 6 and nums[0] + nums[6] = -3 < target +- (1, 4) since 1 < 4 and nums[1] + nums[4] = -5 < target +- (3, 4) since 3 < 4 and nums[3] + nums[4] = -9 < target +- (3, 5) since 3 < 5 and nums[3] + nums[5] = -3 < target +- (4, 5) since 4 < 5 and nums[4] + nums[5] = -8 < target +- (4, 6) since 4 < 6 and nums[4] + nums[6] = -4 < target ++ +
+
Constraints:
+ +1 <= nums.length == n <= 50-50 <= nums[i], target <= 50You are given two 0-indexed strings str1 and str2.
In an operation, you select a set of indices in str1, and for each index i in the set, increment str1[i] to the next character cyclically. That is 'a' becomes 'b', 'b' becomes 'c', and so on, and 'z' becomes 'a'.
Return true if it is possible to make str2 a subsequence of str1 by performing the operation at most once, and false otherwise.
Note: A subsequence of a string is a new string that is formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.
+ ++
Example 1:
+ +Input: str1 = "abc", str2 = "ad" +Output: true +Explanation: Select index 2 in str1. +Increment str1[2] to become 'd'. +Hence, str1 becomes "abd" and str2 is now a subsequence. Therefore, true is returned.+ +
Example 2:
+ +Input: str1 = "zc", str2 = "ad" +Output: true +Explanation: Select indices 0 and 1 in str1. +Increment str1[0] to become 'a'. +Increment str1[1] to become 'd'. +Hence, str1 becomes "ad" and str2 is now a subsequence. Therefore, true is returned.+ +
Example 3:
+ +Input: str1 = "ab", str2 = "d" +Output: false +Explanation: In this example, it can be shown that it is impossible to make str2 a subsequence of str1 using the operation at most once. +Therefore, false is returned.+ +
+
Constraints:
+ +1 <= str1.length <= 1051 <= str2.length <= 105str1 and str2 consist of only lowercase English letters.You are given a string moves of length n consisting only of characters 'L', 'R', and '_'. The string represents your movement on a number line starting from the origin 0.
In the ith move, you can choose one of the following directions:
moves[i] = 'L' or moves[i] = '_'moves[i] = 'R' or moves[i] = '_'Return the distance from the origin of the furthest point you can get to after n moves.
+
Example 1:
+ +Input: moves = "L_RL__R" +Output: 3 +Explanation: The furthest point we can reach from the origin 0 is point -3 through the following sequence of moves "LLRLLLR". ++ +
Example 2:
+ +Input: moves = "_R__LL_" +Output: 5 +Explanation: The furthest point we can reach from the origin 0 is point -5 through the following sequence of moves "LRLLLLL". ++ +
Example 3:
+ +Input: moves = "_______" +Output: 7 +Explanation: The furthest point we can reach from the origin 0 is point 7 through the following sequence of moves "RRRRRRR". ++ +
+
Constraints:
+ +1 <= moves.length == n <= 50moves consists only of characters 'L', 'R' and '_'.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.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.
+ ++
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 <= 1051 <= target <= 105You are given four integers sx, sy, fx, fy, and a non-negative integer t.
In an infinite 2D grid, you start at the cell (sx, sy). Each second, you must move to any of its adjacent cells.
Return true if you can reach cell (fx, fy) after exactly t seconds, or false otherwise.
A cell's adjacent cells are the 8 cells around it that share at least one corner with it. You can visit the same cell several times.
+ ++
Example 1:
+Input: sx = 2, sy = 4, fx = 7, fy = 7, t = 6 +Output: true +Explanation: Starting at cell (2, 4), we can reach cell (7, 7) in exactly 6 seconds by going through the cells depicted in the picture above. ++ +
Example 2:
+Input: sx = 3, sy = 1, fx = 7, fy = 3, t = 3 +Output: false +Explanation: Starting at cell (3, 1), it takes at least 4 seconds to reach cell (7, 3) by going through the cells depicted in the picture above. Hence, we cannot reach cell (7, 3) at the third second. ++ +
+
Constraints:
+ +1 <= sx, sy, fx, fy <= 1090 <= t <= 109You are given a binary string s that contains at least one '1'.
You have to rearrange the bits in such a way that the resulting binary number is the maximum odd binary number that can be created from this combination.
+ +Return a string representing the maximum odd binary number that can be created from the given combination.
+ +Note that the resulting string can have leading zeros.
+ ++
Example 1:
+ +Input: s = "010" +Output: "001" +Explanation: Because there is just one '1', it must be in the last position. So the answer is "001". ++ +
Example 2:
+ +Input: s = "0101" +Output: "1001" +Explanation: One of the '1's must be in the last position. The maximum number that can be made with the remaining digits is "100". So the answer is "1001". ++ +
+
Constraints:
+ +1 <= s.length <= 100s consists only of '0' and '1'.s contains at least one '1'.You are given a 0-indexed array nums consisting of positive integers.
There are two types of operations that you can apply on the array any number of times:
+ +Return the minimum number of operations required to make the array empty, or -1 if it is not possible.
+
Example 1:
+ +Input: nums = [2,3,3,2,2,4,2,3,4] +Output: 4 +Explanation: We can apply the following operations to make the array empty: +- Apply the first operation on the elements at indices 0 and 3. The resulting array is nums = [3,3,2,4,2,3,4]. +- Apply the first operation on the elements at indices 2 and 4. The resulting array is nums = [3,3,4,3,4]. +- Apply the second operation on the elements at indices 0, 1, and 3. The resulting array is nums = [4,4]. +- Apply the first operation on the elements at indices 0 and 1. The resulting array is nums = []. +It can be shown that we cannot make the array empty in less than 4 operations. ++ +
Example 2:
+ +Input: nums = [2,1,2,2,3,3] +Output: -1 +Explanation: It is impossible to empty the array. ++ +
+
Constraints:
+ +2 <= nums.length <= 1051 <= nums[i] <= 106You are given an integer array nums and an integer k.
The frequency of an element x is the number of times it occurs in an array.
An array is called good if the frequency of each element in this array is less than or equal to k.
Return the length of the longest good subarray of nums.
A subarray is a contiguous non-empty sequence of elements within an array.
+ ++
Example 1:
+ +Input: nums = [1,2,3,1,2,3,1,2], k = 2 +Output: 6 +Explanation: The longest possible good subarray is [1,2,3,1,2,3] since the values 1, 2, and 3 occur at most twice in this subarray. Note that the subarrays [2,3,1,2,3,1] and [3,1,2,3,1,2] are also good. +It can be shown that there are no good subarrays with length more than 6. ++ +
Example 2:
+ +Input: nums = [1,2,1,2,1,2,1,2], k = 1 +Output: 2 +Explanation: The longest possible good subarray is [1,2] since the values 1 and 2 occur at most once in this subarray. Note that the subarray [2,1] is also good. +It can be shown that there are no good subarrays with length more than 2. ++ +
Example 3:
+ +Input: nums = [5,5,5,5,5,5,5], k = 4 +Output: 4 +Explanation: The longest possible good subarray is [5,5,5,5] since the value 5 occurs 4 times in this subarray. +It can be shown that there are no good subarrays with length more than 4. ++ +
+
Constraints:
+ +1 <= nums.length <= 1051 <= nums[i] <= 1091 <= k <= nums.lengthYou are given an integer array nums and a positive integer k.
Return the number of subarrays where the maximum element of nums appears at least k times in that subarray.
A subarray is a contiguous sequence of elements within an array.
+ ++
Example 1:
+ +Input: nums = [1,3,2,3,3], k = 2 +Output: 6 +Explanation: The subarrays that contain the element 3 at least 2 times are: [1,3,2,3], [1,3,2,3,3], [3,2,3], [3,2,3,3], [2,3,3] and [3,3]. ++ +
Example 2:
+ +Input: nums = [1,4,2,1], k = 3 +Output: 0 +Explanation: No subarray contains the element 4 at least 3 times. ++ +
+
Constraints:
+ +1 <= nums.length <= 1051 <= nums[i] <= 1061 <= k <= 105You are given an integer array nums of size n and a positive integer k.
Divide the array into one or more arrays of size 3 satisfying the following conditions:
nums should be in exactly one array.k.Return a 2D array containing all the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return any of them.
+ ++
Example 1:
+ +Input: nums = [1,3,4,8,7,9,3,5,1], k = 2 +Output: [[1,1,3],[3,4,5],[7,8,9]] +Explanation: We can divide the array into the following arrays: [1,1,3], [3,4,5] and [7,8,9]. +The difference between any two elements in each array is less than or equal to 2. +Note that the order of elements is not important. ++ +
Example 2:
+ +Input: nums = [1,3,3,2,7,3], k = 3 +Output: [] +Explanation: It is not possible to divide the array satisfying all the conditions. ++ +
+
Constraints:
+ +n == nums.length1 <= n <= 105n is a multiple of 3.1 <= nums[i] <= 1051 <= k <= 105You are given an array of positive integers nums of length n.
A polygon is a closed plane figure that has at least 3 sides. The longest side of a polygon is smaller than the sum of its other sides.
Conversely, if you have k (k >= 3) positive real numbers a1, a2, a3, ..., ak where a1 <= a2 <= a3 <= ... <= ak and a1 + a2 + a3 + ... + ak-1 > ak, then there always exists a polygon with k sides whose lengths are a1, a2, a3, ..., ak.
The perimeter of a polygon is the sum of lengths of its sides.
+ +Return the largest possible perimeter of a polygon whose sides can be formed from nums, or -1 if it is not possible to create a polygon.
+
Example 1:
+ +Input: nums = [5,5,5] +Output: 15 +Explanation: The only possible polygon that can be made from nums has 3 sides: 5, 5, and 5. The perimeter is 5 + 5 + 5 = 15. ++ +
Example 2:
+ +Input: nums = [1,12,1,2,5,50,3] +Output: 12 +Explanation: The polygon with the largest perimeter which can be made from nums has 5 sides: 1, 1, 2, 3, and 5. The perimeter is 1 + 1 + 2 + 3 + 5 = 12. +We cannot have a polygon with either 12 or 50 as the longest side because it is not possible to include 2 or more smaller sides that have a greater sum than either of them. +It can be shown that the largest possible perimeter is 12. ++ +
Example 3:
+ +Input: nums = [5,5,50] +Output: -1 +Explanation: There is no possible way to form a polygon from nums, as a polygon has at least 3 sides and 50 > 5 + 5. ++ +
+
Constraints:
+ +3 <= n <= 1051 <= nums[i] <= 109You are given two 0-indexed strings source and target, both of length n and consisting of lowercase English letters. You are also given two 0-indexed character arrays original and changed, and an integer array cost, where cost[i] represents the cost of changing the character original[i] to the character changed[i].
You start with the string source. In one operation, you can pick a character x from the string and change it to the character y at a cost of z if there exists any index j such that cost[j] == z, original[j] == x, and changed[j] == y.
Return the minimum cost to convert the string source to the string target using any number of operations. If it is impossible to convert source to target, return -1.
Note that there may exist indices i, j such that original[j] == original[i] and changed[j] == changed[i].
+
Example 1:
+ +Input: source = "abcd", target = "acbe", original = ["a","b","c","c","e","d"], changed = ["b","c","b","e","b","e"], cost = [2,5,5,1,2,20] +Output: 28 +Explanation: To convert the string "abcd" to string "acbe": +- Change value at index 1 from 'b' to 'c' at a cost of 5. +- Change value at index 2 from 'c' to 'e' at a cost of 1. +- Change value at index 2 from 'e' to 'b' at a cost of 2. +- Change value at index 3 from 'd' to 'e' at a cost of 20. +The total cost incurred is 5 + 1 + 2 + 20 = 28. +It can be shown that this is the minimum possible cost. ++ +
Example 2:
+ +Input: source = "aaaa", target = "bbbb", original = ["a","c"], changed = ["c","b"], cost = [1,2] +Output: 12 +Explanation: To change the character 'a' to 'b' change the character 'a' to 'c' at a cost of 1, followed by changing the character 'c' to 'b' at a cost of 2, for a total cost of 1 + 2 = 3. To change all occurrences of 'a' to 'b', a total cost of 3 * 4 = 12 is incurred. ++ +
Example 3:
+ +Input: source = "abcd", target = "abce", original = ["a"], changed = ["e"], cost = [10000] +Output: -1 +Explanation: It is impossible to convert source to target because the value at index 3 cannot be changed from 'd' to 'e'. ++ +
+
Constraints:
+ +1 <= source.length == target.length <= 105source, target consist of lowercase English letters.1 <= cost.length == original.length == changed.length <= 2000original[i], changed[i] are lowercase English letters.1 <= cost[i] <= 106original[i] != changed[i]You are given a 0-indexed integer array nums and a positive integer k.
You can apply the following operation on the array any number of times:
+ +0 to 1 or vice versa.Return the minimum number of operations required to make the bitwise XOR of all elements of the final array equal to k.
Note that you can flip leading zero bits in the binary representation of elements. For example, for the number (101)2 you can flip the fourth bit and obtain (1101)2.
+
Example 1:
+ +Input: nums = [2,1,3,4], k = 1 +Output: 2 +Explanation: We can do the following operations: +- Choose element 2 which is 3 == (011)2, we flip the first bit and we obtain (010)2 == 2. nums becomes [2,1,2,4]. +- Choose element 0 which is 2 == (010)2, we flip the third bit and we obtain (110)2 = 6. nums becomes [6,1,2,4]. +The XOR of elements of the final array is (6 XOR 1 XOR 2 XOR 4) == 1 == k. +It can be shown that we cannot make the XOR equal to k in less than 2 operations. ++ +
Example 2:
+ +Input: nums = [2,0,2,0], k = 0 +Output: 0 +Explanation: The XOR of elements of the array is (2 XOR 0 XOR 2 XOR 0) == 0 == k. So no operation is needed. ++ +
+
Constraints:
+ +1 <= nums.length <= 1050 <= nums[i] <= 1060 <= k <= 106You are given an array nums consisting of positive integers.
Return the total frequencies of elements in nums such that those elements all have the maximum frequency.
The frequency of an element is the number of occurrences of that element in the array.
+ ++
Example 1:
+ +Input: nums = [1,2,2,3,1,4] +Output: 4 +Explanation: The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array. +So the number of elements in the array with maximum frequency is 4. ++ +
Example 2:
+ +Input: nums = [1,2,3,4,5] +Output: 5 +Explanation: All elements of the array have a frequency of 1 which is the maximum. +So the number of elements in the array with maximum frequency is 5. ++ +
+
Constraints:
+ +1 <= nums.length <= 1001 <= nums[i] <= 100You are given a string word containing 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 = "xyzxyzxyzxyz" +Output: 12 +Explanation: The remapped keypad given in the image provides the minimum cost. +"x" -> one push on key 2 +"y" -> one push on key 3 +"z" -> one push on key 4 +Total cost is 1 * 4 + 1 * 4 + 1 * 4 = 12 +It can be shown that no other mapping can provide a lower cost. +Note that the key 9 is not mapped to any letter: it is not necessary to map letters to every key, but to map all the letters. ++ +
Example 3:
+
+Input: word = "aabbccddeeffgghhiiiiii" +Output: 24 +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 +"f" -> one push on key 7 +"g" -> one push on key 8 +"h" -> two pushes on key 9 +"i" -> one push on key 9 +Total cost is 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 2 * 2 + 6 * 1 = 24. +It can be shown that no other mapping can provide a lower cost. ++ +
+
Constraints:
+ +1 <= word.length <= 105word consists of lowercase English letters.You are given the head of a linked list of even length containing integers.
Each odd-indexed node contains an odd integer and each even-indexed node contains an even integer.
+ +We call each even-indexed node and its next node a pair, e.g., the nodes with indices 0 and 1 are a pair, the nodes with indices 2 and 3 are a pair, and so on.
For every pair, we compare the values of the nodes in the pair:
+ +"Odd" team gets a point."Even" team gets a point.Return the name of the team with the higher points, if the points are equal, return "Tie".
+
Example 1:
+ +Input: head = [2,1]
+ +Output: "Even"
+ +Explanation: There is only one pair in this linked list and that is (2,1). Since 2 > 1, the Even team gets the point.
Hence, the answer would be "Even".
Example 2:
+ +Input: head = [2,5,4,7,20,5]
+ +Output: "Odd"
+ +Explanation: There are 3 pairs in this linked list. Let's investigate each pair individually:
(2,5) -> Since 2 < 5, The Odd team gets the point.
(4,7) -> Since 4 < 7, The Odd team gets the point.
(20,5) -> Since 20 > 5, The Even team gets the point.
The Odd team earned 2 points while the Even team got 1 point and the Odd team has the higher points.
Hence, the answer would be "Odd".
Example 3:
+ +Input: head = [4,5,2,1]
+ +Output: "Tie"
+ +Explanation: There are 2 pairs in this linked list. Let's investigate each pair individually:
(4,5) -> Since 4 < 5, the Odd team gets the point.
(2,1) -> Since 2 > 1, the Even team gets the point.
Both teams earned 1 point.
Hence, the answer would be "Tie".
+
Constraints:
+ +[2, 100].1 <= Node.val <= 100Given the head of a linked list containing k distinct elements, return the head to a linked list of length k containing the frequency of each distinct element in the given linked list in any order.
+
Example 1:
+ +Input: head = [1,1,2,1,2,3]
+ +Output: [3,2,1]
+ +Explanation: There are 3 distinct elements in the list. The frequency of 1 is 3, the frequency of 2 is 2 and the frequency of 3 is 1. Hence, we return 3 -> 2 -> 1.
Note that 1 -> 2 -> 3, 1 -> 3 -> 2, 2 -> 1 -> 3, 2 -> 3 -> 1, and 3 -> 1 -> 2 are also valid answers.
Example 2:
+ +Input: head = [1,1,2,2,2]
+ +Output: [2,3]
+ +Explanation: There are 2 distinct elements in the list. The frequency of 1 is 2 and the frequency of 2 is 3. Hence, we return 2 -> 3.
Example 3:
+ +Input: head = [6,5,4,3,2,1]
+ +Output: [1,1,1,1,1,1]
+ +Explanation: There are 6 distinct elements in the list. The frequency of each of them is 1. Hence, we return 1 -> 1 -> 1 -> 1 -> 1 -> 1.
+
Constraints:
+ +[1, 105].1 <= Node.val <= 105There exists an undirected tree with n nodes numbered 0 to n - 1. You are given a 0-indexed 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the tree. You are also given a positive integer k, and a 0-indexed array of non-negative integers nums of length n, where nums[i] represents the value of the node numbered i.
Alice wants the sum of values of tree nodes to be maximum, for which Alice can perform the following operation any number of times (including zero) on the tree:
+ +[u, v] connecting the nodes u and v, and update their values as follows:
+
+ nums[u] = nums[u] XOR knums[v] = nums[v] XOR kReturn the maximum possible sum of the values Alice can achieve by performing the operation any number of times.
+ ++
Example 1:
+
+Input: nums = [1,2,1], k = 3, edges = [[0,1],[0,2]] +Output: 6 +Explanation: Alice can achieve the maximum sum of 6 using a single operation: +- Choose the edge [0,2]. nums[0] and nums[2] become: 1 XOR 3 = 2, and the array nums becomes: [1,2,1] -> [2,2,2]. +The total sum of values is 2 + 2 + 2 = 6. +It can be shown that 6 is the maximum achievable sum of values. ++ +
Example 2:
+
+Input: nums = [2,3], k = 7, edges = [[0,1]] +Output: 9 +Explanation: Alice can achieve the maximum sum of 9 using a single operation: +- Choose the edge [0,1]. nums[0] becomes: 2 XOR 7 = 5 and nums[1] become: 3 XOR 7 = 4, and the array nums becomes: [2,3] -> [5,4]. +The total sum of values is 5 + 4 = 9. +It can be shown that 9 is the maximum achievable sum of values. ++ +
Example 3:
+
+Input: nums = [7,7,7,7,7,7], k = 3, edges = [[0,1],[0,2],[0,3],[0,4],[0,5]] +Output: 42 +Explanation: The maximum achievable sum is 42 which can be achieved by Alice performing no operations. ++ +
+
Constraints:
+ +2 <= n == nums.length <= 2 * 1041 <= k <= 1090 <= nums[i] <= 109edges.length == n - 1edges[i].length == 20 <= edges[i][0], edges[i][1] <= n - 1edges represent a valid tree.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 * 1051 <= happiness[i] <= 1081 <= k <= nYou are given a string s. The score of a string is defined as the sum of the absolute difference between the ASCII values of adjacent characters.
Return the score of s.
+
Example 1:
+ +Input: s = "hello"
+ +Output: 13
+ +Explanation:
+ +The ASCII values of the characters in s are: 'h' = 104, 'e' = 101, 'l' = 108, 'o' = 111. So, the score of s would be |104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13.
Example 2:
+ +Input: s = "zaz"
+ +Output: 50
+ +Explanation:
+ +The ASCII values of the characters in s are: 'z' = 122, 'a' = 97. So, the score of s would be |122 - 97| + |97 - 122| = 25 + 25 = 50.
+
Constraints:
+ +2 <= s.length <= 100s consists only of lowercase English letters.Given a 2D array rooks of length n, where rooks[i] = [xi, yi] indicates the position of a rook on an n x n chess board. Your task is to move the rooks 1 cell at a time vertically or horizontally (to an adjacent cell) such that the board becomes peaceful.
A board is peaceful if there is exactly one rook in each row and each column.
+ +Return the minimum number of moves required to get a peaceful board.
+ +Note that at no point can there be two rooks in the same cell.
+ ++
Example 1:
+ +Input: rooks = [[0,0],[1,0],[1,1]]
+ +Output: 3
+ +Explanation:
+
Example 2:
+ +Input: rooks = [[0,0],[0,1],[0,2],[0,3]]
+ +Output: 6
+ +Explanation:
+
+
Constraints:
+ +1 <= n == rooks.length <= 5000 <= xi, yi <= n - 1