question
stringlengths
58
4.29k
label
class label
3 classes
there tree ie connect undirected graph cycle consist n node number 0 n 1 exactly n 1 edge each node value associate root tree node 0to represent tree give integer array num 2D array edge each numsi represent ith node value edgesj uj vj represent edge node uj vj treeTwo value x y coprime gcdx y 1 gcdx y great common divisor x yAn ancestor node node short path node root a node consider ancestor itselfReturn array ans size n ansi close ancestor node numsi numsansi coprime 1 ancestor Example 1input num 2332 edge 011213output 1001explanation in figure node value parenthese Node 0 coprime ancestor Node 1 ancestor node 0 their value coprime gcd23 1 Node 2 ancestor nod 1 0 Node 1s value coprime gcd33 3 node 0s value gcd23 1 node 0 close valid ancestor Node 3 ancestor nod 1 0 it coprime node 1 gcd32 1 node 1 close valid ancestorexample 2input num 561023615 edge 010213142526output 1010001 Constraintsnumslength n1 numsi 501 n 105edgeslength n 1edgesjlength 20 uj vj nuj vj
1graph
you give string word1 word2 merge string add letter alternate order start word1 if string long append additional letter end merge stringreturn merge string example 1input word1 abc word2 pqroutput apbqcrexplanation the merged string merge soword1 b cword2 p q rmerged p b q c rExample 2input word1 ab word2 pqrsoutput apbqrsexplanation notice word2 long rs append endword1 b word2 p q r smerged p b q r sExample 3input word1 abcd word2 pqoutput apbqcdexplanation Notice word1 long cd append endword1 b c dword2 p q merge p b q c d constraints1 word1length word2length 100word1 word2 consist lowercase english letter
2string
you give 0indexed integer array num multiplier size n m respectively n mYou begin score 0 you want perform exactly m operation on ith operation 0indexed willchoose integer x start end array numsAdd multipliersi x scoreNote multipliers0 correspond operation multipliers1 second operation onRemove x numsreturn maximum score perform m operation Example 1input num 123 multiplier 321output 14explanation an optimal solution follow Choose end 123 add 3 3 9 score Choose end 12 add 2 2 4 score Choose end 1 add 1 1 1 scorethe total score 9 4 1 14example 2input num 533271 multiplier 105346output 102explanation an optimal solution follow Choose start 533271 add 5 10 50 score Choose start 33271 add 3 5 15 score Choose start 3271 add 3 3 9 score Choose end 271 add 1 4 4 score Choose end 27 add 7 6 42 score the total score 50 15 9 4 42 102 Constraintsn numslengthm multiplierslength1 m 300 m n 1051000 numsi multipliersi 1000
0array
you give string word1 word2 you want construct string follow mannerchoose nonempty subsequence subsequence1 word1Choose nonempty subsequence subsequence2 word2concatenate subsequence subsequence1 subsequence2 stringreturn length long palindrome construct describe manner if palindrome construct return 0A subsequence stre s string delete possibly character s change order remain charactersA palindrome string read forward backward Example 1input word1 cacb word2 cbbaoutput 5explanation Choose ab word1 cba word2 abcba palindromeExample 2Input word1 ab word2 abOutput 3explanation Choose ab word1 word2 aba palindromeExample 3input word1 aa word2 bbOutput 0explanation you construct palindrome describe method return 0 constraints1 word1length word2length 1000word1 word2 consist lowercase english letter
2string
you like dessert prepare buy ingredient you n ice cream base flavor m type topping choose you follow rule make dessertThere exactly ice cream baseyou add type top topping allthere type toppingyou give inputsbasecost integer array length n basecostsi represent price ith ice cream base flavortoppingcost integer array length m toppingcostsi price ith toppingtarget integer represent target price dessertYou want dessert total cost close target possiblereturn close possible cost dessert target if multiple return low Example 1input basecost 17 toppingcost 34 target 10output 10explanation consider follow combination 0indexed choose base 1 cost 7 take 1 topping 0 cost 1 x 3 3 take 0 top 1 cost 0 x 4 0total 7 3 0 10example 2input basecost 23 toppingcost 45100 target 18output 17explanation consider follow combination 0indexed choose base 1 cost 3 take 1 topping 0 cost 1 x 4 4 take 2 top 1 cost 2 x 5 10 take 0 top 2 cost 0 x 100 0total 3 4 10 0 17 you dessert total cost 18example 3input basecost 310 toppingcost 25 target 9output 8explanation it possible dessert cost 8 10 return 8 low cost Constraintsn baseCostslengthm toppingcostslength1 n m 101 baseCostsi toppingcostsi 1041 target 104
0array
you give array integer nums1 nums2 possibly different length the value array 1 6 inclusivein operation change integer value arrays value 1 6 inclusivereturn minimum number operation require sum value nums1 equal sum value nums2 return 1 possible sum array equal Example 1input nums1 123456 nums2 112222output 3explanation you sum nums1 nums2 equal 3 operation all index 0indexe change nums20 6 nums1 123456 nums2 612222 Change nums15 1 nums1 123451 nums2 612222 Change nums12 2 nums1 122451 nums2 612222example 2input nums1 1111111 nums2 6output 1explanation there way decrease sum nums1 increase sum nums2 equalexample 3input nums1 66 nums2 1output 3explanation you sum nums1 nums2 equal 3 operation all index 0indexe change nums10 2 nums1 26 nums2 1 Change nums11 2 nums1 22 nums2 1 Change nums20 4 nums1 22 nums2 4 Constraints1 nums1length nums2length 1051 nums1i nums2i 6
0array
there n car travel different speed direction onelane road you give array car length n carsi positioni speedi representspositioni distance ith car begin road meter it guarantee positioni positioni1speedi initial speed ith car meter secondFor simplicity car consider point move number line two car collide occupy position once car collide car unite form single car fleet the car form fleet position speed initial speed slow car fleetreturn array answer answeri time second ith car collide car 1 car collide car Answers 105 actual answer accept Example 1input car 12214372output 100000100000300000100000explanation after exactly second car collide second car form car fleet speed 1 ms after exactly 3 second car collide fourth car form car fleet speed 2 msexample 2input car 34546391output 200000100000150000100000 Constraints1 carslength 1051 positioni speedi 106positioni positioni1
0array
you give integer x y represent current location Cartesian grid x y you give array point pointsi ai bi represent point exist ai bi a point valid share xcoordinate ycoordinate locationReturn index 0indexed valid point small Manhattan distance current location if multiple return valid point small index if valid point return 1the Manhattan distance point x1 y1 x2 y2 absx1 x2 absy1 y2 Example 1input x 3 y 4 point 1231242344output 2explanation of point 31 24 44 valid of valid point 24 44 small Manhattan distance current location distance 1 24 small index return 2example 2Input x 3 y 4 point 34output 0explanation the answer allow location current locationExample 3input x 3 y 4 point 23output 1explanation there valid point Constraints1 pointslength 104pointsilength 21 x y ai bi 104
0array
the beauty string difference frequency frequent frequent charactersFor example beauty abaacc 3 1 2given string s return sum beauty substring Example 1input s aabcboutput 5explanation the substring nonzero beauty aabaabcaabcbabcbbcb beauty equal 1example 2input s aabcbaaoutput 17 Constraints1 slength 500s consist lowercase english letter
2string
you give undirected graph define integer n number node 2D integer array edge edge graph edgesi ui vi indicate undirected edge ui vi you give integer array querieslet incidenta b define number edge connect node bThe answer jth query number pair node b satisfy follow conditionsa bincidenta b queriesjreturn array answer answerslength querieslength answersj answer jth queryNote multiple edge nod Example 1input n 4 edge 1224132321 query 23output 65explanation the calculation incidenta b show table abovethe answer query follow answers0 6 all pair incidenta b value great 2 answers1 5 all pair 3 4 incidenta b value great 3example 2input n 5 edge 1515342513512325 query 12345output 1010986 Constraints2 n 2 1041 edgeslength 1051 ui vi nui vi1 querieslength 200 queriesj edgeslength
1graph
give binary string s lead zero return true s contain contiguous segment one otherwise return false example 1input s 1001output falseexplanation the one form contiguous segmentexample 2input s 110output true Constraints1 slength 100si 0 1s0 1
2string
you give integer array nums integer limit goal the array num interesting property absnumsi limitreturn minimum number element need add sum array equal goal the array maintain property absnumsi limitNote absx equal x x 0 x example 1input num 111 limit 3 goal 4output 2explanation you add 2 3 sum array 1 1 1 2 3 4example 2input num 11091 limit 100 goal 0output 1 Constraints1 numslength 1051 limit 106limit numsi limit109 goal 109
0array
there undirecte weight connected graph you give positive integer n denote graph n node label 1 n array edge edgesi ui vi weighti denote edge node ui vi weight equal weightiA path node start node end sequence node z0 z1 z2 zk z0 start zk end edge zi zi1 0 k1the distance path sum weight edge path let distancetolastnodex denote short distance path node n node x a restricted path path satisfie distanceToLastNodezi distancetolastnodezi1 0 k1return number restrict path node 1 node n since number large return modulo 109 7 Example 1input n 5 edge 1231332311425223515410output 3explanation each circle contain node number black distancetolastnode value blue the restrict path are1 1 2 52 1 2 3 53 1 3 5example 2input n 7 edge 131412734253561672753264output 1explanation each circle contain node number black distancetolastnode value blue the restricted path 1 3 7 constraints1 n 2 104n 1 edgeslength 4 104edgesilength 31 ui vi nui vi1 weighti 105There edge nodesThere path node
1graph
you give array num integer k the XOR segment leave right leave right xor element index leave right inclusive numsleft XOR numsleft1 XOR XOR numsrightreturn minimum number element change array XOR segment size k equal zero Example 1input num 12030 k 1Output 3explanation Modify array 12030 00000example 2input num 345217347 k 3output 3explanation Modify array 345217347 347347347example 3input num 124125126 k 3output 3explanation Modify array 124125126 123123123 Constraints1 k numslength 20000 numsi 210
0array
you give string s1 s2 equal length a string swap operation choose index stre necessarily different swap character indicesreturn true possible string equal perform string swap exactly string otherwise return false Example 1input s1 bank s2 kanbOutput trueexplanation for example swap character character s2 bankExample 2input s1 attack s2 defendoutput falseexplanation it impossible equal string swapexample 3input s1 kelb s2 kelboutput trueexplanation the string equal string swap operation require Constraints1 s1length s2length 100s1length s2lengths1 s2 consist lowercase english letter
2string
there undirecte star graph consist n node label 1 n a star graph graph center node exactly n 1 edge connect center node nodeyou give 2D integer array edge edgesi ui vi indicate edge node ui vi Return center give star graph Example 1input edge 122342output 2explanation as show figure node 2 connect node 2 centerExample 2input edge 12511314output 1 Constraints3 n 105edgeslength n 1edgesilength 21 ui vi nui viThe give edge represent valid star graph
1graph
there school class student class have final exam you give 2D integer array classes classesi passi totali you know ith class totali total student passi number student pass examyou give integer extrastudent there extrastudent brilliant student guarantee pass exam class assign you want assign extrastudent student class way maximize average pass ratio classesthe pass ratio class equal number student class pass exam divide total number student class the average pass ratio sum pass ratio class divide number classesReturn maximum possible average pass ratio assign extrastudent student Answers 105 actual answer accept Example 1input class 123522 extrastudent 2output 078333explanation you assign extra student class the average pass ratio equal 34 35 22 3 078333example 2input class 243945210 extrastudent 4output 053485 Constraints1 classeslength 105classesilength 21 passi totali 1051 extrastudent 105
0array
you give array integer num 0indexed integer kThe score subarray j define minnumsi numsi1 numsj j 1 a good subarray subarray k jReturn maximum possible score good subarray Example 1input num 143745 k 3Output 15explanation the optimal subarray 1 5 score min43745 511 3 5 15 Example 2input num 55454111 k 0output 20explanation the optimal subarray 0 4 score min55454 401 4 5 20 constraints1 numslength 1051 numsi 2 1040 k numslength
0array
give alphanumeric string s return second large numerical digit appear s 1 existan alphanumeric string string consist lowercase English letter digit Example 1input s dfa12321afdoutput 2explanation the digit appear s 1 2 3 the second large digit 2example 2input s abc1111output 1explanation the digit appear s 1 there second large digit Constraints1 slength 500s consist lowercase english letter andor digit
2string
you give integer array coin length n represent n coin the value ith coin coinsi you value x choose n coin value sum xReturn maximum number consecutive integer value coin start include 0note multiple coin value Example 1input coin 13output 2explanation you follow value 0 1 1you 2 consecutive integer value start 0example 2input coin 1114output 8explanation you follow value 0 1 1 2 11 3 111 4 4 5 41 6 411 7 4111you 8 consecutive integer value start 0example 3input num 141031output 20 Constraintscoinslength n1 n 4 1041 coinsi 4 104
0array
you give num array positive integer size 2 n you perform n operation arrayIn ith operation 1indexed willchoose element x yreceive score gcdx yRemove x y numsReturn maximum score receive perform n operationsthe function gcdx y great common divisor x y Example 1input num 12output 1explanation the optimal choice operation is1 gcd1 2 1example 2input num 3468output 11explanation the optimal choice operation is1 gcd3 6 2 gcd4 8 3 8 11example 3input num 123456output 14explanation the optimal choice operation is1 gcd1 5 2 gcd2 4 3 gcd3 6 1 4 9 14 constraints1 n 7numslength 2 n1 numsi 106
0array
give array positive integer num return maximum possible sum ascend subarray numsA subarray define contiguous sequence number arrayA subarray numsl numsl1 numsr1 numsr ascend l r numsi numsi1 note subarray size 1 ascend Example 1input num 10203051050output 65explanation 51050 ascend subarray maximum sum 65Example 2input num 1020304050output 150explanation 1020304050 ascend subarray maximum sum 150example 3input num 12171513101112output 33explanation 101112 ascend subarray maximum sum 33 Constraints1 numslength 1001 numsi 100
0array
you give 2D integer array order ordersi pricei amounti orderTypei denote amounti order place type orderTypei price pricei the orderTypei is0 batch buy order or1 batch sell ordersnote ordersi represent batch amounti independent order price order type all order represent ordersi place order represent ordersi1 valid iThere backlog consist order execute the backlog initially when order place follow happensIf order buy order look sell order small price backlog if sell order price small equal current buy order price match execute sell order remove backlog Else buy order add backlogvice versa order sell order look buy order large price backlog if buy order price large equal current sell order price match execute buy order remove backlog else sell order add backlogReturn total order backlog place order input since number large return modulo 109 7 Example 1input order 1050152125113040output 6explanation here happen order 5 order type buy price 10 place there sell order 5 order add backlog 2 order type sell price 15 place there buy order price large equal 15 2 order add backlog 1 order type sell price 25 place there buy order price large equal 25 backlog order add backlog 4 order type buy price 30 place the 2 order match 2 sell order price 15 2 sell order remove backlog the 3rd order match sell order price 25 sell order remove backlog then sell order backlog 4th order add backlogfinally backlog 5 buy order price 10 1 buy order price 30 so total number order backlog 6Example 2input order 710000000001153059999999950511output 999999984explanation here happen order 109 order type sell price 7 place there buy order 109 order add backlog 3 order type buy price 15 place they match 3 sell order price 7 3 sell order remove backlog 999999995 order type buy price 5 place the price sell order 7 999999995 order add backlog 1 order type sell price 5 place it match buy order high price 5 buy order remove backlogfinally backlog 10000000003 sell order price 7 9999999951 buy order price 5 so total number order 1999999991 equal 999999984 109 7 Constraints1 orderslength 105ordersilength 31 pricei amounti 109ordertypei 0 1
0array
give 0indexed integer array num integer low high return number nice pairsA nice pair pair j 0 j numslength low numsi XOR numsj high Example 1input num 1427 low 2 high 6output 6explanation all nice pair j follow 0 1 nums0 XOR nums1 5 0 2 nums0 XOR nums2 3 0 3 nums0 XOR nums3 6 1 2 nums1 XOR nums2 6 1 3 nums1 XOR nums3 3 2 3 nums2 XOR nums3 5example 2input num 98421 low 5 high 14output 8explanation all nice pair j follow 0 2 nums0 XOR nums2 13 0 3 nums0 XOR nums3 11 0 4 nums0 XOR nums4 8 1 2 nums1 XOR nums2 12 1 3 nums1 XOR nums3 10 1 4 nums1 XOR nums4 9 2 3 nums2 XOR nums3 6 2 4 nums2 XOR nums4 5 constraints1 numslength 2 1041 numsi 2 1041 low high 2 104
0array
you give string word consist digits lowercase English lettersyou replace nondigit character space for example a123bc34d8ef34 123 34 8 34 Notice leave integer separate space 123 34 8 34return number different integer perform replacement operation wordtwo integer consider different decimal representation lead zero different Example 1input word a123bc34d8ef34output 3explanation the different integer 123 34 8 Notice 34 count onceExample 2input word leet1234code234Output 2example 3Input word a1b01c001output 1explanation the integer 1 01 001 represent integer becausethe lead zero ignore compare decimal value Constraints1 wordlength 1000word consist digits lowercase english letter
2string
you give integer n you initially permutation perm size n permi 0indexedin operation create new array arr iIf 2 0 arri permi 2if 2 1 arri permn 2 1 2you assign arr permReturn minimum nonzero number operation need perform perm return permutation initial value Example 1input n 2output 1explanation perm 01 initiallyAfter 1st operation perm 01So take 1 operationexample 2input n 4Output 2Explanation perm 0123 initiallyAfter 1st operation perm 0213after 2nd operation perm 0123So take 2 operationsexample 3input n 6output 4 Constraints2 n 1000n
0array
you give coordinate string represent coordinate square chessboard below chessboard referencereturn true square white false square blackthe coordinate represent valid chessboard square the coordinate letter number second Example 1input coordinate a1output falseexplanation from chessboard square coordinate a1 black return falseexample 2input coordinate h3output trueexplanation from chessboard square coordinate h3 white return trueExample 3input coordinate c7output false Constraintscoordinateslength 2a coordinates0 h1 coordinates1 8
2string
you give array num consist nonnegative integer let define revx reverse nonnegative integer x for example rev123 321 rev120 21 a pair indice j nice satisfie follow conditions0 j numslengthnumsi revnumsj numsj revnumsiReturn number nice pair index since number large return modulo 109 7 Example 1input num 4211197output 2explanation the pair 03 42 rev97 42 79 121 97 rev42 97 24 121 12 11 rev1 11 1 12 1 rev11 1 11 12example 2input num 1310352476output 4 constraints1 numslength 1050 numsi 109
0array
there donut shop bake donut batch batchsize they rule serve donut batch serve donut batch you give integer batchsize integer array group groupsi denote group groupsi customer visit shop each customer exactly donutWhen group visit shop customer group serve serve follow group a group happy fresh donut that customer group receive donut leave previous groupyou freely rearrange ordering group return maximum possible number happy group rearrange group Example 1input batchsize 3 group 123456output 4explanation you arrange group 624513 then 1st 2nd 4th 6th group happyExample 2input batchsize 4 group 13252216output 4 constraints1 batchSize 91 groupslength 301 groupsi 109
0array
you give log user action LeetCode integer k the log represent 2D integer array log logsi IDi timei indicate user IDi perform action minute timeiMultiple user perform action simultaneously single user perform multiple action minutethe user active minute UAM give user define number unique minute user perform action LeetCode A minute count multiple action occur ityou calculate 1indexed array answer size k j 1 j k answerj number user UAM equal jReturn array answer describe Example 1input log 0512020513 k 5output 02000explanationthe user ID0 perform action minute 5 2 5 hence UAM 2 minute 5 count oncethe user ID1 perform action minute 2 3 hence UAM 2since user UAM 2 answer2 2 remain answerj value 0example 2input log 112223 k 4Output 1100explanationthe user ID1 perform single action minute 1 hence UAM 1the user ID2 perform action minute 2 3 hence UAM 2there user UAM 1 UAM 2hence answer1 1 answer2 1 remain value 0 Constraints1 logslength 1040 IDi 1091 timei 105k range the maximum UAM user 105
0array
you give positive integer array nums1 nums2 length nthe absolute sum difference array nums1 nums2 define sum nums1i nums2i 0 n 0indexedyou replace element nums1 element nums1 minimize absolute sum differencereturn minimum absolute sum difference replace element array nums1 since answer large return modulo 109 7x define asx x 0 orx x 0 example 1input nums1 175 nums2 235output 3explanation there possible optimal solution replace second element 175 115 replace second element 175 155both yield absolute sum difference 12 13 53 55 3example 2input nums1 246810 nums2 246810output 0explanation nums1 equal nums2 replacement need this result absolute sum difference 0example 3input nums1 1104427 nums2 935174output 20explanation replace element second 1104427 10104427this yield absolute sum difference 109 103 45 41 27 74 20 Constraintsn nums1lengthn nums2length1 n 1051 nums1i nums2i 105
0array
you give array num consist positive integersthe GCD sequence number define great integer divide number sequence evenlyfor example GCD sequence 4616 2A subsequence array sequence form remove element possibly arrayfor example 2510 subsequence 121241510return number different gcd nonempty subsequence num Example 1input num 6103output 5explanation the figure show nonempty subsequence GCDsThe different gcd 6 10 3 2 1example 2input num 5154056output 7 Constraints1 numslength 1051 numsi 2 105
0array
there function signFuncx returns1 x positive1 x negative0 x equal 0you give integer array num let product product value array numsReturn signfuncproduct Example 1input num 1234321output 1explanation the product value array 144 signfunc144 1example 2input num 15023output 0explanation the product value array 0 signFunc0 0example 3input num 11111output 1explanation the product value array 1 signFunc1 1 Constraints1 numslength 1000100 numsi 100
0array
there n friend play game the friend sit circle number 1 n clockwise order more formally move clockwise ith friend bring i1th friend 1 n move clockwise nth friend bring 1st friendthe rule game followsStart 1st friendCount k friend clockwise direction include friend start the counting wrap circle count friend oncethe friend count leave circle lose gameIf friend circle step 2 start friend immediately clockwise friend lose repeatElse friend circle win gamegiven number friend n integer k return winner game Example 1input n 5 k 2output 3explanation here step game1 start friend 12 Count 2 friend clockwise friend 1 23 friend 2 leave circle Next start friend 34 Count 2 friend clockwise friend 3 45 Friend 4 leave circle Next start friend 56 Count 2 friend clockwise friend 5 17 friend 1 leave circle Next start friend 38 Count 2 friend clockwise friend 3 59 friend 5 leave circle only friend 3 leave winnerexample 2input n 6 k 5output 1explanation the friend leave order 5 4 6 2 3 the winner friend 1 Constraints1 k n 500 Follow upcould solve problem linear time constant space
0array
there 3 lane road length n consist n 1 point label 0 n a frog start point 0 second lane want jump point n however obstacle wayyou give array obstacle length n 1 obstaclesi range 0 3 describe obstacle lane obstaclesi point if obstaclesi 0 obstacle point there obstacle 3 lane pointfor example obstacles2 1 obstacle lane 1 point 2the frog travel point point 1 lane obstacle lane point 1 to avoid obstacle frog perform jump jump lane adjacent point obstacle new laneFor example frog jump lane 3 point 3 lane 1 point 3return minimum number jump frog need reach lane point n start lane 2 point 0note there obstacle point 0 n example 1input obstacle 01230output 2 Explanation the optimal solution show arrow there 2 jump red arrowsNote frog jump obstacle make jump show point 2example 2input obstacle 011330output 0explanation there obstacle lane 2 no jump requiredExample 3input obstacle 021030output 2explanation the optimal solution show arrow there 2 jump Constraintsobstacleslength n 11 n 5 1050 obstaclesi 3obstacles0 obstaclesn 0
0array
you give integer array num 0indexed in operation choose element array increment 1for example num 123 choose increment nums1 num 133return minimum number operation need num strictly increasingan array num strictly increase numsi numsi1 0 numslength 1 an array length 1 trivially strictly increase Example 1input num 111output 3explanation you follow operations1 Increment nums2 num 1122 increment nums1 num 1223 Increment nums2 num 123example 2input num 15241output 14example 3input num 8Output 0 Constraints1 numslength 50001 numsi 104
0array
you give array point pointsi xi yi coordinate ith point 2D plane Multiple point coordinatesyou give array query queriesj xj yj rj describe circle center xj yj radius rjfor query queriesj compute number point inside jth circle Points border circle consider insidereturn array answer answerj answer jth query Example 1input point 13335322 query 231431112output 322explanation the point circle show abovequeries0 green circle queries1 red circle queries2 blue circleExample 2input point 1122334455 query 122222432433output 2324explanation the point circle show abovequeries0 green queries1 red queries2 blue queries3 purple Constraints1 pointslength 500pointsilength 20 xi yi 5001 querieslength 500queriesjlength 30 xj yj 5001 rj 500All coordinate integer Follow could find answer query well complexity on
0array
you give sorted array num n nonnegative integer integer maximumBit you want perform follow query n timesfind nonnegative integer k 2maximumbit nums0 XOR nums1 XOR XOR numsnumslength1 XOR k maximized k answer ith queryRemove element current array numsReturn array answer answeri answer ith query Example 1input num 0113 maximumbit 2output 0323explanation the query answer follows1st query num 0113 k 0 0 xor 1 xor 1 xor 3 xor 0 32nd query num 011 k 3 0 xor 1 xor 1 xor 3 33rd query num 01 k 2 0 xor 1 xor 2 34th query num 0 k 3 0 xor 3 3example 2input num 2347 maximumbit 3output 5265explanation the query answer follows1st query num 2347 k 5 2 xor 3 xor 4 xor 7 XOR 5 72nd query num 234 k 2 2 xor 3 xor 4 XOR 2 73rd query num 23 k 6 2 xor 3 xor 6 74th query num 2 k 5 2 xor 5 7example 3input num 012257 maximumbit 3output 436467 Constraintsnumslength n1 n 1051 maximumBit 200 numsi 2maximumbitnums sort ascending order
0array
you give string s 0indexed you ask perform follow operation s sorted stringfind large index 1 slength si si 1find large index j j slength sk si 1 possible value k range j inclusiveSwap character indice 1 jReverse suffix start index iReturn number operation need string sort since answer large return modulo 109 7 Example 1input s cbaoutput 5explanation the simulation go followsOperation 1 i2 j2 Swap s1 s2 scab reverse suffix start 2 now scaboperation 2 i1 j2 Swap s0 s2 sbac reverse suffix start 1 now sbcaoperation 3 i2 j2 Swap s1 s2 sbac reverse suffix start 2 now sbacoperation 4 i1 j1 Swap s0 s1 sabc reverse suffix start 1 now sacboperation 5 i2 j2 Swap s1 s2 sabc reverse suffix start 2 now sabcexample 2input s aabaaoutput 2explanation the simulation go followsoperation 1 i3 j4 Swap s2 s4 saaaab reverse substring start 3 now saaabaoperation 2 i4 j4 Swap s3 s4 saaaab reverse substring start 4 now saaaab Constraints1 slength 3000s consists lowercase english letter
2string
a pangram sentence letter English alphabet appear onceGiven string sentence contain lowercase english letter return true sentence pangram false Example 1input sentence thequickbrownfoxjumpsoverthelazydogoutput trueexplanation sentence contain letter english alphabetexample 2input sentence leetcodeoutput false Constraints1 sentencelength 1000sentence consists lowercase english letter
2string
it swelter summer day boy want buy ice cream barsAt store n ice cream bar you give array cost length n costsi price ith ice cream bar coin the boy initially coin coin spend want buy ice cream bar possible return maximum number ice cream bar boy buy coin coinsNote the boy buy ice cream bar order example 1input cost 13241 coin 7output 4explanation the boy buy ice cream bar index 0124 total price 1 3 2 1 7example 2input cost 1068778 coin 5output 0explanation the boy afford ice cream barsexample 3input cost 163125 coin 20output 6explanation the boy buy ice cream bar total price 1 6 3 1 2 5 18 Constraintscostslength n1 n 1051 costsi 1051 coin 108
0array
you give n task label 0 n 1 represent 2D integer array task tasksi enqueueTimei processingtimei mean ith task available process enqueuetimei processingtimei finish processingyou singlethreaded cpu process task time act follow wayif CPU idle available task process CPU remain idleif CPU idle available task CPU choose short processing time if multiple task short processing time choose task small indexonce task start cpu process entire task stoppingThe CPU finish task start new instantlyreturn order cpu process task Example 1input task 12243241output 0231explanation the event follow at time 1 task 0 available process available task 0 also time 1 idle CPU start process task 0 available task at time 2 task 1 available process available task 1 at time 3 task 2 available process available task 1 2 also time 3 CPU finish task 0 start process task 2 short available task 1 at time 4 task 3 available process available task 1 3 at time 5 CPU finish task 2 start process task 3 short available task 1 at time 6 CPU finish task 3 start process task 1 available task at time 10 CPU finish task 1 idleExample 2input task 710712757472output 43201explanation the event follow at time 7 task available available task 01234 also time 7 idle CPU start process task 4 available task 0123 at time 9 CPU finish task 4 start process task 3 available task 012 at time 13 CPU finish task 3 start process task 2 available task 01 at time 18 CPU finish task 2 start process task 0 available task 1 at time 28 CPU finish task 0 start process task 1 available task at time 40 CPU finish task 1 idle Constraintstaskslength n1 n 1051 enqueueTimei processingTimei 109
0array
the XOR sum list bitwise XOR element if list contain element XOR sum equal elementfor example XOR sum 1234 equal 1 xor 2 xor 3 xor 4 4 XOR sum 3 equal 3you give 0indexe array arr1 arr2 consist nonnegative integersconsider list contain result arr1i and arr2j bitwise and j pair 0 arr1length 0 j arr2lengthreturn XOR sum aforementione list Example 1input arr1 123 arr2 65output 0explanation the list 1 and 6 1 and 5 2 and 6 2 and 5 3 and 6 3 and 5 012021the XOR sum 0 xor 1 xor 2 xor 0 xor 2 xor 1 0example 2input arr1 12 arr2 4output 4explanation the list 12 and 4 4 the XOR sum 4 Constraints1 arr1length arr2length 1050 arr1i arr2j 109
0array
the frequency element number time occur arrayyou give integer array num integer k in operation choose index num increment element index 1return maximum possible frequency element perform k operation Example 1input num 124 k 5output 3explanation Increment element times second element time num 4444 frequency 3example 2input num 14813 k 5output 2explanation there multiple optimal solution increment element time num 44813 4 frequency 2 increment second element time num 18813 8 frequency 2 Increment element time num 141313 13 frequency 2example 3input num 396 k 2output 1 Constraints1 numslength 1051 numsi 1051 k 105
0array
a string consider beautiful satisfie follow conditionsEach 5 english vowel e o u appear itThe letter sort alphabetical order ie es es etcFor example string aeiou aaaaaaeiiiioou consider beautiful uaeio aeoiu aaaeeeooo beautifulGiven string word consist english vowel return length long beautiful substre word if substre exist return 0A substre contiguous sequence character string example 1input word aeiaaioaaaaeiiiiouuuooaauuaeiuoutput 13explanation the long beautiful substre word aaaaeiiiiouuu length 13example 2input word aeeeiiiioooauuuaeiouOutput 5explanation the long beautiful substre word aeiou length 5example 3input word aOutput 0explanation there beautiful substre return 0 Constraints1 wordlength 5 105word consist character e o u
2string
you want build n new building city the new building build line label 1 nHowever city restriction height new buildingsthe height building nonnegative integerthe height building 0the height difference adjacent building exceed 1additionally city restriction maximum height specific building these restriction give 2d integer array restriction restrictionsi idi maxHeighti indicate build idi height equal maxheightiit guarantee building appear restriction build 1 restrictionsreturn maximum possible height tall building Example 1input n 5 restriction 2141output 2explanation the green area image indicate maximum allow height buildingwe build building height 01212 tall building height 2example 2Input n 6 restriction output 5explanation the green area image indicate maximum allow height buildingwe build building height 012345 tall building height 5Example 3Input n 10 restriction 532574103output 5explanation the green area image indicate maximum allow height buildingwe build building height 0123344543 tall building height 5 Constraints2 n 1090 restrictionslength minn 1 1052 idi nidi unique0 maxheighti 109
0array
you give 0indexed string s lowercase english letter indice digit odd indicesthere function shiftc x c character x digit return xth character cFor example shifta 5 f shiftx 0 xFor odd index want replace digit si shiftsi1 siReturn s replace digit it guarantee shiftsi1 si exceed z Example 1input s a1c1e1output abcdefexplanation the digit replace follow s1 shifta1 b s3 shiftc1 d s5 shifte1 fExample 2input s a1b2c3d4eOutput abbdcfdheexplanation the digit replace follow s1 shifta1 b s3 shiftb2 d s5 shiftc3 f s7 shiftd4 h Constraints1 slength 100s consist lowercase english letter digitsshiftsi1 si z odd index
2string
you give array positive integer arr Perform operation possibly arr satisfie conditionsThe value element arr 1the absolute difference 2 adjacent element equal 1 in word absarri arri 1 1 1 arrlength 0indexed absx absolute value xThere 2 type operation perform number timesdecrease value element arr small positive integerrearrange element arr orderreturn maximum possible value element arr perform operation satisfy condition Example 1input arr 22121output 2explanation we satisfy condition rearrange arr 12221the large element arr 2Example 2Input arr 10011000output 3Explanation one possible way satisfy condition following1 Rearrange arr 110010002 Decrease value second element 23 Decrease value element 3Now arr 123 satisfie conditionsthe large element arr 3Example 3Input arr 12345output 5explanation the array satisfy condition large element 5 Constraints1 arrlength 1051 arri 109
0array
there hotel n room the room represent 2D integer array room roomsi roomIdi sizei denote room room number roomIdi size equal sizei each roomidi guarantee uniqueyou give k query 2D array query queriesj preferredj minSizej the answer jth query room number i d room thatthe room size minSizej andabsid preferredj minimized absx absolute value xIf tie absolute difference use room smallest i d if room answer 1Return array answer length k answerj contain answer jth query Example 1input room 221232 query 313352output 313explanation the answer query followsquery 31 room number 3 close abs3 3 0 size 2 1 the answer 3query 33 there room size 3 answer 1query 52 room number 3 close abs3 5 2 size 2 2 the answer 3example 2input room 1423354152 query 232425output 213explanation the answer query followsquery 23 room number 2 close abs2 2 0 size 3 3 the answer 2query 24 Room number 1 3 size 4 the answer 1 smallerquery 25 room number 3 room size 5 the answer 3 Constraintsn roomslength1 n 105k querieslength1 k 1041 roomIdi preferredj 1071 sizei minSizej 107
0array
give integer array num 0indexed integer target start find index numsi target absi start minimize Note absx absolute value xReturn absi startIt guarantee target exist num Example 1input num 12345 target 5 start 3output 1explanation nums4 5 value equal target answer abs4 3 1example 2input num 1 target 1 start 0output 0explanation nums0 1 value equal target answer abs0 0 0example 3input num 1111111111 target 1 start 0output 0explanation every value num 1 nums0 minimize absi start abs0 0 0 constraints1 numslength 10001 numsi 1040 start numslengthtarget num
0array
you give stre s consist digitscheck split s nonempty substring numerical value substring descend order difference numerical value adjacent substring equal 1for example string s 0090089 split 0090 089 numerical value 9089 the value descend order adjacent value differ 1 way validanother example string s 001 split 0 01 00 1 0 0 1 however way invalid numerical value 01 01 001 respectively descend orderreturn true possible split s describe false otherwisea substre contiguous sequence character string Example 1input s 1234output falseexplanation there valid way split sExample 2input s 050043output trueexplanation s split 05 004 3 numerical value 543the value descend order adjacent value differ 1example 3input s 9080701output falseexplanation there valid way split s constraints1 slength 20s consist digit
2string
you give stre num represent large integer integer kwe integer wonderful permutation digit num great value num there wonderful integer however care smallestvalue onesfor example num 5489355142the 1st small wonderful integer 5489355214The 2nd small wonderful integer 5489355241the 3rd small wonderful integer 5489355412the 4th small wonderful integer 5489355421return minimum number adjacent digit swap need apply num reach kth small wonderful integerthe test generate way kth small wonderful integer exist Example 1input num 5489355142 k 4Output 2explanation the 4th small wonderful number 5489355421 to number Swap index 7 index 8 5489355142 5489355412 Swap index 8 index 9 5489355412 5489355421example 2input num 11112 k 4Output 4explanation the 4th small wonderful number 21111 to number Swap index 3 index 4 11112 11121 Swap index 2 index 3 11121 11211 Swap index 1 index 2 11211 12111 Swap index 0 index 1 12111 21111example 3input num 00123 k 1output 1explanation the 1st small wonderful number 00132 to number Swap index 3 index 4 00123 00132 constraints2 numlength 10001 k 1000num consist digit
2string
you give 2D integer array intervals intervalsi lefti righti describe ith interval start lefti end righti inclusive the size interval define number integer contain formally righti lefti 1you give integer array query the answer jth query size small interval lefti queriesj righti if interval exist answer 1return array contain answer query Example 1input interval 14243644 query 2345output 3314explanation the query process follow Query 2 the interval 24 small interval contain 2 the answer 4 2 1 3 query 3 the interval 24 small interval contain 3 the answer 4 2 1 3 Query 4 the interval 44 small interval contain 4 the answer 4 4 1 1 query 5 the interval 36 small interval contain 5 the answer 6 3 1 4example 2input interval 2325182025 query 219522output 2146explanation the query process follow Query 2 the interval 23 small interval contain 2 the answer 3 2 1 2 Query 19 none interval contain 19 the answer 1 query 5 the interval 25 small interval contain 5 the answer 5 2 1 4 Query 22 the interval 2025 small interval contain 22 the answer 25 20 1 6 Constraints1 intervalslength 1051 querieslength 105intervalsilength 21 lefti righti 1071 queriesj 107
0array
you give 2D integer array log logsi birthi deathi indicate birth death year ith personThe population year x number people alive year the ith person count year xs population x inclusive range birthi deathi 1 note person count year diereturn early year maximum population Example 1input log 1993199920002010output 1993explanation the maximum population 1 1993 early year populationExample 2input log 195019611960197119701981output 1960explanation the maximum population 2 happen year 1960 1970the early year 1960 Constraints1 logslength 1001950 birthi deathi 2050
0array
you give nonincrease 0indexed integer array nums1 nums2A pair indice j 0 nums1length 0 j nums2length valid j nums1i nums2j the distance pair j iReturn maximum distance valid pair j if valid pair return 0an array arr nonincrease arri1 arri 1 arrlength Example 1input nums1 5530542 nums2 1002010105output 2explanation the valid pair 00 22 23 24 33 34 44the maximum distance 2 pair 24example 2input nums1 222 nums2 10101output 1explanation the valid pair 00 01 11the maximum distance 1 pair 01example 3input nums1 3029195 nums2 2525252525output 2explanation the valid pair 22 23 24 33 34the maximum distance 2 pair 24 Constraints1 nums1length nums2length 1051 nums1i nums2j 105both nums1 nums2 nonincreasing
0array
the minproduct array equal minimum value array multiply array sumfor example array 325 minimum value 2 minproduct 2 325 2 10 20given array integer num return maximum minproduct nonempty subarray num since answer large return modulo 109 7note minproduct maximize perform modulo operation testcase generate maximum minproduct modulo fit 64bit sign integerA subarray contiguous array Example 1input num 1232output 14explanation the maximum minproduct achieve subarray 232 minimum value 22 232 2 7 14example 2input num 23312output 18explanation the maximum minproduct achieve subarray 33 minimum value 33 33 3 6 18example 3input num 315642output 60explanation the maximum minproduct achieve subarray 564 minimum value 44 564 4 15 60 constraints1 numslength 1051 numsi 107
0array
there direct graph n color node m edge the node number 0 n 1you give string color colorsi lowercase english letter represent color ith node graph 0indexe you give 2d array edge edgesj aj bj indicate direct edge node aj node bjA valid path graph sequence node x1 x2 x3 xk direct edge xi xi1 1 k the color value path number node color frequently occur color pathreturn large color value valid path give graph 1 graph contain cycle Example 1input color abaca edge 01022334output 3explanation the path 0 2 3 4 contain 3 node color red imageExample 2input color edge 00output 1explanation there cycle 0 0 Constraintsn colorslengthm edgeslength1 n 1050 m 105colors consist lowercase English letters0 aj bj n
1graph
a sentence list word separate single space lead trail space each word consist lowercase uppercase English lettersA sentence shuffle append 1indexed word position word rearrange word sentencefor example sentence this sentence shuffle sentence4 a3 is2 This1 is2 sentence4 This1 a3given shuffle sentence s contain 9 word reconstruct return original sentence Example 1Input s is2 sentence4 This1 a3output this sentenceexplanation Sort word s original position This1 is2 a3 sentence4 remove numbersExample 2input s Myself2 me1 I4 and3Output I Myself IExplanation Sort word s original position me1 Myself2 and3 I4 remove number Constraints2 slength 200s consist lowercase uppercase English letter space digit 1 9the number word s 1 9the word s separate single space contain lead trail space
2string
you give m x n matrix character box represent sideview box each cell box followingA stone a stationary obstacle Empty the box rotate 90 degree clockwise cause stone fall gravity each stone fall land obstacle stone box Gravity affect obstacle position inertia boxs rotation affect stone horizontal positionsIt guarantee stone box rest obstacle stone boxReturn n x m matrix represent box rotation describe Example 1input box Output Example 2input box Output Example 3input box Output Constraintsm boxlengthn boxilength1 m n 500boxij
0array
give integer array num return sum floornumsi numsj pair index 0 j numslength array since answer large return modulo 109 7the floor function return integer division Example 1input num 259output 10explanationfloor2 5 floor2 9 floor5 9 0floor2 2 floor5 5 floor9 9 1floor5 2 2floor9 2 4floor9 5 1we calculate floor division pair index array sum upexample 2input num 7777777output 49 Constraints1 numslength 1051 numsi 105
0array
the XOR total array define bitwise XOR element 0 array emptyfor example XOR total array 256 2 xor 5 xor 6 1given array num return sum XOR total subset num Note Subsets element count multiple timesan array subset array b obtain b delete possibly zero element b example 1input num 13output 6explanation the 4 subset 13 the subset XOR total 0 1 xor total 1 3 xor total 3 13 xor total 1 xor 3 20 1 3 2 6example 2input num 516output 28explanation the 8 subset 516 the subset XOR total 0 5 xor total 5 1 xor total 1 6 xor total 6 51 XOR total 5 xor 1 4 56 xor total 5 xor 6 3 16 XOR total 1 xor 6 7 516 xor total 5 xor 1 xor 6 20 5 1 6 4 3 7 2 28example 3input num 345678output 480explanation the sum XOR total subset 480 constraints1 numslength 121 numsi 20
0array
give binary string s return minimum number character swap alternate 1 impossiblethe string call alternate adjacent character equal for example string 010 1010 alternate string 0100 notany character swap adjacent Example 1input s 111000output 1explanation Swap position 1 4 111000 101010the string alternatingexample 2input s 010output 0explanation the string alternate swap neededexample 3input s 1110output 1 constraints1 slength 1000si 0 1
2string
you give integer array nums1 nums2 you task implement data structure support query typesAdd positive integer element give index array nums2Count number pair j nums1i nums2j equal give value 0 nums1length 0 j nums2lengthimplement FindSumPairs classfindsumpairsint nums1 int nums2 Initializes FindSumPairs object integer array nums1 nums2void addint index int val add val nums2index ie apply nums2index valint countint tot return number pair j nums1i nums2j tot Example 1inputfindsumpairs count add count count add add count1 1 2 2 2 3 1 4 5 2 5 4 7 3 2 8 4 0 1 1 1 7outputnull 8 null 2 1 null null 11ExplanationFindSumPairs findSumPairs new FindSumPairs1 1 2 2 2 3 1 4 5 2 5 4findsumpairscount7 return 8 pair 22 32 42 24 34 44 2 5 pair 51 55 3 4findsumpairsadd3 2 nums2 145454findsumpairscount8 return 2 pair 52 54 3 5findsumpairscount4 return 1 pair 50 make 3 1findsumpairsadd0 1 nums2 245454findsumpairsadd1 1 nums2 255454findsumpairscount7 return 11 pair 21 22 24 31 32 34 41 42 44 2 5 pair 53 55 3 4 Constraints1 nums1length 10001 nums2length 1051 nums1i 1091 nums2i 1050 index nums2length1 val 1051 tot 109At 1000 call add count
0array
give binary string s return true long contiguous segment 1s strictly long long contiguous segment 0s s return false otherwisefor example s 110100010 long continuous segment 1s length 2 long continuous segment 0s length 3Note 0s long continuous segment 0s consider length 0 the apply 1 Example 1input s 1101output trueexplanationthe long contiguous segment 1s length 2 1101the long contiguous segment 0s length 1 1101the segment 1s long return trueExample 2input s 111000output falseExplanationThe long contiguous segment 1s length 3 111000the long contiguous segment 0s length 3 111000the segment 1s long return falseexample 3input s 110100010output falseExplanationThe long contiguous segment 1s length 2 110100010the long contiguous segment 0s length 3 110100010the segment 1s long return false constraints1 slength 100si 0 1
2string
you give floatingpoint number hour represent time reach office to commute office n train sequential order you give integer array dist length n disti describe distance kilometer ith train rideeach train depart integer hour need wait train ridefor example 1st train ride take 15 hour wait additional 05 hour depart 2nd train ride 2 hour markreturn minimum positive integer speed kilometer hour train travel reach office time 1 impossible timetest generate answer exceed 107 hour digit decimal point Example 1input dist 132 hour 6output 1explanation at speed 1 the train ride take 11 1 hour since integer hour depart immediately 1 hour mark the second train take 31 3 hour since integer hour depart immediately 4 hour mark the train take 21 2 hour you arrive exactly 6 hour markExample 2input dist 132 hour 27output 3explanation at speed 3 the train ride take 13 033333 hour since integer hour wait 1 hour mark depart the second train ride take 33 1 hour since integer hour depart immediately 2 hour mark the train take 23 066667 hour you arrive 266667 hour markExample 3input dist 132 hour 19output 1explanation it impossible early train depart 2 hour mark Constraintsn distlength1 n 1051 disti 1051 hour 109There digit decimal point hour
0array
you give 0indexed binary string s integer minjump maxjump in begin stand index 0 equal 0 you index index j follow condition fulfilledi minjump j mini maxjump slength 1 andsj 0return true reach index slength 1 s false Example 1input s 011010 minjump 2 maxjump 3output trueexplanationin step index 0 index 3 in second step index 3 index 5Example 2Input s 01101110 minjump 2 maxjump 3output false constraints2 slength 105si 0 1s0 01 minjump maxjump slength
2string
Alice Bob turn play game Alice start firstThere n stone arrange row on player turn number stone followingchoose integer x 1 remove leftmost x stone rowadd sum remove stone value player scoreplace new stone value equal sum leave rowthe game stop stone leave rowthe score difference Alice Bob Alices score Bobs score Alices goal maximize score difference Bobs goal minimize score differencegiven integer array stone length n stonesi represent value ith stone leave return score difference Alice Bob play optimally example 1input stone 12345output 5explanation Alice remove 4 stone add 1 2 3 4 2 score place stone value 2 leave stone 25 Bob remove 2 stone add 2 5 3 score place stone value 3 leave stone 3the difference score 2 3 5example 2input stone 76510526output 13explanation Alice remove stone add 7 6 5 10 5 2 6 13 score place stone value 13 leave stone 13the difference score 13 0 13example 3input stone 1012output 22explanation Alice remove stone she add 10 12 22 score place stone value 22 leave stone 22the difference score 22 0 22 Constraintsn stoneslength2 n 105104 stonesi 104
0array
a string good repeat charactersgiven string s return number good substring length snote multiple occurrence substre occurrence countedA substre contiguous sequence character string Example 1input s xyzzazoutput 1explanation there 4 substring size 3 xyz yzz zza zaz the good substring length 3 xyzexample 2input s aababcabcoutput 4explanation there 7 substring size 3 aab aba bab abc bca cab abcthe good substring abc bca cab abc Constraints1 slength 100s consist lowercase english letter
2string
the pair sum pair ab equal b the maximum pair sum large pair sum list pairsfor example pair 15 23 44 maximum pair sum max15 23 44 max6 5 8 8given array num length n pair element num n 2 pair thateach element num exactly pair andthe maximum pair sum minimizedReturn minimize maximum pair sum optimally pair element Example 1input num 3523output 7explanation the element pair pair 33 52the maximum pair sum max33 52 max6 7 7Example 2input num 354246output 8explanation the element pair pair 35 44 62the maximum pair sum max35 44 62 max8 8 8 8 Constraintsn numslength2 n 105n even1 numsi 105
0array
you give m x n integer matrix grida rhombus sum sum element form border regular rhombus shape grid the rhombus shape square rotate 45 degree corner center grid cell below image valid rhombus shape correspond color cell include rhombus sumnote rhombus area 0 depict purple rhombus right cornerReturn big distinct rhombus sum grid descend order if distinct value return Example 1input grid 3451333423203020040101554143225output 228216211explanation the rhombus shape big distinct rhombus sum depict Blue 20 3 200 5 228 Red 200 2 10 4 216 Green 5 200 4 2 211example 2input grid 123456789output 2098explanation the rhombus shape big distinct rhombus sum depict Blue 4 2 6 8 20 Red 9 area 0 rhombus right corner Green 8 area 0 rhombus middleExample 3input grid 777output 7explanation all possible rhombus sum return 7 Constraintsm gridlengthn gridilength1 m n 501 gridij 105
0array
you give integer array nums1 nums2 length nThe XOR sum integer array nums10 XOR nums20 nums11 XOR nums21 nums1n 1 XOR nums2n 1 0indexedfor example XOR sum 123 321 equal 1 xor 3 2 xor 2 3 xor 1 2 0 2 4rearrange element nums2 result XOR sum minimizedreturn XOR sum rearrangement Example 1input nums1 12 nums2 23output 2explanation Rearrange nums2 32the XOR sum 1 xor 3 2 XOR 2 2 0 2example 2input nums1 103 nums2 534output 8explanation Rearrange nums2 543 the XOR sum 1 xor 5 0 xor 4 3 xor 3 4 4 0 8 Constraintsn nums1lengthn nums2length1 n 140 nums1i nums2i 107
0array
the letter value letter position alphabet start 0 ie 0 b 1 c 2 etcThe numerical value string lowercase English letter s concatenation letter value letter s convert integerfor example s acb concatenate letter letter value result 021 after convert 21you give string firstWord secondWord targetword consist lowercase English letter j inclusivereturn true summation numerical value firstWord secondWord equal numerical value targetword false example 1input firstWord acb secondWord cba targetWord cdbOutput trueexplanationthe numerical value firstWord acb 021 21the numerical value secondWord cba 210 210the numerical value targetWord cdb 231 231we return true 21 210 231example 2input firstword aaa secondword targetword aaboutput falseexplanation the numerical value firstWord aaa 000 0the numerical value secondWord 0 0the numerical value targetWord aab 001 1we return false 0 0 1example 3input firstWord aaa secondWord targetword aaaaoutput trueexplanation the numerical value firstWord aaa 000 0the numerical value secondWord 0 0the numerical value targetWord aaaa 0000 0We return true 0 0 0 constraints1 firstwordlength secondwordlength targetwordlength 8firstword secondWord targetword consist lowercase English letter j inclusive
2string
you give large integer n represent string integer digit x the digit n digit x inclusive range 1 9 n represent negative numberyou want maximize ns numerical value insert x decimal representation n you insert x leave negative signFor example n 73 x 6 good insert 7 3 making n 763if n 55 x 2 good insert 5 make n 255return string represent maximum value n insertion Example 1input n 99 x 9output 999explanation the result regardless insert 9example 2input n 13 x 2output 123explanation you n 213 123 132 large 123 Constraints1 nlength 1051 x 9The digit n range 1 9n valid representation integerIn case negative n begin
2string
you give 0indexed integer array server task length n m respectively serversi weight ith server tasksj time need process jth task secondstask assign server task queue Initially server free queue emptyAt second j jth task insert queue start 0th task insert second 0 as long free server queue task queue assign free server small weight case tie assign free server small indexIf free server queue wait server free immediately assign task if multiple server free time multiple task queue assign order insertion follow weight index priority aboveA server assign task j second t free second t tasksjbuild array ans length m ansj index server jth task assign toReturn array an Example 1input server 332 task 123212output 220212explanation event chronological order follow at second 0 task 0 add process server 2 second 1 at second 1 server 2 free Task 1 add process server 2 second 3 at second 2 task 2 add process server 0 second 5 at second 3 server 2 free task 3 add process server 2 second 5 at second 4 task 4 add process server 1 second 5 at second 5 server free Task 5 add process server 2 second 7example 2input server 51432 task 2124521output 1414132explanation event chronological order follow at second 0 task 0 add process server 1 second 2 at second 1 task 1 add process server 4 second 2 at second 2 server 1 4 free Task 2 add process server 1 second 4 at second 3 task 3 add process server 4 second 7 at second 4 server 1 free Task 4 add process server 1 second 9 at second 5 task 5 add process server 3 second 7 at second 6 task 6 add process server 2 second 7 constraintsserverslength ntaskslength m1 n m 2 1051 serversi tasksj 2 105
0array
you give integer hoursbefore number hour travel meeting to arrive meeting travel n road the road length give integer array dist length n disti describe length ith road kilometer in addition give integer speed speed kmh travel atAfter travel road rest wait integer hour begin travel road note rest travel road meetingFor example travel road take 14 hour wait 2 hour mark travel road if travel road take exactly 2 hour need waithowever allow skip rest able arrive time mean need wait integer hour Note mean finish travel future road different hour marksfor example suppose travel road take 14 hour travel second road take 06 hour Skipping rest road mean finish travel second road right 2 hour mark let start travel road immediatelyreturn minimum number skip require arrive meeting time 1 impossible Example 1input dist 132 speed 4 hoursbefore 2output 1ExplanationWithout skip rest arrive 14 34 34 14 24 25 hoursYou skip rest arrive 14 0 34 0 24 15 hoursnote second rest shorten finish travel second road integer hour skip restexample 2input dist 7355 speed 2 hoursbefore 10output 2explanationwithout skip rest arrive 72 12 32 12 52 12 52 115 hoursyou skip rest arrive 72 0 32 0 52 0 52 10 hoursExample 3input dist 7355 speed 1 hoursbefore 10output 1explanation it impossible arrive meeting time skip rest Constraintsn distlength1 n 10001 disti 1051 speed 1061 hoursbefore 107
0array
give n x n binary matrix mat target return true possible mat equal target rotate mat 90degree increment false example 1input mat 0110 target 1001output trueexplanation we rotate mat 90 degree clockwise mat equal targetexample 2input mat 0111 target 1001output falseexplanation it impossible mat equal target rotate matexample 3input mat 000010111 target 111010000output trueexplanation we rotate mat 90 degree clockwise time mat equal target Constraintsn matlength targetlengthn matilength targetilength1 n 10matij targetij 0 1
0array
give integer array num goal element num equal to complete operation follow stepsfind large value num let index 0indexed value large if multiple element large value pick small ifind large value num strictly small large let value nextlargestreduce numsi nextlargestreturn number operation element num equal Example 1input num 513output 3explanation it take 3 operation element num equal1 large 5 index 0 nextlarg 3 Reduce nums0 3 num 3132 large 3 index 0 nextlarg 1 Reduce nums0 1 num 1133 large 3 index 2 nextlarg 1 reduce nums2 1 num 111example 2input num 111output 0explanation all element num equalexample 3input num 11223output 4explanation it take 4 operation element num equal1 large 3 index 4 nextlarg 2 Reduce nums4 2 num 112222 large 2 index 2 nextlarg 1 reduce nums2 1 num 111223 large 2 index 3 nextlarg 1 Reduce nums3 1 num 111124 large 2 index 4 nextlarg 1 Reduce nums4 1 num 11111 Constraints1 numslength 5 1041 numsi 5 104
0array
you give binary string s you allow perform type operation stre sequenceType1 Remove character start stre s append end stringType2 Pick character s flip value ie value 0 1 viceversareturn minimum number type2 operation need perform s alternatingthe string call alternate adjacent character equalFor example string 010 1010 alternate string 0100 Example 1input s 111000output 2explanation Use operation times s 100011Then use second operation sixth element s 101010example 2input s 010output 0explanation the string alternatingexample 3input s 1110output 1explanation Use second operation second element s 1010 Constraints1 slength 105si 0 1
2string
you n package try place box package box there m supplier produce box different size infinite supply a package place box size package equal size boxthe package size give integer array package packagesi size ith package the supplier give 2D integer array box boxesj array box size jth supplier producesyou want choose single supplier use box total waste space minimize for package box define space waste size box size package the total waste space sum space waste boxesFor example fit package size 235 supplier offer box size 48 fit package size2 size3 box size4 package size5 box size8 this result waste 42 43 85 6return minimum total waste space choosing box supplier optimally 1 impossible fit package inside box since answer large return modulo 109 7 Example 1input package 235 box 4828output 6explanation it optimal choose supplier size4 box size8 boxthe total waste 42 43 85 6example 2input package 235 box 142334output 1explanation there box package size 5 fit inexample 3input package 358101112 box 1211910514output 9explanation it optimal choose supplier size5 box size10 box size14 boxesThe total waste 53 55 108 1010 1411 1412 9 Constraintsn packageslengthm boxeslength1 n 1051 m 1051 packagesi 1051 boxesjlength 1051 boxesjk 105sumboxesjlength 105the element boxesj distinct
0array
you give 2D integer array range integer leave right each rangesi starti endi represent inclusive interval starti endiReturn true integer inclusive range leave right covered interval range return false otherwisean integer x cover interval rangesi starti endi starti x endi Example 1input range 123456 leave 2 right 5output trueexplanation every integer 2 5 cover 2 cover range 3 4 cover second range 5 cover rangeexample 2input range 1101020 leave 21 right 21output falseexplanation 21 cover range Constraints1 rangeslength 501 starti endi 501 leave right 50
0array
there n student class number 0 n 1 the teacher student problem start student number 0 student number 1 teacher reach student number n 1 after teacher restart process start student number 0 againYou give 0indexed integer array chalk integer k there initially k piece chalk when student number give problem solve use chalki piece chalk solve problem however current number chalk piece strictly chalki student number ask replace chalkReturn index student replace chalk example 1input chalk 515 k 22output 0explanation the student turn follow student number 0 use 5 chalk k 17 Student number 1 use 1 chalk k 16 Student number 2 use 5 chalk k 11 Student number 0 use 5 chalk k 6 Student number 1 use 1 chalk k 5 Student number 2 use 5 chalk k 0student number 0 chalk replace itexample 2input chalk 3412 k 25output 1explanation the student turn follow student number 0 use 3 chalk k 22 Student number 1 use 4 chalk k 18 Student number 2 use 1 chalk k 17 Student number 3 use 2 chalk k 15 Student number 0 use 3 chalk k 12 Student number 1 use 4 chalk k 8 student number 2 use 1 chalk k 7 Student number 3 use 2 chalk k 5 student number 0 use 3 chalk k 2student number 1 chalk replace Constraintschalklength n1 n 1051 chalki 1051 k 109
0array
a k x k magic square k x k grid fill integer row sum column sum diagonal sum equal the integer magic square distinct every 1 x 1 grid trivially magic squareGiven m x n integer grid return size ie length k large magic square find grid Example 1input grid 71456251641543212734output 3explanation the large magic square size 3every row sum column sum diagonal sum magic square equal 12 row sum 516 543 273 12 Column sum 552 147 633 12 Diagonal sum 543 642 12example 2input grid 513193311338output 2 Constraintsm gridlengthn gridilength1 m n 501 gridij 106
0array
you give valid boolean expression string expression consist character 10 bitwise and operator bitwise or operator for example 11 1 valid 1 10 101 valid expressionsReturn minimum cost change final value expressionfor example expression 11001 value 11001 1101 101 11 1 we want apply operation new expression evaluate 0the cost change final value expression number operation perform expression the type operation describe followsTurn 1 0turn 0 1turn turn note precedence order calculation Evaluate parenthese lefttoright order Example 1input expression 101output 1explanation we turn 101 101 change 1 operationthe new expression evaluate 0 example 2input expression 00000output 3explanation we turn 00000 01000 3 operationsthe new expression evaluate 1example 3input expression 0101output 1explanation we turn 0101 0001 1 operationthe new expression evaluate 0 Constraints1 expressionlength 105expression contain 10 all parenthesis properly matchedThere parenthese ie substre expression
2string
you give array string word 0indexedin operation pick distinct index j wordsi nonempty string character wordsi position wordsjreturn true string word equal number operation false example 1input word abcaabcbcoutput trueexplanation move words1 words2to words1 abc words2 abcAll string equal abc return trueexample 2input word abaoutput falseexplanation it impossible string equal operation Constraints1 wordslength 1001 wordsilength 100wordsi consist lowercase english letter
2string
a triplet array integer you give 2D integer array triplet tripletsi ai bi ci describe ith triplet you give integer array target x y z describe triplet want obtainto obtain target apply follow operation triplet number time possibly zerochoose index 0indexe j j update tripletsj maxai aj maxbi bj maxci cjFor example tripletsi 2 5 3 tripletsj 1 7 5 tripletsj update max2 1 max5 7 max3 5 2 7 5return true possible obtain target triplet x y z element triplet false example 1input triplet 253184175 target 275output trueExplanation perform follow operation choose triplet 253184175 update triplet max21 max57 max35 275 triplet 253184275the target triplet 275 element tripletsexample 2input triplet 345456 target 325output falseexplanation it impossible 325 element 2 tripletsexample 3input triplet 253234125523 target 555output trueexplanation perform follow operation choose triplet 253234125523 update triplet max21 max52 max35 255 triplet 253234255523 choose fourth triplet 253234255523 update fourth triplet max25 max52 max53 555 triplet 253234255555the target triplet 555 element triplet Constraints1 tripletslength 105tripletsilength targetlength 31 ai bi ci x y z 1000
0array
a peak element 2D grid element strictly great adjacent neighbor leave right bottomgiven 0indexe m x n matrix mat adjacent cell equal find peak element matij return length 2 array ijYou assume entire matrix surround outer perimeter value 1 cellYou write algorithm run Om logn on logm time Example 1input mat 1432output 01explanation both 3 4 peak element 10 01 acceptable answersexample 2input mat 10201521301471632output 11explanation both 30 32 peak element 11 22 acceptable answer Constraintsm matlengthn matilength1 m n 5001 matij 105no adjacent cell equal
0array
you give stre num represent large integer Return largestvalue odd integer string nonempty substre num string odd integer existsA substre contiguous sequence character string Example 1input num 52output 5explanation the nonempty substring 5 2 52 5 odd numberExample 2input num 4206output Explanation there odd number 4206example 3input num 35427output 35427explanation 35427 odd number Constraints1 numlength 105num consist digit contain lead zero
2string
you participate online chess tournament there chess round start 15 minute the round day start 0000 15 minute new round startsfor example second round start 0015 fourth round start 0045 seventh round start 0130you give string logintime logoutTime wherelogintime time login game andlogouttime time logout gameIf logouttime early logintime mean play logintime midnight midnight logouttimereturn number chess round play tournamentnote all give time follow 24hour clock that mean round day start 0000 round day start 2345 Example 1input logintime 0931 logoutTime 1014output 1explanation you play round 0945 1000you play round 0930 0945 log 0931 beganyou play round 1000 1015 log 1014 endedExample 2input logintime 2130 logouttime 0300output 22explanation you play 10 round 2130 0000 12 round 0000 030010 12 22 ConstraintsloginTime logoutTime format hhmm00 hh 2300 mm 59logintime logoutTime equal
2string
the minimum absolute difference array define minimum value ai aj 0 j alength ai aj if element minimum absolute difference 1for example minimum absolute difference array 52372 2 3 1 note 0 ai aj differentyou give integer array nums array query queriesi li ri for query compute minimum absolute difference subarray numsliri contain element num 0based index li ri inclusiveReturn array ans ansi answer ith queryA subarray contiguous sequence element arraythe value x define asx x 0x x 0 example 1input num 1348 query 01122303output 2141explanation the query process follow queries0 01 the subarray 13 minimum absolute difference 13 2 queries1 12 the subarray 34 minimum absolute difference 34 1 queries2 23 the subarray 48 minimum absolute difference 48 4 queries3 03 the subarray 1348 minimum absolute difference 34 1example 2input num 4522710 query 23020535output 1113explanation the query process follow queries0 23 the subarray 22 minimum absolute difference 1 element queries1 02 the subarray 452 minimum absolute difference 45 1 queries2 05 the subarray 4522710 minimum absolute difference 45 1 queries3 35 the subarray 2710 minimum absolute difference 710 3 constraints2 numslength 1051 numsi 1001 querieslength 2 1040 li ri numslength
0array
give 0indexed integer array num return true strictly increase remove exactly element false if array strictly increase return truethe array num strictly increase numsi 1 numsi index 1 numslength Example 1input num 121057output trueexplanation by remove 10 index 2 num 12571257 strictly increase return trueexample 2input num 2312output falseExplanation312 result remove element index 0212 result remove element index 1232 result remove element index 2231 result remove element index 3No result array strictly increase return falseexample 3input num 111output falseexplanation the result remove element 1111 strictly increase return false constraints2 numslength 10001 numsi 1000
0array
give string s perform follow operation s occurrence substre removedfind leftmost occurrence substring remove sReturn s remove occurrence parta substre contiguous sequence character string Example 1input s daabcbaabcbc abcoutput dabexplanation the follow operation s daabcbaabcbc remove abc start index 2 s dabaabcbc s dabaabcbc remove abc start index 4 s dababc s dababc remove abc start index 3 s dabnow s occurrence abcexample 2Input s axxxxyyyyb xyOutput abExplanation the follow operation s axxxxyyyyb remove xy start index 4 s axxxyyyb s axxxyyyb remove xy start index 3 s axxyyb s axxyyb remove xy start index 2 s axyb s axyb remove xy start index 1 s abnow s occurrence xy Constraints1 slength 10001 partlength 1000 consists lowercase english letter
2string
the alternate sum 0indexed array define sum element index minus sum element odd indicesFor example alternate sum 4253 4 5 2 3 4given array num return maximum alternate sum subsequence num reindexe element subsequencea subsequence array new array generate original array delete element possibly change remain element relative order for example 274 subsequence 4237214 underline element 242 example 1input num 4253output 7explanation it optimal choose subsequence 425 alternate sum 4 5 2 7example 2input num 5678output 8explanation it optimal choose subsequence 8 alternate sum 8example 3input num 621245output 10explanation it optimal choose subsequence 615 alternate sum 6 5 1 10 constraints1 numslength 1051 numsi 105
0array
you movie rent company consist n shop you want implement renting system support search booking return movie the system support generating report currently rent movieseach movie give 2D integer array entries entriesi shopi moviei pricei indicate copy movie moviei shop shopi rental price pricei each shop carry copy movie movieithe system support follow functionssearch find cheap 5 shop unrente copy give movie the shop sort price ascending order case tie small shopi appear if 5 matching shop return if shop unrente copy list returnedrent rent unrente copy give movie give shopDrop drop previously rent copy give movie give shopreport return cheapest 5 rent movie possibly movie ID 2D list re resj shopj moviej describe jth cheap rent movie moviej rent shop shopj the movie re sorted price ascending order case tie small shopj appear tie small moviej appear if few 5 rent movie return if movie currently rent list returnedimplement movierentingsystem classmovierentingsystemint n int entry Initializes MovieRentingSystem object n shop movie entrieslistinteger searchint movie Returns list shop unrente copy give movie describe abovevoid rentint shop int movie rent give movie give shopvoid dropint shop int movie drop previously rent movie give shoplistlistinteg report Returns list cheap rent movie describe abovenote the test case generate rent call shop unrente copy movie drop call shop previously rent movie Example 1inputmovierentingsystem search rent rent report drop search3 0 1 5 0 2 6 0 3 7 1 1 4 1 2 7 2 1 5 1 0 1 1 2 1 2 2outputnull 1 0 2 null null 0 1 1 2 null 0 1explanationmovierentingsystem movierentingsystem new MovieRentingSystem3 0 1 5 0 2 6 0 3 7 1 1 4 1 2 7 2 1 5movierentingsystemsearch1 return 1 0 2 Movies ID 1 unrented shop 1 0 2 Shop 1 cheap shop 0 2 price order shop numbermovieRentingSystemrent0 1 Rent movie 1 shop 0 unrented movie shop 0 23movierentingsystemrent1 2 Rent movie 2 shop 1 unrented movie shop 1 1movierentingsystemreport return 0 1 1 2 Movie 1 shop 0 cheap follow movie 2 shop 1movierentingsystemdrop1 2 Drop movie 2 shop 1 unrented movie shop 1 12movierentingsystemsearch2 return 0 1 Movies ID 2 unrented shop 0 1 Shop 0 cheap follow shop 1 Constraints1 n 3 1051 entrieslength 1050 shopi n1 moviei pricei 104each shop carry copy movie movieiAt 105 call total search rent drop report
0array
the product difference pair b c d define b c dFor example product difference 5 6 2 7 5 6 2 7 16given integer array num choose distinct index w x y z product difference pair numsw numsx numsy numsz maximizedreturn maximum product difference Example 1input num 56274output 34explanation we choose index 1 3 pair 6 7 index 2 4 second pair 2 4the product difference 6 7 2 4 34example 2input num 4259748output 64explanation we choose index 3 6 pair 9 8 index 1 5 second pair 2 4the product difference 9 8 2 4 64 constraints4 numslength 1041 numsi 104
0array
you give m x n integer matrix grid m n integer integer kThe matrix compose layer show image color layera cyclic rotation matrix cyclically rotate layer matrix to cyclically rotate layer element layer place adjacent element counterclockwise direction an example rotation show belowreturn matrix apply k cyclic rotation example 1input grid 40103020 k 1Output 10204030explanation the figure represent grid stateExample 2input grid 12345678910111213141516 k 2output 34812211101617615591314explanation the figure represent grid state Constraintsm gridlengthn gridilength2 m n 50both m n integers1 gridij 50001 k 109
0array
a wonderful string string letter appear odd number timesfor example ccjjc abab wonderful ab notGiven string word consist lowercase english letter j return number wonderful nonempty substring word if substring appear multiple time word count occurrence separatelyA substre contiguous sequence character string example 1input word abaoutput 4explanation the wonderful substring underline aba aba b aba aba abaExample 2Input word aabbOutput 9explanation the wonderful substring underline aabb aabb aa aabb aab aabb aabb aabb aabb abb aabb b aabb bb aabb bExample 3input word heOutput 2explanation the wonderful substring underline h e Constraints1 wordlength 105word consist lowercase english letter j
2string
you ant task add n new room number 0 n1 colony you give expansion plan 0indexe integer array length n prevroom prevRoomi indicate build room prevRoomi building room room connect directly Room 0 build prevroom0 1 the expansion plan give room build room reachable room 0you build room time travel freely room build connect you choose build room long previous room builtreturn number different order build room since answer large return modulo 109 7 Example 1input prevroom 101output 1explanation there way build additional room 0 1 2example 2input prevroom 10012output 6explanationthe 6 way are0 1 3 2 40 2 4 1 30 1 2 3 40 1 2 4 30 2 1 3 40 2 1 4 3 Constraintsn prevroomlength2 n 105prevRoom0 10 prevRoomi n 1 nEvery room reachable room 0 room build
1graph
give zerobased permutation num 0indexe build array ans length ansi numsnumsi 0 numslength return itA zerobased permutation num array distinct integer 0 numslength 1 inclusive Example 1input num 021534output 012453explanation the array an build follow an numsnums0 numsnums1 numsnums2 numsnums3 numsnums4 numsnums5 nums0 nums2 nums1 nums5 nums3 nums4 012453example 2input num 501234output 450123explanation the array an build followsan numsnums0 numsnums1 numsnums2 numsnums3 numsnums4 numsnums5 nums5 nums0 nums1 nums2 nums3 nums4 450123 Constraints1 numslength 10000 numsi numslengthThe element num distinct Followup can solve extra space ie o1 memory
0array
you play video game defend city group n monster you give 0indexed integer array dist size n disti initial distance kilometer ith monster cityThe monster walk city constant speed the speed monster give integer array speed size n speedi speed ith monster kilometer minuteyou weapon fully charge eliminate single monster however weapon take minute chargethe weapon fully charge startYou lose monster reach city if monster reach city exact moment weapon fully charge count loss game end use weaponreturn maximum number monster eliminate lose n eliminate monster reach city Example 1input dist 134 speed 111output 3explanationin begin distance monster 134 you eliminate monsterafter minute distance monster X23 you eliminate second monsterafter minute distance monster XX2 you eliminate thrid monsterall 3 monster eliminatedexample 2input dist 1123 speed 1111output 1explanationin begin distance monster 1123 you eliminate monsterafter minute distance monster X012 loseyou eliminate 1 monsterexample 3input dist 324 speed 532output 1explanationin begin distance monster 324 you eliminate monsterafter minute distance monster X02 loseyou eliminate 1 monster Constraintsn distlength speedlength1 n 1051 disti speedi 105
0array
there country n city number 0 n 1 in country road connect pair citiesThere m friend number 0 m 1 travel country each path consist city each path represent integer array contain visit city order the path contain city city list consecutivelyGiven integer n 2D integer array path pathsi integer array represent path ith friend return length long common subpath share friend path 0 common subpath alla subpath path contiguous sequence city path Example 1input n 5 path 01234 234 40123output 2explanation the long common subpath 23example 2input n 3 path 012output 0explanation there common subpath share pathsexample 3input n 5 path 01234 43210output 1explanation the possible long common subpath 0 1 2 3 4 all length 1 constraints1 n 105 m pathslength2 m 105sumpathsilength 1050 pathsij nThe city list multiple time consecutively pathsi
0array