SodaPDF Converted Untitled Document 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

1.

Regular Expression Matching : String - pattern diya hua hai check whether pattern matches string or not
2. Longest Valid Parentheses : Given a string containing just the characters '(' and ')', find the length of the longest va
lid (well-formed) parentheses substring.
3. Trapping Rain Water : Given n non-negative integers representing an elevation map where the width of each bar i
s 1, compute how much water it can trap after raining.
4. Wildcard Matching : Given an input string (s) and a pattern (p), implement wildcard pattern matching with suppor
t for '?' and '*'
5. Edit Distance : Given two strings word1 and word2, return the minimum number of operations required to convert
word1 to word2.
6. Maximal Rectangle : Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing
only 1's and return its area.
7. Scramble String : We can scramble a string s to get a string t using the following algorithm ; Given two strings s1
and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
8. Distinct Subsequences : Given two strings s and t, return the number of distinct subsequences of s which equals t.
9. Best Time to Buy and Sell Stock III : You are given an array prices where prices[i] is the price of a given stock on
the ith day. Find the maximum profit you can achieve. You may complete at most two transactions.
10. Binary Tree Maximum Path Sum : Given the root of a binary tree, return the maximum path sum of any non-emp
ty path.
11. Palindrome Partitioning II : Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
12. Word Break II : Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence whe
re each word is a valid dictionary word. Return all such possible sentences in any order.
13. Dungeon Game : Matrix : The demons had captured the princess and imprisoned her in the bottom-right corner o
f a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned i
n the top-left room and must fight his way through dungeon to rescue the princess. Return the knight's minimum initi
al health so that he can rescue the princess.
14. Best Time to Buy and Sell Stock IV : You are given an integer array prices where prices[i] is the price of a given
stock on the ith day, and an integer k.Find the maximum profit you can achieve. You may complete at most k transa
ctions.
15. Number of Digit One : Given an integer n, count the total number of digit 1 appearing in all non-negative intege
rs less than or equal to n.
16. Paint House II : There are a row of n houses, each house can be painted with one of the k colors. The cost of pain
ting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses ha
ve the same color.The cost of painting each house with a certain color is represented by an n x k cost matrix costs.Re
turn the minimum cost to paint all houses.
17. Burst Balloons : You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it r
epresented by an array nums. You are asked to burst all the balloons.If you burst the ith balloon, you will get nums[i
- 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon
with a 1 painted on it. Return the maximum coins you can collect by bursting the balloons wisely.
18. Longest Increasing Path in a Matrix : Given an m x n integers matrix, return the length of the longest increasing
path in matrix.
19. Russian Doll Envelopes : You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represent
s the width and the height of an envelope.Return the maximum number of envelopes you can Russian doll (i.e., put o
ne inside the other).
20. Max Sum of Rectangle No Larger Than K : Given an m x n matrix matrix and an integer k, return the max sum o
f a rectangle in the matrix such that its sum is no larger than k
21. Frog Jump : Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross t
he 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.
22. Split Array Largest Sum : Given an array nums which consists of non-negative integers and an integer m, you ca
n split the array into m non-empty continuous subarrays.Write an algorithm to minimize the largest sum among these
m subarrays.
23. Arithmetic Slices II - Subsequence : Given an integer array nums, return the number of all the arithmetic subsequ
ences of nums.
24. Poor Pigs : There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out whi
ch one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunatel
y, you only have minutesToTest minutes to determine which bucket is poisonous. Given buckets, minutesToDie, and
minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allott
ed time.
25. Optimal Account Balancing : You are given an array of transactions transactions where transactions[i] = [fromi, t
oi, amounti] indicates that the person with ID = fromi gave amounti $ to the person with ID = toi.Return the minimu
m number of transactions required to settle the debt.
26. Count The Repetitions : You are given two strings s1 and s2 and two integers n1 and n2. You have the two string
s str1 = [s1, n1] and str2 = [s2, n2]. Return the maximum integer m such that str = [str2, m] can be obtained from str
1.We define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it beco
mes s1. We define str = [s, n] as the string str which consists of the string s concatenated n times.
27. Encode String with Shortest Length : Given a string s, encode the string such that its encoded length is the shorte
st.The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated ex
actly k times. k should be a positive integer.
28. Concatenated Words : Given an array of strings words (without duplicates), return all the concatenated words in
the given list of words. A concatenated word is defined as a string that is comprised entirely of at least two shorter w
ords in the given array.
29. Zuma Game : Given a string board, representing the row of balls on the board, and a string hand, representing th
e balls in your hand, return the minimum number of balls you have to insert to clear all the balls from the board. If y
ou cannot clear all the balls from the board using the balls in your hand, return -1.
30. Freedom Trail : Given a string ring that represents the code engraved on the outer ring and another string key tha
t represents the keyword that needs to be spelled, return the minimum number of steps to spell all the characters in th
e keyword.
31. Remove Boxes : You are given several boxes with different colors represented by different positive numbers. Yo
u may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuo
us boxes with the same color (i.e., composed of k boxes, k >= 1), remove them and get k * k points. Return the maxi
mum points you can get.
32. Student Attendance Record II : Given an integer n, return the number of possible attendance records of length n t
hat make a student eligible for an attendance award. The answer may be very large, so return it modulo 109 + 7.Any
student is eligible for an attendance award if they meet both of the following criteria:The student was absent ('A') for
strictly fewer than 2 days total.The student was never late ('L') for 3 or more consecutive days.
33. Maximum Vacation Days : employees the option to travel among n cities to collect algorithm problems. Your jo
b is to schedule the traveling to maximize the number of vacation days you could take, but there are certain rules and
restrictions you need to follow. Given the two matrices flights and days, return the maximum vacation days you cou
ld take during k weeks.
34. Non-negative Integers without Consecutive Ones : Given a positive integer n, return the number of the integers i
n the range [0, n] whose binary representations do not contain consecutive ones.
35. K Inverse Pairs Array : For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 <= i < j < nu
ms.length and nums[i] > nums[j].Given two integers n and k, return the number of different arrays consist of number
s from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo 109 + 7.
36. Decode Ways II : Given a string s consisting of digits and '*' characters, return the number of ways to decode it.
s = "2*" he encoded message can represent any of the encoded messages "21", "22", "23", "24", "25", "26", "27", "2
8", or "29"."21", "22", "23", "24", "25", and "26" have 2 ways of being decoded, but "27", "28", and "29" only have
1 way.Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode "2*".
37. Coin Path : You are given an integer array coins (1-indexed) of length n and an integer maxJump. You can jump
to any index i of the array coins if coins[i] != -1 and you have to pay coins[i] when you visit index i. In addition to th
at, if you are currently at index i, you can only jump to any index i + k where i + k <= n and k is a value in the range
[1, maxJump].Return an integer array of the indices that you will visit in order so that you can reach index n with the
minimum cost. If there are multiple paths with the same cost, return the lexicographically smallest such path. If it is
not possible to reach index n, return an empty array.
38. Strange Printer : The printer can only print a sequence of the same character each time. At each turn, the printer c
an print new characters starting from and ending at any place and will cover the original existing characters. Given a
string s, return the minimum number of turns the printer needed to print it.
39. Maximum Sum of 3 Non-Overlapping Subarrays : Given an integer array nums and an integer k, find three non-
overlapping subarrays of length k with maximum sum and return them. Return the result as a list of indices represent
ing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically small
est one
40. Stickers to Spell Word : You would like to spell out the given string target by cutting individual letters from your
collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infi
nite quantities of each sticker.Return the minimum number of stickers that you need to spell out target. If the task is i
mpossible, return -1
41. Minimum Window Subsequence : Given strings s1 and s2, return the minimum contiguous substring part of s1, s
o that s2 is a subsequence of the part.
42. Count Different Palindromic Subsequences : Given a string s, return the number of different non-empty palindro
mic subsequences in s. Since the answer may be very large, return it modulo 109 + 7.
43. Cherry Pickup : Return the maximum number of cherries you can collect by following the rules below:
44. Minimum Swaps To Make Sequences Increasing : Return the minimum number of needed operations to make nu
ms1 and nums2 strictly increasing. The test cases are generated so that the given input always makes it possible.
45. Split Array With Same Average : You should move each element of nums into one of the two arrays A and B su
ch that A and B are non-empty, and average(A) == average(B).
46. Race car : Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative po
sitions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse): Given
a target position target, return the length of the shortest sequence of instructions to get there.
47. Count Unique Characters of All Substrings of a Given String : Given a string s, return the sum of countUniqueC
hars(t) where t is a substring of s
48. Sum of Distances in Tree : Return an array answer of length n where answer[i] is the sum of the distances betwe
en the ith node in the tree and all other nodes.
49. Shortest Path Visiting All Nodes : 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.
50. Minimum Number of Refueling Stops : There are gas stations along the way. The gas stations are represented as
an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the sta
rting position and has fueli liters of gas. Return the minimum number of refueling stops the car must make in order t
o reach its destination.
51. Profitable Schemes : There is a group of n members, and a list of various crimes they could commit. The ith crim
e generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that
member can't participate in another crime.Let's call a profitable scheme any subset of these crimes that generates at l
east minProfit profit, and the total number of members participating in that subset of crimes is at most n
52. Super Egg Drop : You are given k identical eggs and you have access to a building with n floors labeled from 1 t
o n. You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will bre
ak, and any egg dropped at or below floor f will not break. Return the minimum number of moves that you need to d
etermine with certainty what the value of f is.
53. Numbers At Most N Given Digit Set : Given an array of digits which is sorted in non-decreasing order. You can
write numbers using each digits[i] as many times as we want. Return the number of positive integers that can be gen
erated that are less than or equal to a given integer n.
54. Valid Permutations for DI Sequence : A permutation perm of n + 1 integers of all the integers in the range [0, n]
is called a valid permutation if for all valid i: If s[i] == 'D', then perm[i] > perm[i + 1], and If s[i] == 'I', then perm[i]
< perm[i + 1]. Return the number of valid permutations perm.
55. Cat and Mouse : A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.
56. Number of Music Playlists : Your 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: Given n, goal, and k, retu
rn the number of possible playlists that you can create.
57. Distinct Subsequences II : Given a string s, return the number of distinct non-empty subsequences of s.
58. Find the Shortest Superstring : Given an array of strings words, return the smallest string that contains each strin
g in words as a substring. If there are multiple valid strings of the smallest length, return any of them.
59. Tallest Billboard : You are installing a billboard and want it to have the largest height. The billboard will have tw
o steel supports, one on each side. Each steel support must be an equal height.Return the largest possible height of y
our billboard installation. If you cannot support the billboard, return 0.
60. Delete Columns to Make Sorted III : Suppose we chose a set of deletion indices answer such that after deletions,
the final array has every string (row) in lexicographic order. (i.e., (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].len
gth - 1]), and (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1]), and so on). Return the minimum possible v
alue of answer.length. For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the fin
al array after deletions is ["bef", "vyz"].
61. Least Operators to Express Number : We would like to write an expression with the least number of operators su
ch that the expression equals the given target. Return the least number of operators used.
62. Binary Tree Cameras : You are given the root of a binary tree. We install cameras on the tree nodes where each c
amera at a node can monitor its parent, itself, and its immediate children.Return the minimum number of cameras ne
eded to monitor all nodes of the tree.
63. Odd Even Jump : You are given an integer array arr. From some starting index, you can make a series of jumps.
The (1st, 3rd, 5th, ...) jumps in the series are called odd-numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the seri
es are called even-numbered jumps. Note that the jumps are numbered, not the indices.A starting index is good if, sta
rting from that index, you can reach the end of the array (index arr.length - 1) by jumping some number of times (po
ssibly 0 or more than once). Return the number of good starting indices.
64. Number of Squareful Arrays : An array is squareful if the sum of every pair of adjacent elements is a perfect squ
are.Given an integer array nums, return the number of permutations of nums that are squareful.
65. Minimum Cost to Merge Stones : A move consists of merging exactly k consecutive piles into one pile, and the c
ost of this move is equal to the total number of stones in these k piles. Return the minimum cost to merge all piles of
stones into one pile. If it is impossible, return -1.
66. Numbers With Repeated Digits : Given an integer n, return the number of positive integers in the range [1, n] tha
t have at least one repeated digit.
67. Digit Count in Range : Given a single-digit integer d and two integers low and high, return the number of times t
hat d occurs as a digit in all integers in the inclusive range [low, right].
68. Shortest Common Supersequence : Given two strings str1 and str2, return the shortest string that has both str1 an
d str2 as subsequences. If there are multiple valid strings, return any of them.
69. Smallest Sufficient Team : In a project, you have a list of required skills req_skills, and a list of people. The ith p
erson people[i] contains a list of skills that the person has. Return any sufficient team of the smallest possible size, re
presented by the index of each person. You may return the answer in any order
70. Longest Chunked Palindrome Decomposition : You are given a string text. You should split it to k substrings (s
ubtext1, subtext2, ..., subtextk) such that:subtexti == subtextk - i + 1 for all valid values of i (i.e., 1 <= i <= k). Retur
n the largest possible value of k.
71. Make Array Strictly Increasing : Given two integer arrays arr1 and arr2, return the minimum number of operatio
ns (possibly zero) needed to make arr1 strictly increasing.
72. Valid Palindrome III : Given a string s and an integer k, return true if s is a k-palindrome. A string is k-palindro
me if it can be transformed into a palindrome by removing at most k characters from it.
73. Count Vowels Permutation : Given an integer n, your task is to count how many strings of length n can be forme
d under the following rules:
74. Dice Roll Simulation : A die simulator generates a random number from 1 to 6 for each roll. You introduced a co
nstraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times. rol
lMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls.
75. Maximum Profit in Job Scheduling : We have n jobs, where every job is scheduled to be done from startTime[i] t
o endTime[i], obtaining a profit of profit[i].You're given the startTime, endTime and profit arrays, return the maxim
um profit you can take such that there are no two jobs in the subset with overlapping time range.
76. Tiling a Rectangle with the Fewest Squares : Given a rectangle of size n x m, return the minimum number of inte
ger-sided squares that tile the rectangle.
77. Palindrome Removal : Given an integer array arr, in one move you can select a palindromic subarray arr[i], arr[i
+1], ..., arr[j] where i <= j, and remove that subarray from the given array. Return the minimum number of moves ne
eded to remove all numbers from the array.
78. Maximum Score Words Formed by Letters : 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 (wor
ds[i] cannot be used two or more times).
79. Handshakes That Don't Cross : You are given an even number of people numPeople that stand around a circle an
d each person shakes hands with someone else so that there are numPeople / 2 handshakes total.Return the number o
f ways these handshakes could occur such that none of the handshakes cross.
80. Number of Ways to Stay in the Same Place After Some Steps : You have a pointer at index 0 in an array of size a
rrLen. 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 num
ber of ways such that your pointer still at index 0 after exactly steps steps.
81. Palindrome Partitioning III : You are given a string s containing lowercase letters and an integer k. You need to :
Then divide s into k non-empty disjoint substrings such that each substring is a palindrome.Return the minimal num
ber of characters that you need to change to divide the string.
82. Minimum Falling Path Sum II : Given an n x n integer matrix grid, return the minimum sum of a falling path wit
h non-zero shifts. A falling path with non-zero shifts is a choice of exactly one element from each row of grid such t
hat no two elements chosen in adjacent rows are in the same column.
83. Number of Paths with Max Score : You need to reach the top left square marked with the character 'E'. The rest o
f the squares are labeled either with a numeric character 1, 2, ..., 9 or with an obstacle 'X'. In one move you can go u
p, left or up-left (diagonally) only if there is no obstacle there.Return a list of two integers: the first integer is the ma
ximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to g
et that maximum sum
84. Minimum Insertion Steps to Make a String Palindrome : Given a string s. In one step you can insert any characte
r at any index of the string. Return the minimum number of steps to make s palindrome.
85. Distinct Echo Substrings : Return the number of distinct non-empty substrings of text that can be written as the c
oncatenation of some string with itself (i.e. it can be written as a + a where a is some string).
86 . Minimum Distance to Type a Word Using Two Fingers : You have a keyboard layout as shown above in the X-
Y plane, where each English uppercase letter is located at some coordinate.Given the string word, return the minimu
m total distance to type such string using only two fingers.The distance between coordinates (x1, y1) and (x2, y2) is |
x1 - x2| + |y1 - y2|.
87. Minimum Number of Taps to Open to Water a Garden : There is a one-dimensional garden on the x-axis. The ga
rden starts at the point 0 and ends at the point n. (i.e The length of the garden is n).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 + range
s[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.
88. Minimum Difficulty of a Job Schedule : 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 are given an integer array jobDifficulty an
d 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.
89. Jump Game V : Given an array of integers arr and an integer d. In one step you can jump from index i to index: i
+ x where: i + x < arr.length and 0 < x <= d. i - x where: i - x >= 0 and 0 < x <= d.You can choose any index of the a
rray and start jumping. Return the maximum number of indices you can visit.
90. Maximum Students Taking Exam : Given a m * n matrix seats that represent seats distributions in a classroom. I
f a seat is broken, it is denoted by '#' character otherwise it is denoted by a '.' character. Return the maximum number
of students that can take the exam together without any cheating being possible..
91. Count All Valid Pickup and Delivery Options : Given n orders, each order consist in pickup and delivery service
s. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
92. Largest Multiple of Three : Given an array of digits digits, return the largest multiple of three that can be formed
by concatenating some of the given digits in any order. If there is no answer return an empty string.
93. Maximum Sum BST in Binary Tree : Given a binary tree root, return the maximum sum of all keys of any sub-tr
ee which is also a Binary Search Tree (BST).
94. Pizza With 3n Slices : There is a pizza with 3n slices of varying size, you and your friends will take slices of pizz
a as follows: Given an integer array slices that represent the sizes of the pizza slices in a clockwise direction, return t
he maximum possible sum of slice sizes that you can pick.
95. Find All Good Strings : Given the strings s1 and s2 of size n and the string evil, return the number of good string
s.A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to
s2, and it does not contain the string evil as a substring
96. Reducing Dishes : A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1
unit of time.Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes m
ultiplied by its satisfaction level i.e. time[i] * satisfaction[i].Return the maximum sum of like-time coefficient that th
e chef can obtain after dishes preparation.
97. Stone Game III : Alice and Bob continue their games with piles of stones. There are several stones arranged in a
row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take tu
rns, with Alice starting first. On each player's turn, that player can take 1, 2, or 3 stones from the first remaining ston
es in the row.Return "Alice" if Alice will win, "Bob" if Bob will win, or "Tie" if they will end the game with the sam
e score.
98. Number of Ways to Paint N × 3 Grid : exactly one of the three colors: Red, Yellow, or Green while making sure
that no two adjacent cells have the same color Given n the number of rows of the grid, return the number of ways yo
u can paint this grid.
99. Restore The Array : A program was supposed to print an array of integers. The program forgot to print whitespac
es and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1,
k] and there are no leading zeros in the array.Given the string s and the integer k, return the number of the possible a
rrays that can be printed as s using the mentioned program.
100. Build Array Where You Can Find The Maximum Exactly K Comparisons : You are given three integers n, m a
nd k. Consider the following algorithm to find the maximum element of an array of positive integers: Return the nu
mber 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.
101. Constrained Subsequence Sum : Given an integer array nums and an integer k, return the maximum sum of a no
n-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and num
s[j], where i < j, the condition j - i <= k is satisfied.
102. Number of Ways to Wear Different Hats to Each Other : There are n people and 40 types of hats labeled from 1
to 40.Given a 2D integer array hats, where hats[i] is a list of all hats preferred by the ith person.Return the number o
f ways that the n people wear different hats to each other.
103. Number of Ways of Cutting a Pizza : Given a rectangular pizza represented as a rows x cols matrix containing t
he following characters: 'A' (an apple) and '.' (empty cell) and given the integer k. You have to cut the pizza into k pi
eces using k-1 cuts. Return the number of ways of cutting the pizza such that each piece contains at least one apple
104. Form Largest Integer With Digits That Add up to Target : Given an array of integers cost and an integer target,
return the maximum integer you can paint under the following rules:The cost of painting a digit (i + 1) is given by co
st[i] (0-indexed). The total cost used must be equal to target. The integer does not have 0 digits.
105. Max Dot Product of Two Subsequences : Return the maximum dot product between non-empty subsequences o
f nums1 and nums2 with the same length.
106. Cherry Pickup II : You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] repre
sents the number of cherries that you can collect from the (i, j) cell.Return the maximum number of cherries collecti
on using both robots by following the rules below: 2 robots
107. Probability of a Two Boxes Having The Same Number of Distinct Balls : Given 2n balls of k distinct colors. Y
ou will be given an integer array balls of size k where balls[i] is the number of balls of color i. All the balls will be s
huffled uniformly at random, then we will distribute the first n balls to the first box and the remaining n balls to the o
ther box. Return the probability that the two boxes have the same number of distinct balls.
108. Paint House III : There is a row of m houses in a small city, each house must be painted with one of the n colors
(labeled from 1 to n), some houses that have been painted last summer should not be painted again.A neighborhood
is a maximal group of continuous houses that are painted with the same color.Return the minimum cost of painting a
ll the remaining houses in such a way that there are exactly target neighborhoods
109. Allocate Mailboxes : Given the array houses where houses[i] is the location of the ith house along a street and a
n integer k, allocate k mailboxes in the street. Return the minimum total distance between each house and its nearest
mailbox.
110. Kth Ancestor of a Tree Node : You are given a tree with n nodes numbered from 0 to n - 1 in the form of a pare
nt array parent where parent[i] is the parent of ith node. The root of the tree is node 0. Find the kth ancestor of a give
n node.int getKthAncestor(int node, int k) return the kth ancestor of the given node node. If there is no such ancestor
, return -1
111. Parallel Courses II : You are given an integer n, which indicates that there are n courses labeled from 1 to n. Yo
u are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relatio
nship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCo
ursei. Also, you are given the integer k.In one semester, you can take at most k courses as long as you have taken all
the prerequisites in the previous semesters for the courses you are taking.Return the minimum number of semesters
needed to take all courses
112. Stone Game IV : Initially, there are n stones in a pile. On each player's turn, that player makes a move consistin
g of removing any non-zero square number of stones in the pile. Also, if a player cannot make a move, he/she loses t
he game.Given a positive integer n, return true if and only if Alice wins the game otherwise return false
113. Minimum Number of Increments on Subarrays to Form a Target Array : You are given an integer array target.
You have an integer array initial of the same size as target with all elements initially zeros.In one operation you can
choose any subarray from initial and increment each value by one.Return the minimum number of operations to for
m a target array from initial.
114. String Compression II : Run-length encoding is a string compression method that works by replacing consecuti
ve identical characters (repeated 2 or more times) with the concatenation of the character and the number marking th
e count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" a
nd replace "ccc" by "c3". Thus the compressed string becomes "a2bc3".Given a string s and an integer k. You need t
o delete at most k characters from s such that the run-length encoded version of s has minimum length.Find the mini
mum length of the run-length encoded version of s after deleting at most k characters.
115. Get the Maximum Score : You are given two sorted arrays of distinct integers nums1 and nums2.A valid path is
defined as follows: If you are reading any value that is present in nums1 and nums2 you are allowed to change your
path to the other array.Return the maximum score you can obtain of all possible valid paths.
116. Minimum Cost to Cut a Stick : The cost of one cut is the length of the stick to be cut, the total cost is the sum of
costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the lengt
h of the stick before the cut). Return the minimum total cost of the cuts.
117. The Most Similar Path in a Graph : We have n cities and m bi-directional roads where roads[i] = [ai, bi] connec
ts city ai with city bi. Each city has a name consisting of exactly three upper-case English letters given in the string a
rray names. Starting at any city x, you can reach any city y where y != x (i.e., the cities and the roads are forming an
undirected connected graph). You will be given a string array targetPath. You should find a path in the graph of the s
ame length and with the minimum edit distance to targetPath. code
118. Minimum Number of Days to Eat N Oranges : If the number of remaining oranges n is divisible by 3 then you c
an eat 2 * (n / 3) oranges. Given the integer n, return the minimum number of days to eat n oranges.
119. Stone Game V : In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and rig
ht row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob th
rows away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If t
he value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with
the remaining row.Return the maximum score that Alice can obtain.
120. Number of Ways to Reorder Array to Get Same BST : Given an array nums that represents a permutation of int
egers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order in
to an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical
to that formed from the original array nums. Return the number of ways to reorder nums such that the BST formed i
s identical to the original BST formed from nums.
121. Count All Possible Routes : You are given an array of distinct positive integers locations where locations[i] repr
esents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending cit
y, and the initial amount of fuel you have, respectively.At each step, if you are at city i, you can pick any city j such t
hat j != i and 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you
have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x. Return the count of all poss
ible routes from start to finish
122. Minimum Cost to Connect Two Groups of Points : The cost of the connection between any two points are given
in an size1 x size2 matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second
group. The groups are connected if each point in both groups is connected to one or more points in the opposite gro
up. In other words, each point in the first group must be connected to at least one point in the second group, and each
point in the second group must be connected to at least one point in the first group.Return the minimum cost it takes
to connect the two groups.
123. Minimum One Bit Operations to Make Integers Zero : Given an integer n, you must transform it into 0 using th
e following operations any number of times:Change the rightmost (0th) bit in the binary representation of n.Change t
he 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. Retu
rn the minimum number of operations to transform n into 0.
124. Count Subtrees With Max Distance Between Cities : There are n cities numbered from 1 to n. You are given an
array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists
a unique path between each pair of cities. In other words, the cities form a tree. For each d from 1 to n-1, find the nu
mber of subtrees in which the maximum distance between any two cities in the subtree is equal to d. Return an array
of size n-1 where the dth element (1-indexed) is the number of subtrees in which the maximum distance between any
two cities is equal to d.
125. Number of Ways to Form a Target String Given a Dictionary : You are given a list of strings of the same length
words and a string target.To form the ith character (0-indexed) of target, you can choose the kth character of the jth
string in words if target[i] = words[j][k]. Once you use the kth character of the jth string of words, you can no longer
use the xth character of any string in words where x <= k. In other words, all characters to the left of or at index k be
come unusuable for every string.Repeat the process until you form the string target. Return the number of ways to fo
rm target from words.
126. Kth Smallest Instructions : Bob is standing at cell (0, 0), and he wants to reach destination: (row, column). He c
an only travel right and down. You are going to help Bob by providing instructions for him to reach destination. Giv
en an integer array destination and an integer k, return the kth lexicographically smallest instructions that will take B
ob to destination.
127. Distribute Repeating Integers : You are given an array of n integers, nums, where there are at most 50 unique v
alues in the array. You are also given an array of m customer order quantities, quantity, where quantity[i] is the amo
unt of integers the ith customer ordered. Determine if it is possible to distribute nums such that:The ith customer gets
exactly quantity[i] integers, The integers the ith customer gets are all equal, andEvery customer is satisfied. Return t
rue if it is possible to distribute nums according to the above conditions.
128. Maximize Grid Happiness : You are given four integers, m, n, introvertsCount, and extrovertsCount. You have
an m x n grid, and there are two types of people: introverts and extroverts. There are introvertsCount introverts and e
xtrovertsCount extroverts. The happiness of each person is calculated as follows: Introverts start with 120 happiness
and lose 30 happiness for each neighbor (introvert or extrovert). Extroverts start with 40 happiness and gain 20 happi
ness for each neighbor (introvert or extrovert). The grid happiness is the sum of each person's happiness. Return the
maximum possible grid happiness.
129. Minimum Number of Removals to Make Mountain Array : You may recall that an array arr is a mountain array
if and only if:arr.length >= 3There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:arr[0] < arr[1
] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1] Given an integer array nums , return the minimu
m number of elements to remove to make nums a mountain array.
130. Minimum Incompatibility : A subset's incompatibility is the difference between the maximum and minimum el
ements in that array. Return the minimum possible sum of incompatibilities of the k subsets after distributing the arr
ay optimally, or return -1 if it is not possible.
131. Delivering Boxes from Storage to Ports : You have the task of delivering some boxes from storage to their ports
using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry. Yo
u are given an array boxes, where boxes[i] = [ports i , weighti], and three integers portsCount, maxBoxes, and max
Weight.Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.
132. Maximum Height by Stacking Cuboids : Given n cuboids where the dimensions of the ith cuboid is cuboids[i]
= [widthi, lengthi, heighti] (0-indexed). Choose a subset of cuboids and place them on each other.You can place cub
oid i on cuboid j if widthi <= widthj and lengthi <= lengthj and heighti <= heightj. You can rearrange any cuboid's di
mensions by rotating it to put it on another cuboid.Return the maximum height of the stacked cuboids.
133. Count Ways to Distribute Candies : There are n unique candies (labeled 1 through n) and k bags. You are asked
to distribute all the candies into the bags such that every bag has at least one candy.There can be multiple ways to di
stribute the candies. Two ways are considered different if the candies in one bag in the first way are not all in the sa
me bag in the second way. The order of the bags and the order of the candies within each bag do not matter. Given t
wo integers, n and k, return the number of different ways to distribute the candies.
134. Sum Of Special Evenly-Spaced Elements In Array : You are given a 0-indexed integer array nums consisting of
n non-negative integers. You are also given an array queries, where queries[i] = [xi, yi]. The answer to the ith query
is the sum of all nums[j] where xi <= j < n and (j - xi) is divisible by yi. Return an array answer where answer.length
== queries.length and answer[i]
135. Find Minimum Time to Finish All Jobs : There are k workers that you can assign jobs to. Each job should be as
signed to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assig
ned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is mi
nimized. Return the minimum possible maximum working time of any assignment.
136. Cat and Mouse II : A game is played by a cat and a mouse named Cat and Mouse. The environment is represent
ed by a grid of size rows x cols, where each element is a wall, floor, player (Cat, Mouse), or food.Mouse and Cat pla
y according to the following rules: Given a rows x cols matrix grid and two integers catJump and mouseJump, return
true if Mouse can win the game if both Cat and Mouse play optimally, otherwise return false.
137. Count Ways to Make Array With Product : You are given a 2D integer array, queries. For each queries[i], wher
e queries[i] = [ni, ki], find the number of different ways you can place positive integers into an array of size ni such t
hat the product of the integers is ki. As the number of ways may be too large, the answer to the ith query is the numb
er of ways modulo 109 + 7.Return an integer array answer where answer.length == queries.length, and answer[i] is t
he answer to the ith query.
138. Palindrome Partitioning IV : Given a string s, return true if it is possible to split the string s into three non-empt
y palindromic substrings. Otherwise, return false. A string is said to be palindrome if it the same string when reve
rsed.
139. Maximum Number of Events That Can Be Attended II : You are given an array of events where events[i] = [sta
rtDayi, endDayi, valuei]. The ith event starts at startDayi and ends at endDayi, and if you attend this event, you will r
eceive a value of valuei. You are also given an integer k which represents the maximum number of events you can at
tend. You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Not
e that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on th
e same day.Return the maximum sum of values that you can receive by attending events.
140. Closest Subsequence Sum : You are given an integer array nums and an integer goal. You want to choose a sub
sequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subseque
nce's elements is sum, then you want to minimize the absolute difference abs(sum - goal).Return the minimum possi
ble value of abs(sum - goal).
141. Maximize Palindrome Length From Subsequences : You are given two strings, word1 and word2. You want to
construct a string in the following manner: Choose some non-empty subsequence subsequence1 from word1. Choose
some non-empty subsequence subsequence2 from word2. Concatenate the subsequences: subsequence1 + subseque
nce2, to make the string. Return the length of the longest palindrome that can be constructed in the described manner
. If no palindromes can be constructed, return 0.
142. Make the XOR of All Segments Equal to Zero : You are given an array nums and an integer k . The XOR o
f a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right, inclusi
ve: nums[left] XOR nums[left+1] XOR ... XOR nums[right]. Return the minimum number of elements to change in t
he array such that the XOR of all segments of size k is equal to zero.
143. Maximize Score After N Operations : You are given nums, an array of positive integers of size 2 * n. You must
perform n operations on this array. In the ith operation (1-indexed), you will: Choose two elements, x and y. Receiv
e a score of i * gcd(x, y). Remove x and y from nums. Return the maximum score you can receive after performing n
operations.
144. Maximum Number of Groups Getting Fresh Donuts : There is a donuts shop that bakes donuts in batches of bat
chSize. They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next bat
ch. You are given an integer batchSize and an integer array groups, where groups[i] denotes that there is a group of g
roups[i] customers that will visit the shop. Each customer will get exactly one donut. When a group visits the shop, a
ll customers of the group must be served before serving any of the following groups. A group will be happy if they a
ll get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previo
us group. You can freely rearrange the ordering of the groups. Return the maximum possible number of happy group
s after rearranging the groups.
145. Largest Color Value in a Directed Graph : There is a directed graph of n colored nodes and m edges. The nodes
are numbered from 0 to n - 1. You are given a string colors where colors[i] is a lowercase English letter representing
the color of the ith node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = [aj, bj] indi
cates that there is a directed edge from node aj to node bj. A valid path in the graph is a sequence of nodes x1 -> x2 -
> x3 -> ... -> xk such that there is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is t
he number of nodes that are colored the most frequently occurring color along that path. Return the largest color valu
e of any valid path in the given graph, or -1 if the graph contains a cycle.
146. Number of Ways to Rearrange Sticks With K Sticks Visible : There are n uniquely-sized sticks whose lengths a
re integers from 1 to n. You want to arrange the sticks such that exactly k sticks are visible from the left. A stick is vi
sible from the left if there are no longer sticks to the left of it. For example, if the sticks are arranged [1,3,2,5,4], then
the sticks with lengths 1, 3, and 5 are visible from the left. Given n and k, return the number of such arrangements.
Since the answer may be large, return it modulo 109 + 7
147. Stone Game VIII : Alice and Bob take turns playing a game, with Alice starting first. There are n stones arrange
d in a row. On each player's turn, while the number of stones is more than one, they will do the following:The score
difference between Alice and Bob is (Alice's score - Bob's score). Alice's goal is to maximize the score difference, a
nd Bob's goal is the minimize the score difference. Given an integer array stones of length n where stones[i] represen
ts the value of the ith stone from the left, return the score difference between Alice and Bob if they both play optimal
ly.
148. Minimum XOR Sum of Two Arrays : You are given two integer arrays nums1 and nums2 of length n. The XO
R sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XO
R nums2[n - 1]) (0-indexed). Rearrange the elements of nums2 such that the resulting XOR sum is minimized. Retur
n the XOR sum after the rearrangement.
149. Minimum Skips to Arrive at Meeting On Time : You are given an integer hoursBefore, the number of hours yo
u have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are
given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition,
you are given an integer speed, which is the speed (in km/h) you will travel at. After you travel road i, you must rest
and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest a
fter traveling the last road because you are already at the meeting. However, you are allowed to skip some rests to be
able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finis
h traveling future roads at different hour marks. Return the minimum number of skips required to arrive at the meeti
ng on time, or -1 if it is impossible.
150. Minimum Cost to Change the Final Value of Expression : You are given a valid boolean expression as a string
expression consisting of the characters '1','0','&' (bitwise AND operator),'|' (bitwise OR operator),'(', and ')'. Return th
e minimum cost to change the final value of the expression. The cost of changing the final value of an expression is t
he number of operations performed on the expression. The types of operations are described as follows: Turn a '1' int
o a '0'. Turn a '0' into a '1'. Turn a '&' into a '|'. Turn a '|' into a '&'.
151. The Earliest and Latest Rounds Where Players Compete : There is a tournament where n players are participati
ng. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (pl
ayer 1 is the first player in the row, player 2 is the second player in the row, etc.). The tournament consists of multipl
e rounds (starting from round number 1). In each round, the ith player from the front of the row competes against the
ith player from the end of the row, and the winner advances to the next round. When the number of players is odd fo
r the current round, the player in the middle automatically advances to the next round. The players numbered firstPla
yer and secondPlayer are the best in the tournament. They can win against any other player before they compete agai
nst each other. If any two other players compete against each other, either of them might win, and thus you may cho
ose the outcome of this round. Given the integers n, firstPlayer, and secondPlayer, return an integer array containing
two values, the earliest possible round number and the latest possible round number in which these two players will
compete against each other, respectively.
152. Count Ways to Build Rooms in an Ant Colony : You are an ant tasked with adding n new rooms numbered 0 to
n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n, prevRoom, where pre
vRoom[i] indicates that you must build room prevRoom[i] before building room i, and these two rooms must be con
nected directly. Room 0 is already built, so prevRoom[0] = -1. The expansion plan is given such that once all the roo
ms are built, every room will be reachable from room 0. You can only build one room at a time, and you can travel f
reely between rooms you have already built only if they are connected. You can choose to build any room as long as
its previous room is already built. Return the number of different orders you can build all the rooms in. Since the ans
wer may be large, return it modulo
153. Minimum Cost to Reach Destination in Time : There is a country of n cities numbered from 0 to n - 1 where all
the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i]
= [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel. There may be multiple roa
ds of differing travel times connecting the same two cities, but no road connects a city to itself. Each time you pass t
hrough a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n w
here passingFees[j] is the amount of dollars you must pay when you pass through city j. In the beginning, you are at
city 0 and want to reach city n - 1 in maxTime minutes or less. The cost of your journey is the summation of passing
fees for each city that you passed through at some moment of your journey (including the source and destination citi
es).Given maxTime, edges, and passingFees, return the minimum cost to complete your journey, or -1 if you cannot
complete it within maxTime minutes.
154. Painting a Grid With Three Different Colors : You are given two integers m and n. Consider an m x n grid wher
e each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted. Return the number
of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, retur
n it modulo
155. Count Number of Special Subsequences : A sequence is special if it consists of a positive number of 0s, followe
d by a positive number of 1s, then a positive number of 2s.Given an array nums (consisting of only integers 0, 1, and
2), return the number of different subsequences that are special. Since the answer may be very large, return it modul
o
156. Number of Ways to Separate Numbers : You wrote down many positive integers in a string called num. Howev
er, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integ
ers was non-decreasing and that no integer had leading zeros. Return the number of possible lists of integers that you
could have written down to get the string num. Since the answer may be large, return it modulo
157. Number of Unique Good Subsequences : You are given a binary string binary. A subsequence of binary is consi
dered good if it is not empty and has no leading zeros (with the exception of "0"). Find the number of unique good s
ubsequences of binary.
158. The Number of Good Subsets : You are given an integer array nums. We call a subset of nums good if its produ
ct can be represented as a product of one or more distinct prime numbers. Return the number of different good subse
ts in nums modulo 109 + 7.
159. Smallest Missing Genetic Value in Each Subtree : There is a family tree rooted at 0 consisting of n nodes numb
ered 0 to n - 1. You are given a 0-indexed integer array parents, where parents[i] is the parent for node i. Since node
0 is the root, parents[0] == -1. There are 105 genetic values, each represented by an integer in the inclusive range [1,
105]. You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for node i. Return an a
rray ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i.
160. Subtree Removal Game with Fibonacci Tree : A Fibonacci tree is a binary tree created using the order function
order(n): order(0) is the empty tree. order(1) is a binary tree with only one node. order(n) is a binary tree that consist
s of a root node with the left subtree as order(n - 2) and the right subtree as order(n - 1). Alice and Bob are playing a
game with a Fibonacci tree with Alice staring first. On each turn, a player selects a node and removes that node and i
ts subtree. The player that is forced to delete root loses. Given the integer n, return true if Alice wins the game or fals
e if Bob wins, assuming both players play optimally.
161. The Score of Students Solving Math Expression : You are given a string s that contains digits 0-9, addition sym
bols '+', and multiplication symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*
2). This expression was given to n elementary school students. The students were instructed to get the answer of the
expression by following this order of operations:You are given an integer array answers of length n, which are the su
bmitted answers of the students in no particular order. You are asked to grade the answers, by following these rules:
Otherwise, if the answer could be interpreted as if the student applied the operators in the wrong order but had correc
t arithmetic, this student will be rewarded 2 points; Return the sum of the points of the students.
162. Partition Array Into Two Arrays to Minimize Sum Difference : You are given an integer array nums of 2 * n int
egers. You need to partition nums into two arrays of length n to minimize the absolute difference of the sums of the
arrays. To partition nums, put each element of nums into one of the two arrays. Return the minimum possible absolu
te difference.
163. Parallel Courses III : You are given an integer n, which indicates that there are n courses labeled from 1 to n. Y
ou are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course pre
vCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given a 0-i
ndexed 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.
164. Check if an Original String Exists Given Two Encoded Strings : An original string, consisting of lowercase Eng
lish letters, can be encoded by the following steps: Arbitrarily split it into a sequence of some number of non-empty
substrings. Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a
numeric string). Concatenate the sequence as the encoded string.Given two encoded strings s1 and s2, consisting of l
owercase English letters and digits 1-9 (inclusive), return true if there exists an original string that could be encoded
as both s1 and s2. Otherwise, return false.
165. Count Fertile Pyramids in a Land : A farmer has a rectangular grid of land with m rows and n columns that can
be divided into unit cells. Each cell is either fertile (represented by a 1) or barren (represented by a 0). All cells outsi
de the grid are considered barren. A pyramidal plot of land can be defined as a set of cells with the following criteria
: The apex of a pyramid is the topmost cell of the pyramid. The height of a pyramid is the number of rows it covers.
Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r <= i <= r + h
- 1 and c - (i - r) <= j <= c + (i - r). An inverse pyramidal plot of land can be defined as a set of cells with similar crit
eria: The apex of an inverse pyramid is the bottommost cell of the inverse pyramid. The height of an inverse pyrami
d is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises
of cells (i, j) where r - h + 1 <= i <= r and c - (r - i) <= j <= c + (r - i).
166. Choose Numbers From Two Arrays in Range : You are given two 0-indexed integer arrays nums1 and nums2 o
f length n. A range [l, r] (inclusive) where 0 <= l <= r < n is balanced if:The sum of the numbers you pick from nums
1 equals to the sum of the numbers you pick from nums2 (the sum is considered to be 0 if you pick no numbers from
an array).Return the number of different ranges that are balanced. Since the answer may be very large, return it mod
ulo 109 + 7.
167. Number of Ways to Divide a Long Corridor : Along a long library corridor, there is a line of seats and decorativ
e plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represent
s 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 se
ction has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two wa
ys are different if there is a position with a room divider installed in the first way but not in the second way. Return t
he number of ways to divide the corridor. Since the answer may be very large, return it modulo 109 + 7. If there is n
o way, return 0.
168. Minimum Difference in Sums After Removal of Elements : You are given a 0-indexed integer array nums consi
sting of 3 * n elements. You are allowed to remove any subsequence of elements of size exactly n from nums. The re
maining 2 * n elements will be divided into two equal parts: The first n elements belonging to the first part and their
sum is sumfirst. The next n elements belonging to the second part and their sum is sumsecond. The difference in su
ms of the two parts is denoted as sumfirst - sumsecond. Return the minimum difference possible between the sums o
f the two parts after the removal of n elements.
169. Minimum Time to Remove All Cars Containing Illegal Goods : You are given a 0-indexed binary string s whic
h represents a sequence of train cars. s[i] = '0' denotes that the ith car does not contain illegal goods and s[i] = '1' den
otes that the ith car does contain illegal goods. As the train conductor, you would like to get rid of all the cars contai
ning illegal goods. You can do any of the following three operations any number of times: Remove a train car from t
he left end (i.e., remove s[0]) which takes 1 unit of time. Remove a train car from the right end (i.e., remove s[s.lengt
h - 1]) which takes 1 unit of time. Remove a train car from anywhere in the sequence which takes 2 units of time. Re
turn the minimum time to remove all the cars containing illegal goods.
170. Maximum AND Sum of Array : You are given an integer array nums of length n and an integer numSlots such
that 2 * numSlots >= n. There are numSlots slots numbered from 1 to numSlots. You have to place all n integers into
the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bit
wise AND of every number with its respective slot. Return the maximum possible AND sum of nums given numSlot
s slots. number.
171. Minimum Time to Finish the Race : You are given a 0-indexed 2D integer array tires where tires[i] = [fi, ri] ind
icates that the ith tire can finish its xth successive lap in fi * ri(x-1) seconds. You are also given an integer changeTi
me and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have a
n unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type)
if you wait changeTime seconds. Return the minimum time to finish the race.
172. Minimum White Tiles After Covering With Carpets : You are given a 0-indexed binary string floor, which repr
esents the colors of tiles on a floor: floor[i] = '0' denotes that the ith tile of the floor is colored black. On the other ha
nd, floor[i] = '1' denotes that the ith tile of the floor is colored white. You are also given numCarpets and carpetLen.
You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that t
he number of white tiles still visible is minimum. Carpets may overlap one another.Return the minimum number of
white tiles still visible.
173. Maximum Value of K Coins From Piles : There are n piles of coins on a table. Each pile consists of a positive n
umber of coins of assorted denominations. In one move, you can choose any coin on top of any pile, remove it, and a
dd it to your wallet. Given a list piles, where piles[i] is a list of integers denoting the composition of the ith pile from
top to bottom, and a positive integer k, return the maximum total value of coins you can have in your wallet if you c
hoose exactly k coins optimally.
174. Maximum Cost of Trip With K Highways : A series of highways connect n cities numbered from 0 to n - 1. Yo
u are given a 2D integer array highways where highways[i] = [city1i, city2i, tolli] indicates that there is a highway th
at connects city1i and city2i, allowing a car to go from city1i to city2i and vice versa for a cost of tolli. You are also
given an integer k. You are going on a trip that crosses exactly k highways. You may start at any city, but you may o
nly visit each city at most once during your trip. Return the maximum cost of your trip. If there is no trip that meets t
he requirements, return -1.
175. Total Appeal of A String : The appeal of a string is the number of distinct characters found in the string. Given
a string s, return the total appeal of all of its substrings. A substring is a contiguous sequence of characters within a s
tring.
176. Make Array Non-decreasing or Non-increasing : You are given a 0-indexed integer array nums. In one operatio
n, you can: Choose an index i in the range 0 <= i < nums.length. Set nums[i] to nums[i] + 1 or nums[i] - 1 Return the
minimum number of operations to make nums non-decreasing or non-increasing.
177. Check if There Is a Valid Parentheses String Path : A parentheses string is a non-empty string consisting only o
f '(' and ')'. It is valid if any of the following conditions is true: You are given an m x n matrix of parentheses grid. A
valid parentheses string path in the grid is a path satisfying all of the following conditions: The path starts from the u
pper left cell (0, 0). The path ends at the bottom-right cell (m - 1, n - 1). The path only ever moves down or right. Th
e resulting parentheses string formed by the path is valid. Return true if there exists a valid parentheses string path in
the grid. Otherwise, return false.
178. Substring With Largest Variance : The variance of a string is defined as the largest difference between the num
ber of occurrences of any 2 characters present in the string. Note the two characters may or may not be the same. Giv
en a string s consisting of lowercase English letters only, return the largest variance possible among all substrings of
s. A substring is a contiguous sequence of characters within a string.
179. Selling Pieces of Wood : You are given two integers m and n that represent the height and width of a rectangula
r piece of wood. You are also given a 2D integer array prices, where prices[i] = [hi, wi, pricei] indicates you can sell
a rectangular piece of wood of height hi and width wi for pricei dollars. To cut a piece of wood, you must make a ve
rtical or horizontal cut across the entire height or width of the piece to split it into two smaller pieces. After cutting a
piece of wood into some number of smaller pieces, you can sell pieces according to prices. You may sell multiple pi
eces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you
cannot rotate a piece to swap its height and width. Return the maximum money you can earn after cutting an m x n p
iece of wood.
180. Minimum Flips in Binary Tree to Get Result :You are given the root of a binary tree with the following properti
es: Non-leaf nodes have either the value 2, 3, 4, or 5, representing the boolean operations OR, AND, XOR, and NOT
, respectively.Otherwise, evaluate the node's children and apply the boolean operation of its value with the children's
evaluations.Return the minimum number of operations that need to be performed such that the evaluation of root yie
lds result. It can be shown that there is always a way to achieve result.
181. Number of Distinct Roll Sequences : You are given an integer n. You roll a fair 6-sided dice n times. Determine
the total number of distinct sequences of rolls possible such that the following conditions are satisfied:There is at lea
st a gap of 2 rolls between equal valued rolls. More formally, if the value of the ith roll is equal to the value of the jth
roll, then abs(i - j) > 2.Return the total number of distinct sequences possible. Since the answer may be very large, r
eturn it modulo 109 + 7.
182. Maximum Score Of Spliced Array : You are given two 0-indexed integer arrays nums1 and nums2, both of leng
th n.You can choose two integers left and right where 0 <= left <= right < n and swap the subarray nums1[left...right
] with the subarray nums2[left...right]. You may choose to apply the mentioned operation once or not do anything.T
he score of the arrays is the maximum of sum(nums1) and sum(nums2), where sum(arr) is the sum of all the element
s in the array arr.Return the maximum possible score.
183. Number of Increasing Paths in a Grid : You are given an m x n integer matrix grid, where you can move from a
cell to any adjacent cell in all 4 directions. Return the number of strictly increasing paths in the grid such that you ca
n start from any cell and end at any cell. Since the answer may be very large, return it modulo 109 + 7. Two paths ar
e considered different if they do not have exactly the same sequence of visited cells.
184. Count the Number of Ideal Arrays : You are given two integers n and maxValue, which are used to describe an
ideal array. A 0-indexed integer array arr of length n is considered ideal if the following conditions hold: Every arr[i]
is a value from 1 to maxValue, for 0 <= i < n. Every arr[i] is divisible by arr[i - 1], for 0 < i < n. Return the number
of distinct ideal arrays of length n. Since the answer may be very large, return it modulo 109 + 7

You might also like