question
stringlengths 58
4.29k
| label
class label 3
classes |
---|---|
give array positive integer num remove smallest subarray possibly sum remain element divisible p it allow remove arrayreturn length small subarray need remove 1 impossibleA subarray define contiguous block element array Example 1input num 3142 p 6output 1explanation the sum element num 10 divisible 6 we remove subarray 4 sum remain element 6 divisible 6example 2input num 6352 p 9output 2explanation we remove single element sum divisible 9 the good way remove subarray 52 leave 63 sum 9example 3input num 123 p 3output 0explanation here sum 6 divisible 3 thus need remove Constraints1 numslength 1051 numsi 1091 p 109 | 0array
|
you give string text word place number space each word consist lowercase english letter separate space its guarantee text contain wordrearrange space equal number space pair adjacent word number maximize if redistribute space equally place extra space end mean return string length textreturn string rearrange space Example 1input text sentence output sentenceexplanation there total 9 space 4 word we evenly divide 9 space word 9 41 3 spacesExample 2input text practice make perfectoutput practice make perfect Explanation there total 7 space 3 word 7 31 3 space plus 1 extra space we place extra space end string Constraints1 textlength 100text consists lowercase english letter text contain word | 2string
|
give string s return maximum number unique substring give string split intoyou split string s list nonempty substring concatenation substring form original string however split substring uniquea substre contiguous sequence character string Example 1input s ababcccoutput 5explanation one way split maximally b ab c cc splitting like b b c cc valid b multiple timesexample 2input s abaoutput 2explanation one way split maximally baexample 3input s aaoutput 1explanation it impossible split string Constraints1 slength 16 contain low case english letter | 2string
|
you give m x n matrix grid initially locate topleft corner 0 0 step right matrixamong possible path start topleft corner 0 0 end bottomright corner m 1 n 1 find path maximum nonnegative product the product path product integer grid cell visit pathreturn maximum nonnegative product modulo 109 7 if maximum product negative return 1notice modulo perform get maximum product example 1input grid 123233332output 1explanation it possible nonnegative product path 0 0 2 2 return 1example 2input grid 121121341output 8explanation maximum nonnegative product show 1 1 2 4 1 8example 3input grid 1304output 0explanation maximum nonnegative product show 1 0 4 0 Constraintsm gridlengthn gridilength1 m n 154 gridij 4 | 0array
|
you give group point group size1 point second group size2 point size1 size2the cost connection point give size1 x size2 matrix costij cost connect point group point j second group the group connect point group connect point opposite group in word point group connect point second group point second group connect point groupreturn minimum cost take connect group Example 1input cost 15 96 36 2output 17explanation the optimal way connect group is1a2bthis result total cost 17example 2input cost 1 3 5 4 1 1 1 5 3output 4explanation the optimal way connect group is1a2b2c3athis result total cost 4note multiple point connect point 2 group point a second group this matter limit number point connect we care minimum total costExample 3input cost 2 5 1 3 4 7 8 1 2 6 2 4 3 8 8output 10 Constraintssize1 costlengthsize2 costilength1 size1 size2 12size1 size20 costij 100 | 0array
|
you operator Centennial Wheel gondolas gondola room people you ability rotate gondolas counterclockwise cost runningcost dollarsyou give array customer length n customersi number new customer arrive ith rotation 0indexed this mean rotate wheel time customersi customer arrive you customer wait room gondola each customer pay boardingcost dollars board gondola close ground exit gondola reach ground againYou stop wheel time include serve customer if decide stop serve customer subsequent rotation free order customer safely note currently customer wait wheel board gondola rest wait rotationreturn minimum number rotation need perform maximize profit if scenario profit positive return 1 example 1input customer 83 boardingcost 5 runningcost 6output 3explanation the number write gondolas number people currently there1 8 customer arrive 4 board 4 wait gondola wheel rotate current profit 4 5 1 6 142 3 customer arrive 4 wait board wheel 3 wait wheel rotate current profit 8 5 2 6 283 the final 3 customer board gondola wheel rotate current profit 11 5 3 6 37the high profit 37 rotate wheel 3 timesexample 2input customer 1096 boardingcost 6 runningcost 4output 7explanation1 10 customer arrive 4 board 6 wait gondola wheel rotate current profit 4 6 1 4 202 9 customer arrive 4 board 11 wait 2 originally wait 9 newly wait wheel rotate current profit 8 6 2 4 403 the final 6 customer arrive 4 board 13 wait wheel rotate current profit 12 6 3 4 604 4 board 9 wait wheel rotate current profit 16 6 4 4 805 4 board 5 wait wheel rotate current profit 20 6 5 4 1006 4 board 1 wait wheel rotate current profit 24 6 6 4 1207 1 board wheel rotate current profit 25 6 7 4 122the high profit 122 rotate wheel 7 timesexample 3input customer 34051 boardingcost 1 runningcost 92output 1explanation1 3 customer arrive 3 board 0 wait wheel rotate current profit 3 1 1 92 892 4 customer arrive 4 board 0 wait wheel rotate current profit 7 1 2 92 1773 0 customer arrive 0 board 0 wait wheel rotate current profit 7 1 3 92 2694 5 customer arrive 4 board 1 wait wheel rotate current profit 11 1 4 92 3575 1 customer arrive 2 board 0 wait wheel rotate current profit 13 1 5 92 447the profit positive return 1 Constraintsn customerslength1 n 1050 customersi 501 boardingcost runningcost 100 | 0array
|
a kingdom consist king child grandchild every family die child bornthe kingdom welldefine order inheritance consist king member Lets define recursive function Successorx curorder give person x inheritance order far return person x order inheritancesuccessorx curorder x child xs child curOrder x king return null return Successorxs parent curorder return xs old child who s curOrderFor example assume kingdom consist king child Alice Bob Alice old Bob finally alice son jackin begin curorder kingcalle successorke curorder return Alice append curorder king AliceCalling SuccessorAlice curorder return Jack append curorder king Alice JackCalling SuccessorJack curorder return Bob append curorder king Alice Jack BobCalling SuccessorBob curorder return null Thus order inheritance king Alice Jack BobUsing function obtain unique order inheritanceimplement ThroneInheritance classthroneinheritancestre kingname initialize object ThroneInheritance class the king give constructorvoid birthstre parentName string childname Indicates parentName give birth childnamevoid deathstre indicate death the death person do not affect Successor function current inheritance order you treat mark person deadstre getInheritanceOrder return list represent current order inheritance exclude dead people Example 1inputthroneinheritance birth birth birth birth birth birth getinheritanceorder death getinheritanceorderking king andy king bob king catherine andy matthew bob alex bob asha null bob nullOutputnull null null null null null null king andy matthew bob alex asha catherine null king andy matthew alex asha catherineexplanationthroneinheritance t new ThroneInheritanceking order kingtbirthke andy order king andytbirthke bob order king andy bobtbirthking catherine order king andy bob catherinetbirthandy matthew order king andy matthew bob catherinetbirthbob alex order king andy matthew bob alex catherinetbirthbob asha order king andy matthew bob alex asha catherinetgetInheritanceOrder return king andy matthew bob alex asha catherinetdeathbob order king andy matthew bob alex asha catherinetgetInheritanceOrder return king andy matthew alex asha catherine Constraints1 kingnamelength parentnamelength childnamelength namelength 15kingname parentName childname consist lowercase english letter onlyall argument childname kingname distinctAll argument death pass constructor childname birth firstfor birthparentName childName guarantee parentname aliveat 105 call birth deathat 10 call getinheritanceorder | 1graph
|
we n building number 0 n 1 each building number employee its transfer season employee want change building reside inyou give array request requestsi fromi toi represent employee request transfer build fromi building toiall building list request achievable building net change employee transfer zero this mean number employee leave equal number employee move for example n 3 employee leave build 0 leave build 1 leave build 2 employee moving build 0 employee move build 1 employee move build 2return maximum number achievable request Example 1input n 5 request 011001122034output 5explantion Lets requestsfrom build 0 employee x y want build 1from build 1 employee b want building 2 0 respectivelyFrom build 2 employee z want build 0from build 3 employee c want build 4from building 4 do not requestsWe achieve request user x b swap placesWe achieve request user y z swap place 3 buildingsexample 2input n 3 request 001221output 3explantion Lets requestsfrom building 0 employee x want stay build 0from build 1 employee y want build 2From build 2 employee z want build 1we achieve request Example 3input n 4 request 03311220output 4 constraints1 n 201 requestslength 16requestsilength 20 fromi toi n | 0array
|
you give array rowsum colsum nonnegative integer rowSumi sum element ith row colsumj sum element jth column 2D matrix in word know elements matrix know sum row columnfind matrix nonnegative integer size rowsumlength x colsumlength satisfie rowsum colsum requirementsreturn 2D array represent matrix fulfill requirement its guarantee matrix fulfill requirement exist Example 1input rowsum 38 colsum 47Output 30 17explanation 0th row 3 0 3 rowsum01st row 1 7 8 rowsum10th column 3 1 4 colsum01st column 0 7 7 colsum1the row column sum match matrix element nonnegativeanother possible matrix 12 35example 2input rowsum 5710 colsum 868output 050 610 208 Constraints1 rowsumlength colsumlength 5000 rowSumi colsumi 108sumrows sumcolumn | 0array
|
you k server number 0 k1 handle multiple request simultaneously each server infinite computational capacity handle request time the request assign server accord specific algorithmthe ith 0indexed request arrivesif server busy request drop handle allIf kth server available assign request serverotherwise assign request available server wrapping list server start 0 necessary for example ith server busy try assign request i1th server i2th server onyou give strictly increase array arrival positive integer arrivali represent arrival time ith request array load loadi represent load ith request time take complete your goal find busy server a server consider busiest handle number request successfully serversreturn list contain id 0indexe busy server you return id order Example 1Input k 3 arrival 12345 load 52333 Output 1 Explanation all server start availableThe 3 request handle 3 server orderrequ 3 come Server 0 busy assign available server 1request 4 come it handle server busy droppedserver 0 2 handle request server 1 handle request hence server 1 busy serverexample 2input k 3 arrival 1234 load 1212output 0explanation the 3 request handle 3 serversrequ 3 come it handle server 0 server availableserver 0 handle request server 1 2 handle request hence server 0 busy serverexample 3input k 3 arrival 123 load 101211output 012explanation each server handle single request consider busy Constraints1 k 1051 arrivallength loadlength 105arrivallength loadlength1 arrivali loadi 109arrival strictly increase | 0array
|
you give array num nonnegative integer num consider special exist number x exactly x number num greater equal xNotice x element numsReturn x array special return 1 it prove num special value x unique Example 1input num 35output 2explanation there 2 value 3 5 great equal 2example 2input num 00output 1explanation no number fit criterion xIf x 0 0 number x 2if x 1 1 number x 0if x 2 2 number x 0x great 2 number numsExample 3input num 04304output 3explanation there 3 value greater equal 3 constraints1 numslength 1000 numsi 1000 | 0array
|
a binary tree name EvenOdd meet follow conditionsThe root binary tree level index 0 child level index 1 child level index 2 etcfor evenindexe level node level odd integer value strictly increase order leave rightfor oddindexed level node level integer value strictly decrease order leave rightGiven root binary tree return true binary tree EvenOdd return false Example 1input root 11043null791286nullnull2output trueExplanation the node value level arelevel 0 1level 1 104level 2 379level 3 12862since level 0 2 odd increase level 1 3 decrease tree evenoddexample 2input root 542337output falseexplanation the node value level arelevel 0 5level 1 42level 2 337node value level 2 strictly increase order tree evenoddexample 3input root 591357output falseexplanation Node value level 1 integer ConstraintsThe number nod tree range 1 1051 Nodeval 106 | 1graph
|
you give array point integer angle location location posx posy pointsi xi yi denote integral coordinate XY planeinitially face directly east position you position rotate in word posx posy change your field view degree represent angle determine wide give view direction let d degree rotate counterclockwise Then field view inclusive range angle d angle2 d angle2Your browser support video tag video formatyou set point point angle form point position immediate east direction position field viewthere multiple point coordinate there point location point regardless rotation Points obstruct vision pointsreturn maximum number point example 1input point 212233 angle 90 location 11output 3explanation the shaded region represent field view all point visible field view include 33 22 line sightexample 2input point 21223411 angle 90 location 11output 4explanation all point visible field view include locationexample 3input point 1021 angle 13 location 11output 1explanation you point show Constraints1 pointslength 105pointsilength 2locationlength 20 angle 3600 posx posy xi yi 100 | 0array
|
a string valid parenthesis stre denote VPS meet followingit string single character equal it write AB a concatenate B A b vps orit write a a VPSWe similarly define nesting depth depths VPS S followsdepth 0depthC 0 c string single character equal depthA B maxdeptha depthB a b vpssdepth a 1 depthA A VPSFor example VPSs nesting depth 0 1 2 VPSsGiven VPS represent string s return nesting depth s example 1input s 123841output 3explanation Digit 8 inside 3 nest parenthese stringexample 2input s 123output 3 Constraints1 slength 100s consist digit 09 character it guarantee parenthese expression s vps | 2string
|
there infrastructure n city number road connect city each roadsi ai bi indicate bidirectional road city ai biThe network rank different city define total number directly connect road city if road directly connect city count oncethe maximal network rank infrastructure maximum network rank pair different citiesGiven integer n array road return maximal network rank entire infrastructure Example 1input n 4 road 01031213output 4explanation the network rank city 0 1 4 4 road connect 0 1 the road 0 1 count onceExample 2input n 5 road 010312132324output 5explanation there 5 road connect city 1 2example 3input n 8 road 011223245657output 5explanation the network rank 2 5 5 notice city connect Constraints2 n 1000 roadslength n n 1 2roadsilength 20 ai bi n1ai biEach pair city road connect | 1graph
|
you give string b length Choose index split string index splitting string aprefix asuffix aprefix asuffix splitting b string bprefix bsuffix b bprefix bsuffix check aprefix bsuffix bprefix asuffix form palindromeWhen split string s sprefix ssuffix ssuffix sprefix allow for example s abc abc bc ab c abc valid splitsreturn true possible form palindrome string return falseNotice x y denote concatenation string x y Example 1Input x b yOutput trueexplaination if b palindrome answer true split follow wayaprefix asuffix xbprefix bsuffix yThen aprefix bsuffix y y palindromeExample 2Input xbdef b xecabOutput falseExample 3input ulacfd b jizaluoutput trueexplaination Split index 3aprefix ula asuffix cfdbprefix jiz bsuffix aluthen aprefix bsuffix ula alu ulaalu palindrome Constraints1 alength blength 105alength blengtha b consist lowercase english letter | 2string
|
give integer array arr return mean remain integer remove smallest 5 large 5 elementsanswer 105 actual answer consider accept Example 1input arr 12222222222222222223output 200000explanation after erase minimum maximum value array element equal 2 mean 2example 2input arr 627512031025055087680output 400000example 3input arr 607075783407816811248195438510866106108234output 477778 constraints20 arrlength 1000arrlength multiple 200 arri 105 | 0array
|
you give array network tower tower towersi xi yi qi denote ith network tower location xi yi quality factor qi all coordinate integral coordinate XY plane distance coordinate Euclidean distanceyou give integer radius tower reachable distance equal radius outside distance signal garbled tower reachableThe signal quality ith tower coordinate x y calculate formula qi 1 d d distance tower coordinate the network quality coordinate sum signal quality reachable towersreturn array cx cy represent integral coordinate cx cy network quality maximum if multiple coordinate network quality return lexicographically minimum nonnegative coordinatenotea coordinate x1 y1 lexicographically small x2 y2 eitherx1 x2 orx1 x2 y1 y2val great integer equal val floor function Example 1input tower 125217319 radius 2output 21explanation at coordinate 2 1 total quality 13 Quality 7 2 1 result 7 1 sqrt0 7 7 Quality 5 1 2 result 5 1 sqrt2 207 2 Quality 9 3 1 result 9 1 sqrt1 45 4no coordinate high network qualityExample 2input tower 231121 radius 9output 2311explanation since tower network quality high right tower locationexample 3input tower 1213217019 radius 2output 12Explanation Coordinate 1 2 high network quality Constraints1 towerslength 50towersilength 30 xi yi qi 501 radius 50 | 0array
|
give string s return length long substre equal character exclude character if substre return 1A substre contiguous sequence character string example 1input s aaoutput 0explanation the optimal substring substre asExample 2input s abcaoutput 2explanation the optimal substring bcExample 3input s cbzxyoutput 1explanation there character appear twice s Constraints1 slength 300s contain lowercase english letter | 2string
|
you manager basketball team for upcoming tournament want choose team high overall score the score team sum score players teamhowever basketball team allow conflict a conflict exist young player strictly high score old player a conflict occur player agegiven list score ages scoresi agesi represent score age ith player respectively return high overall score possible basketball team Example 1input score 1351015 age 12345output 34explanation you choose playersExample 2input score 4565 age 2121output 16explanation it well choose 3 player Notice allow choose multiple people ageexample 3input score 1235 age 89101output 6explanation it well choose 3 player Constraints1 scoreslength ageslength 1000scoreslength ageslength1 scoresi 1061 agesi 1000 | 0array
|
we n city label 1 n two different city label x y directly connect bidirectional road x y share common divisor strictly great threshold more formally city label x y road exist integer z follow truex z 0y z 0 andz thresholdGiven integer n threshold array query determine queriesi ai bi city ai bi connect directly indirectly ie path themreturn array answer answerlength querieslength answeri true ith query path ai bi answeri false path Example 1input n 6 threshold 2 query 142536output falsefalsetrueexplanation the divisor number1 12 1 23 1 34 1 2 45 1 56 1 2 3 6using underline divisor threshold city 3 6 share common divisor theonly one directly connect the result query14 1 connect 425 2 connect 536 3 connect 6 path 36example 2input n 6 threshold 0 query 4534322613output truetruetruetruetrueexplanation the divisor number previous example however threshold 0all divisor since number share 1 divisor city connectedexample 3input n 5 threshold 1 query 4545322334output falsefalsefalsefalsefalseexplanation only city 2 4 share common divisor 2 strictly great threshold 1 one directly connectedplease notice multiple query pair node x y query x y equivalent query y x Constraints2 n 1040 threshold n1 querieslength 105queriesilength 21 ai bi citiesai bi | 0array
|
a sequence number call arithmetic consist element difference consecutive element more formally sequence s arithmetic si1 si s1 s0 valid iFor example arithmetic sequences1 3 5 7 97 7 7 73 1 5 9the follow sequence arithmetic1 1 2 5 7you give array n integer num array m integer l r represent m range query ith query range li ri all arrays 0indexedreturn list boolean element answer answeri true subarray numsli numsli1 numsri rearrange form arithmetic sequence false Example 1input num 465937 l 002 r 235output truefalsetrueexplanationin 0th query subarray 465 this rearrange 654 arithmetic sequenceIn 1st query subarray 4659 this rearrange arithmetic sequenceIn 2nd query subarray 5937 this rearrange 3579 arithmetic sequenceexample 2input num 1293126152025201510 l 016487 r 4497910output falsetruefalsefalsetruetrue Constraintsn numslengthm llengthm rlength2 n 5001 m 5000 li ri n105 numsi 105 | 0array
|
give array integer num sort array increase order base frequency value if multiple value frequency sort decrease orderreturn sorted array Example 1input num 112223output 311222explanation 3 frequency 1 1 frequency 2 2 frequency 3example 2input num 23132output 13322explanation 2 3 frequency 2 sort decrease orderexample 3input num 116456141output 514466111 Constraints1 numslength 100100 numsi 100 | 0array
|
give n point 2D plane pointsi xi yi return wide vertical area point point inside areaA vertical area area fixedwidth extend infinitely yaxis ie infinite height the widest vertical area maximum widthnote point edge vertical area consider include area Example 1input point 87997497output 1explanation both red blue area optimalexample 2input point 319010145388output 3 Constraintsn pointslength2 n 105pointsilength 20 xi yi 109 | 0array
|
give string s t find number way choose nonempty substring s replace single character different character result substre substre t in word find number substring s differ substre t exactly characterfor example underline substrings computer computation differ ea valid wayreturn number substring satisfy condition aboveA substre contiguous sequence character string Example 1input s aba t babaoutput 6explanation the follow pair substring s t differ exactly 1 characteraba babaaba babaaba babaaba babaaba babaaba babaThe underlined portion substring choose s tExample 2input s ab t bbOutput 3explanation the follow pair substring s t differ 1 characterab bbab bbab bbThe underlined portion substring choose s t constraints1 slength tlength 100s t consist lowercase english letter | 2string
|
you give array distinct integer arr array integer array piece integer piece distinct your goal form arr concatenate arrays piece order however allow reorder integer array piecesireturn true possible form array arr piece otherwise return false Example 1input arr 1588 piece 8815output trueExplanation Concatenate 15 88example 2input arr 491816 piece 161849output falseexplanation even number match reorder pieces0Example 3Input arr 9146478 piece 7846491output trueexplanation Concatenate 91 464 78 Constraints1 pieceslength arrlength 100sumpiecesilength arrlength1 piecesilength arrlength1 arri piecesij 100The integer arr distinctthe integer piece distinct ie if flatten piece 1D array integer array distinct | 0array
|
you give integer array height represent height building brick laddersyou start journey build 0 building possibly brick ladderswhile move building building i1 0indexedif current building height greater equal building height need ladder bricksIf current building height building height use ladder hi1 hi bricksreturn furth building index 0indexed reach use give ladder brick optimally example 1input height 427691412 brick 5 ladder 1output 4explanation starting building 0 follow step go build 1 ladder brick 4 2 go build 2 5 brick you use brick ladder 2 7 go build 3 ladder brick 7 6 go build 4 ladder you use brick ladder 6 9it impossible building 4 brick laddersExample 2input height 4122731820319 brick 10 ladder 2Output 7example 3input height 143193 brick 17 ladder 0output 3 Constraints1 heightslength 1051 heightsi 1060 brick 1090 ladder heightslength | 0array
|
Bob stand cell 0 0 wants reach destination row column he travel right you go help Bob provide instruction reach destinationthe instruction represent string character eitherH mean horizontally right orv mean vertically downmultiple instruction lead Bob destination for example destination 2 3 hhhvv HVHVH valid instructionsHowever Bob picky Bob lucky number k want kth lexicographically small instruction lead destination k 1indexedgiven integer array destination integer k return kth lexicographically small instruction Bob destination Example 1input destination 23 k 1output HHHVVExplanation all instruction reach 2 3 lexicographic order followsHHHVV HHVHV HHVVH HVHHV HVHVH HVVHH VHHHV VHHVH VHVHH VVHHHExample 2input destination 23 k 2output HHVHVExample 3input destination 23 k 3output HHVVH Constraintsdestinationlength 21 row column 151 k nCrrow column row nCra b denote choose b | 0array
|
you give integer n a 0indexed integer array num length n 1 generate follow waynums0 0nums1 1nums2 numsi 2 2 nnums2 1 numsi numsi 1 2 2 1 nReturn maximum integer array num Example 1input n 7output 3explanation according give rule nums0 0 nums1 1 nums1 2 2 nums1 1 nums1 2 1 3 nums1 nums2 1 1 2 nums2 2 4 nums2 1 nums2 2 1 5 nums2 nums3 1 2 3 nums3 2 6 nums3 2 nums3 2 1 7 nums3 nums4 2 1 3hence num 01121323 maximum max01121323 3example 2input n 2output 1explanation according give rule num 011 the maximum max011 1Example 3input n 3output 2explanation according give rule num 0112 the maximum max0112 2 Constraints0 n 100 | 0array
|
a string s call good different character s frequencyGiven string s return minimum number character need delete s goodthe frequency character string number time appear stre for example stre aab frequency 2 frequency b 1 Example 1input s aaboutput 0explanation s goodexample 2input s aaabbbccoutput 2explanation you delete b result good string aaabccanother way delete b c result good string aaabbcexample 3input s ceabaacboutput 2explanation you delete cs result good string eabaabnote care character string end ie frequency 0 ignore Constraints1 slength 105s contain lowercase english letter | 2string
|
you inventory different colored ball customer want order ball colorthe customer weirdly value color ball each color ball value number ball color currently inventory for example 6 yellow ball customer pay 6 yellow ball after transaction 5 yellow ball leave yellow ball value 5 ie value ball decreases sell customerYou give integer array inventory inventoryi represent number ball ith color initially you give integer order represent total number ball customer want you sell ball orderreturn maximum total value attain selling order color ball as answer large return modulo 109 7 Example 1input inventory 25 order 4output 14explanation sell 1st color 1 time 2 2nd color 3 time 5 4 3the maximum total value 2 5 4 3 14example 2input inventory 35 order 6output 19explanation sell 1st color 2 time 3 2 2nd color 4 time 5 4 3 2the maximum total value 3 2 5 4 3 2 19 Constraints1 inventorylength 1051 inventoryi 1091 order minsuminventoryi 109 | 0array
|
give integer array instruction ask create sorted array element instruction you start container num for element leave right instruction insert num the cost insertion minimum followingthe number element currently num strictly instructionsithe number element currently num strictly great instructionsifor example insert element 3 num 1235 cost insertion min2 1 element 1 2 3 element 5 great 3 num 12335return total cost insert element instruction num since answer large return modulo 109 7 Example 1input instruction 1562output 1explanation Begin num Insert 1 cost min0 0 0 num 1insert 5 cost min1 0 0 num 15insert 6 cost min2 0 0 num 156insert 2 cost min1 2 1 num 1256the total cost 0 0 0 1 1example 2input instruction 123654output 3explanation Begin num Insert 1 cost min0 0 0 num 1insert 2 cost min1 0 0 num 12insert 3 cost min2 0 0 num 123insert 6 cost min3 0 0 num 1236insert 5 cost min3 1 1 num 12356insert 4 cost min3 2 2 num 123456the total cost 0 0 0 0 1 2 3example 3input instruction 133324212output 4explanation Begin num Insert 1 cost min0 0 0 num 1insert 3 cost min1 0 0 num 13Insert 3 cost min1 0 0 num 133insert 3 cost min1 0 0 num 1333insert 2 cost min1 3 1 num 12333insert 4 cost min5 0 0 num 123334insert 2 cost min1 4 1 num 1223334insert 1 cost min0 6 0 num 11223334insert 2 cost min2 4 2 num 112223334the total cost 0 0 0 0 1 0 1 0 2 4 Constraints1 instructionslength 1051 instructionsi 105 | 0array
|
you bomb defuse time run your informer provide circular array code length n key kto decrypt code replace number all number replace simultaneouslyIf k 0 replace ith number sum k numbersIf k 0 replace ith number sum previous k numbersIf k 0 replace ith number 0As code circular element coden1 code0 previous element code0 coden1Given circular array code integer key k return decrypt code defuse bomb Example 1input code 5714 k 3output 12101613explanation each number replace sum 3 number the decrypt code 714 145 457 571 Notice number wrap aroundexample 2input code 1234 k 0output 0000explanation when k zero number replace 0 example 3input code 2493 k 2output 125613explanation the decrypted code 39 23 42 94 notice number wrap if k negative sum previous number Constraintsn codelength1 n 1001 codei 100n 1 k n 1 | 0array
|
you give string s consist character byou delete number character s s balanced s balanced pair index ij j si b sj areturn minimum number deletion need s balanced Example 1input s aababbaboutput 2explanation you eitherdelete character 0indexe position 2 6 aababbab aaabbb ordelete character 0indexed position 3 6 aababbab aabbbbexample 2input s bbaaaaabboutput 2explanation the solution delete character Constraints1 slength 105si b | 2string
|
you give array n integer num 50 unique value array you give array m customer order quantitie quantity quantityi integer ith customer order Determine possible distribute num thatthe ith customer get exactly quantityi integersthe integer ith customer get equal andevery customer satisfiedreturn true possible distribute num accord condition Example 1input num 1234 quantity 2output falseexplanation the 0th customer give different integersExample 2input num 1233 quantity 2output trueexplanation the 0th customer give 33 the integer 12 usedexample 3input num 1122 quantity 22output trueexplanation the 0th customer give 11 1st customer give 22 Constraintsn numslength1 n 1051 numsi 1000 m quantitylength1 m 101 quantityi 105there 50 unique value num | 0array
|
there stream n idkey value pair arrive arbitrary order idKey integer 1 n value string no pair iddesign stream return value increase order id return chunk list value insertion the concatenation chunk result list sort valuesImplement OrderedStream classorderedstreamint n Constructs stream n valuesstre insertint idKey String value Inserts pair idkey value stream return large possible chunk currently insert value appear order ExampleInputOrderedStream insert insert insert insert insert5 3 ccccc 1 aaaaa 2 bbbbb 5 eeeee 4 dddddOutputnull aaaaa bbbbb ccccc ddddd eeeeeexplanation note value order ID aaaaa bbbbb ccccc ddddd eeeeeorderedstream os new OrderedStream5osinsert3 ccccc Inserts 3 ccccc return osinsert1 aaaaa Inserts 1 aaaaa return aaaaaosinsert2 bbbbb Inserts 2 bbbbb return bbbbb cccccosinsert5 eeeee Inserts 5 eeeee return osinsert4 ddddd insert 4 ddddd return ddddd eeeee Concatentating chunk return aaaaa bbbbb ccccc ddddd eeeee aaaaa bbbbb ccccc ddddd eeeee the result order order Constraints1 n 10001 i d nvaluelength 5value consist lowercase lettersEach insert unique idexactly n call insert | 0array
|
two string consider close attain follow operationsoperation 1 Swap exist charactersfor example abcde aecdboperation 2 transform occurrence exist character exist character characterFor example aacabb bbcbaa turn bs bs turn asyou use operation string time necessarygiven string word1 word2 return true word1 word2 close false example 1input word1 abc word2 bcaoutput trueexplanation you attain word2 word1 2 operationsapply operation 1 abc acbApply operation 1 acb bcaexample 2input word1 word2 aaOutput falseexplanation it impossible attain word2 word1 vice versa number operationsexample 3input word1 cabbba word2 abbcccoutput trueexplanation you attain word2 word1 3 operationsapply operation 1 cabbba caabbbapply operation 2 caabbb baacccapply operation 2 baaccc abbccc Constraints1 word1length word2length 105word1 word2 contain lowercase english letter | 2string
|
you give integer array nums integer x in operation remove leftmost rightmost element array num subtract value x note modify array future operationsreturn minimum number operation reduce x exactly 0 possible return 1 Example 1input num 11423 x 5output 2explanation the optimal solution remove element reduce x zeroExample 2input num 56789 x 4Output 1Example 3input num 3220113 x 10output 5explanation the optimal solution remove element element 5 operation total reduce x zero Constraints1 numslength 1051 numsi 1041 x 109 | 0array
|
the numeric value lowercase character define position 1indexed alphabet numeric value 1 numeric value b 2 numeric value c 3 onThe numeric value string consist lowercase character define sum character numeric value for example numeric value string abe equal 1 2 5 8you give integer n k Return lexicographically small string length equal n numeric value equal kNote string x lexicographically small string y x come y dictionary order x prefix y position xi yi xi come yi alphabetic order Example 1input n 3 k 27output aayexplanation the numeric value string 1 1 25 27 small string value length equal 3example 2input n 5 k 73output aaszz Constraints1 n 105n k 26 n | 2string
|
you give integer array num you choose exactly index 0indexed remove element Notice index element change removalfor example num 61741choosing remove index 1 result num 6741choosing remove index 2 result num 6141choosing remove index 4 result num 6174an array fair sum oddindexe value equal sum evenindexe valuesreturn number index choose removal num fair Example 1input num 2164output 1explanationremove index 0 164 even sum 1 4 5 odd sum 6 not fairRemove index 1 264 even sum 2 4 6 odd sum 6 FairRemove index 2 214 even sum 2 4 6 odd sum 1 not fairRemove index 3 216 even sum 2 6 8 odd sum 1 not fairthere 1 index remove num fairexample 2input num 111output 3explanation you remove index remain array fairexample 3input num 123output 0explanation you fair array remove index Constraints1 numslength 1051 numsi 104 | 0array
|
you give array task tasksi actuali minimumiactuali actual energy spend finish ith taskminimumi minimum energy require begin ith taskFor example task 10 12 current energy 11 start task however current energy 13 complete task energy 3 finishing itYou finish task order likereturn minimum initial energy need finish task Example 1input task 122448output 8explanationstarte 8 energy finish task follow order 3rd task now energy 8 4 4 2nd task now energy 4 2 2 1st task now energy 2 1 1notice leftover energy start 7 energy work 3rd taskexample 2input task 13241011101289output 32explanationstarting 32 energy finish task follow order 1st task now energy 32 1 31 2nd task now energy 31 2 29 3rd task now energy 29 10 19 4th task now energy 19 10 9 5th task now energy 9 8 1example 3input task 172839410511612output 27explanationstarting 27 energy finish task follow order 5th task now energy 27 5 22 2nd task now energy 22 2 20 3rd task now energy 20 3 17 1st task now energy 17 1 16 4th task now energy 16 4 12 6th task now energy 12 6 6 Constraints1 taskslength 1051 actuali minimumi 104 | 0array
|
for string sequence string word krepeate word concatenate k time substre sequence the word maximum krepeating value high value k word krepeate sequence if word substre sequence word maximum krepeating value 0given string sequence word return maximum krepeating value word sequence Example 1input sequence ababc word abOutput 2explanation abab substre ababcexample 2input sequence ababc word baOutput 1explanation ba substre ababc baba substre ababcexample 3input sequence ababc word acOutput 0explanation ac substre ababc Constraints1 sequencelength 1001 wordlength 100sequence word contain lowercase english letter | 2string
|
design queue support push pop operation middle backImplement FrontMiddleBack classfrontmiddleback Initializes queuevoid pushfrontint val add val queuevoid pushmiddleint val add val middle queuevoid pushbackint val add val queueint popfront remove element queue return if queue return 1int popmiddle Removes middle element queue return if queue return 1int popback Removes element queue return if queue return 1notice middle position choice operation perform frontmost middle position choice for examplepushe 6 middle 1 2 3 4 5 result 1 2 6 3 4 5popping middle 1 2 3 4 5 6 return 3 result 1 2 4 5 6 Example 1inputfrontmiddlebackqueue pushfront pushback pushmiddle pushmiddle popFront popmiddle popmiddle popback popfront 1 2 3 4 outputnull null null null null 1 3 4 2 1explanationfrontmiddlebackqueue q new FrontMiddleBackQueueqpushFront1 1qpushback2 1 2qpushmiddle3 1 3 2qpushmiddle4 1 4 3 2qpopfront return 1 4 3 2qpopmiddle return 3 4 2qpopmiddle return 4 2qpopback return 2 qpopfront return 1 the queue Constraints1 val 109At 1000 call pushfront pushmiddle pushback popfront popmiddle popback | 0array
|
you recall array arr mountain array ifarrlength 3There exist index 0indexe 0 arrlength 1 thatarr0 arr1 arri 1 arriarri arri 1 arrarrlength 1given integer array num return minimum number element remove num mountain array Example 1input num 131output 0explanation the array mountain array need remove elementsexample 2input num 21156231output 3explanation one solution remove element indice 0 1 5 make array num 15631 constraints3 numslength 10001 numsi 109it guarantee mountain array num | 0array
|
you give m x n integer grid account accountsij money ith customer jth bank Return wealth rich customer hasa customer wealth money bank account the rich customer customer maximum wealth Example 1input account 123321output 6Explanation1st customer wealth 1 2 3 62nd customer wealth 3 2 1 6both customer consider rich wealth 6 return 6example 2input account 157335output 10explanation 1st customer wealth 62nd customer wealth 10 3rd customer wealth 8the 2nd customer rich wealth 10example 3input account 287713195output 17 Constraintsm accountslengthn accountsilength1 m n 501 accountsij 100 | 0array
|
you give integer array num length n integer limit in replace integer num integer 1 limit inclusivethe array num complementary index 0indexe numsi numsn 1 equal number for example array 1234 complementary index numsi numsn 1 5return minimum number move require num complementary Example 1input num 1243 limit 4output 1explanation in 1 change num 1223 underline element changednums0 nums3 1 3 4nums1 nums2 2 2 4nums2 nums1 2 2 4nums3 nums0 3 1 4therefore numsi numsn1i 4 num complementaryExample 2input num 1221 limit 2output 2explanation in 2 move change num 2222 you change number 3 3 limitExample 3input num 1212 limit 2output 0explanation num complementary Constraintsn numslength2 n 1051 numsi limit 105n | 0array
|
you give array num n positive integersyou perform type operation element array number timesIf element divide 2for example array 1234 operation element array 1232if element odd multiply 2for example array 1234 operation element array 2234the deviation array maximum difference element arrayreturn minimum deviation array perform number operation Example 1input num 1234output 1explanation you transform array 1232 2232 deviation 3 2 1example 2input num 415203output 3explanation you transform array operation 42553 deviation 5 2 3example 3input num 2108output 3 Constraintsn numslength2 n 5 1041 numsi 109 | 0array
|
you Goal Parser interpret string command the command consist alphabet G andor al order the Goal Parser interpret g stre g string o al string al the interpret string concatenate original orderGiven string command return Goal Parsers interpretation command Example 1input command GalOutput GoalExplanation the Goal Parser interpret command followsg G oal althe final concatenated result GoalExample 2input command GalOutput GooooalExample 3input command alGalGOutput alGalooG Constraints1 commandlength 100command consist G andor al order | 2string
|
you give integer array num integer kIn operation pick number array sum equal k remove arrayreturn maximum number operation perform array Example 1input num 1234 k 5output 2explanation start num 1234 Remove number 1 4 num 23 Remove number 2 3 num there pair sum 5 total 2 operationsexample 2input num 31343 k 6output 1explanation start num 31343 Remove 3s num 143there pair sum 6 total 1 operation Constraints1 numslength 1051 numsi 1091 k 109 | 0array
|
you give integer array num integer k you ask distribute array k subset equal size equal element subsetA subset incompatibility difference maximum minimum element arrayreturn minimum possible sum incompatibility k subset distribute array optimally return 1 possibleA subset group integer appear array particular order Example 1input num 1214 k 2output 4explanation the optimal distribution subset 12 14the incompatibility 21 41 4note 11 24 result small sum subset contain 2 equal elementsExample 2input num 63813122 k 4Output 6explanation the optimal distribution subset 12 23 68 13the incompatibility 21 32 86 31 6example 3input num 533633 k 3output 1explanation it impossible distribute num 3 subset element equal subset Constraints1 k numslength 16numslength divisible k1 numsi numslength | 0array
|
you give integer array num sort nondecrease orderBuild return integer array result length num resulti equal summation absolute difference numsi element arrayin word resulti equal sumnumsinumsj 0 j numslength j 0indexed Example 1input num 235output 435explanation assume array 0indexe thenresult0 22 23 25 0 1 3 4result1 32 33 35 1 0 2 3result2 52 53 55 3 2 0 5example 2input num 146810output 2415131521 Constraints2 numslength 1051 numsi numsi 1 104 | 0array
|
Alice Bob turn play game Alice start firstthere n stone pile on player turn remove stone pile receive point base stone value Alice Bob value stone differentlyYou give integer array length n alicevalue bobvalues each alicevaluesi bobvaluesi represent Alice Bob respectively value ith stoneThe winner person point stone choose if player point game result draw both player play optimally both player know valuesdetermine result game andIf Alice win return 1if Bob win return 1if game result draw return 0 example 1input alicevalue 13 bobvalue 21output 1ExplanationIf Alice take stone 1 0indexed Alice receive 3 pointsbob choose stone 0 receive 2 pointsalice winsexample 2input alicevalue 12 bobvalue 31output 0explanationif Alice take stone 0 Bob take stone 1 1 pointdrawexample 3input alicevalue 243 bobvalue 167output 1explanationregardless Alice play Bob able point AliceFor example Alice take stone 1 Bob stone 2 Alice take stone 0 Alice 6 point Bobs 7bob win Constraintsn alicevalueslength bobvalueslength1 n 1051 aliceValuesi bobvaluesi 100 | 0array
|
you task deliver box storage port ship however ship limit number box total weight carryyou give array box boxesi portsi weighti integer portscount maxBoxes maxWeightportsi port need deliver ith box weightsi weight ith boxportscount number portsmaxboxe maxWeight respective box weight limit shipthe box need deliver order give the ship follow stepsthe ship number box box queue violating maxboxe maxWeight constraintsFor load box order ship trip port box need deliver deliver if ship correct port trip need box immediately deliveredthe ship make return trip storage box queuethe ship end storage box deliveredreturn minimum number trip ship need deliver box respective port Example 1input box 112111 portscount 2 maxboxe 3 maxweight 3output 4explanation the optimal strategy follow the ship take box queue go port 1 port 2 port 1 return storage 4 tripsso total number trip 4note box deliver box need deliver order ie second box need deliver port 2 boxexample 2input box 1233313124 portscount 3 maxboxe 3 maxweight 6output 6explanation the optimal strategy follow the ship take box go port 1 return storage 2 trip the ship take second fourth box go port 3 return storage 2 trip the ship take fifth box go port 3 return storage 2 tripsso total number trip 2 2 2 6example 3input box 141221213234 portscount 3 maxboxe 6 maxweight 7output 6explanation the optimal strategy follow the ship take second box go port 1 return storage 2 trip the ship take fourth box go port 2 return storage 2 trip the ship take fifth sixth box go port 3 return storage 2 tripsso total number trip 2 2 2 6 Constraints1 boxeslength 1051 portscount maxboxe maxweight 1051 portsi portscount1 weightsi maxweight | 0array
|
a decimal number call decibinary digits 0 1 lead zero for example 101 1100 decibinary 112 3001 notGiven string n represent positive decimal integer return minimum number positive decibinary number need sum n Example 1input n 32output 3explanation 10 11 11 32example 2input n 82734output 8Example 3input n 27346209830709182346output 9 Constraints1 nlength 105n consist digitsn contain lead zero represent positive integer | 2string
|
Alice Bob turn play game Alice start firstThere n stone arrange row on player turn remove leftmost stone rightmost stone row receive point equal sum remain stone value row the winner high score stone leave removeBob find lose game poor Bob lose decide minimize score difference Alices goal maximize difference scoregiven array integer stone stonesi represent value ith stone leave return difference Alice Bobs score play optimally example 1input stone 53142output 6explanation Alice remove 2 get 5 3 1 4 13 point Alice 13 Bob 0 stone 5314 Bob remove 5 get 3 1 4 8 point Alice 13 Bob 8 stone 314 Alice remove 3 get 1 4 5 point Alice 18 Bob 8 stone 14 Bob remove 1 get 4 point Alice 18 Bob 12 stone 4 Alice remove 4 get 0 point Alice 18 Bob 12 stone the score difference 18 12 6example 2input stone 7905110010102output 122 Constraintsn stoneslength2 n 10001 stonesi 1000 | 0array
|
give n cuboid dimension ith cuboid cuboidsi widthi lengthi heighti 0indexed choose subset cuboid place otheryou place cuboid cuboid j widthi widthj lengthi lengthj heighti heightj you rearrange cuboid dimension rotate cuboidReturn maximum height stack cuboid Example 1input cuboid 504520953753452312output 190explanationcuboid 1 place 53x37 face height 95cuboid 0 place 45x20 face height 50Cuboid 2 place 23x12 face height 45The total height 95 50 45 190example 2input cuboid 38254576353output 76explanationyou can not place cuboid otherWe choose cuboid 1 rotate 35x3 face height 76example 3input cuboid 711177171111717111771771117117output 102ExplanationAfter rearrange cuboid cuboid dimensionyou place 11x7 cuboid height 17the maximum height stack cuboid 6 17 102 Constraintsn cuboidslength1 n 1001 widthi lengthi heighti 100 | 0array
|
you give phone number string number number consist digits space andor dash you like reformat phone number certain manner Firstly remove space dash then group digit leave right block length 3 4 few digit the final digit group follows2 digit a single block length 23 digit a single block length 34 digits two block length 2 eachthe block join dash Notice reformatte process produce block length 1 produce block length 2return phone number format Example 1input number 12345 6output 123456explanation the digit 123456step 1 there 4 digit group 3 digits the 1st block 123step 2 there 3 digit remain single block length 3 the 2nd block 456joining block give 123456example 2input number 123 4567output 1234567explanation the digit 1234567step 1 there 4 digit group 3 digits the 1st block 123step 2 there 4 digit leave split block length 2 the block 45 67joining block give 1234567example 3input number 123 45678output 12345678explanation the digit 12345678step 1 the 1st block 123step 2 the 2nd block 456step 3 there 2 digit leave single block length 2 the 3rd block 78joining block give 12345678 Constraints2 numberlength 100number consist digit character there digit number | 2string
|
you give array positive integer num want erase subarray contain unique element the score erase subarray equal sum elementsreturn maximum score erase exactly subarrayAn array b call subarray form contiguous subsequence equal alal1ar lr Example 1input num 42456output 17explanation the optimal subarray 2456example 2input num 521252125output 8explanation the optimal subarray 521 125 Constraints1 numslength 1051 numsi 104 | 0array
|
you give 0indexed integer array num integer kYou initially stand index 0 in jump k step forward go outside boundary array that jump index index range 1 minn 1 k inclusiveYou want reach index array index n 1 your score sum numsj index j visit arrayreturn maximum score example 1input num 112473 k 2output 7explanation you choose jump form subsequence 1143 underline the sum 7example 2input num 1052403 k 3output 17explanation you choose jump form subsequence 1043 underline the sum 17example 3input num 152041363 k 2output 0 Constraints1 numslength k 105104 numsi 104 | 0array
|
the school cafeteria offer circular square sandwich lunch break refer number 0 1 respectively all student stand queue each student prefer square circular sandwichesThe number sandwich cafeteria equal number student the sandwich place stack at stepIf student queue prefer sandwich stack leave queueOtherwise leave queue endthis continue queue student want sandwich unable eatyou give integer array student sandwich sandwichesi type ith sandwich stack 0 stack studentsj preference jth student initial queue j 0 queue Return number student unable eat Example 1input student 1100 sandwich 0101output 0 Explanation Front student leave sandwich return end line make student 1001 Front student leave sandwich return end line make student 0011 Front student take sandwich leave line make student 011 sandwich 101 front student leave sandwich return end line make student 110 front student take sandwich leave line make student 10 sandwich 01 front student leave sandwich return end line make student 01 front student take sandwich leave line make student 1 sandwich 1 front student take sandwich leave line make student sandwich hence student able eatexample 2input student 111001 sandwich 100011output 3 constraints1 studentslength sandwicheslength 100studentslength sandwicheslengthsandwichesi 0 1studentsi 0 1 | 0array
|
there restaurant single chef you give array customer customersi arrivali timeiarrivali arrival time ith customer the arrival time sort nondecrease ordertimei time need prepare order ith customerWhen customer arrive give chef order chef start prepare idle the customer wait till chef finish prepare order the chef prepare food customer time the chef prepare food customer order give inputReturn average wait time customer solution 105 actual answer consider accept Example 1input customer 122543output 500000explanation1 the customer arrive time 1 chef take order start prepare immediately time 1 finish time 3 wait time customer 3 1 22 the second customer arrive time 2 chef take order start prepare time 3 finish time 8 wait time second customer 8 2 63 the customer arrive time 4 chef take order start prepare time 8 finish time 11 wait time customer 11 4 7so average wait time 2 6 7 3 5example 2input customer 5254103201output 325000explanation1 the customer arrive time 5 chef take order start prepare immediately time 5 finish time 7 wait time customer 7 5 22 the second customer arrive time 5 chef take order start prepare time 7 finish time 11 wait time second customer 11 5 63 the customer arrive time 10 chef take order start prepare time 11 finish time 14 wait time customer 14 10 44 the fourth customer arrive time 20 chef take order start prepare immediately time 20 finish time 21 wait time fourth customer 21 20 1so average wait time 2 6 4 1 4 325 Constraints1 customerslength 1051 arrivali timei 104arrivali arrivali1 | 0array
|
you give binary string binary consist 0s 1s you apply follow operation number timesoperation 1 if number contain substre 00 replace 10For example 00010 10010operation 2 if number contain substre 10 replace 01for example 00010 00001return maximum binary string obtain number operation binary string x great binary string y xs decimal representation great ys decimal representation Example 1input binary 000110output 111011explanation a valid transformation sequence be000110 000101 000101 100101 100101 110101 110101 110011 110011 111011example 2input binary 01output 01explanation 01 transform Constraints1 binarylength 105binary consist 0 1 | 2string
|
you give integer array num integer k nums comprise 0s 1s in choose adjacent index swap valuesreturn minimum number move require num k consecutive 1s Example 1input num 100101 k 2output 1explanation in 1 num 100011 2 consecutive 1sexample 2input num 10000011 k 3output 5explanation in 5 move leftmost 1 shift right num 00000111example 3input num 1101 k 2output 0explanation num 2 consecutive 1s Constraints1 numslength 105numsi 0 11 k sumnum | 0array
|
you give stre s length Split string half equal length let half b second halftwo string alike number vowel e o u a e I o u Notice s contain uppercase lowercase lettersreturn true b alike Otherwise return false example 1input s bookoutput trueexplanation bo b ok 1 vowel b 1 vowel therefore alikeexample 2input s textbookoutput falseexplanation text b book 1 vowel b 2 therefore alikenotice vowel o count twice constraints2 slength 1000slength evens consist uppercase lowercase letter | 2string
|
there special kind apple tree grow apple day n day on ith day tree grow applesi apple rot daysi days day daysi apple rotten eat on day apple tree grow apple denote applesi 0 daysi 0you decide eat apple day doctor away Note eat n daysgiven integer array day apple length n return maximum number apple eat Example 1input apple 12352 day 32142output 7explanation you eat 7 apple on day eat apple grow day on second day eat apple grow second day on day eat apple grow second day after day apple grow day rot on fourth seventh day eat apple grow fourth dayexample 2input apple 300002 day 300002output 5explanation you eat 5 apple on day eat apple grow day do fouth fifth day on sixth seventh day eat apple grow sixth day Constraintsn appleslength dayslength1 n 2 1040 applesi daysi 2 104daysi 0 applesi 0 | 0array
|
you give array num consist nonnegative integer you give query array queriesi xi miThe answer ith query maximum bitwise XOR value xi element num exceed mi in word answer maxnumsj XOR xi j numsj mi if element num large mi answer 1return integer array answer answerlength querieslength answeri answer ith query Example 1input num 01234 query 311356output 337explanation1 0 1 integer great 1 0 xor 3 3 1 xor 3 2 the large 32 1 xor 2 33 5 XOR 2 7example 2input num 524663 query 1248163output 1515 Constraints1 numslength querieslength 105queriesilength 20 numsj xi mi 109 | 0array
|
you assign box truck you give 2D array boxtypes boxTypesi numberOfBoxesi numberOfUnitsPerBoxinumberOfBoxesi number box type inumberofunitsperboxi number unit box type iYou give integer trucksize maximum number box truck you choose box truck long number box exceed trucksizereturn maximum total number unit truck example 1input boxtypes 132231 trucksize 4Output 8explanation there 1 box type contain 3 unit 2 box second type contain 2 unit 3 box type contain 1 unit eachyou box second type box typethe total number unit 1 3 2 2 1 1 8example 2input boxtypes 510254739 truckSize 10output 91 Constraints1 boxtypeslength 10001 numberOfBoxesi numberofunitsperboxi 10001 truckSize 106 | 0array
|
a good meal meal contain exactly different food item sum deliciousness equal power twoYou pick different food good mealgiven array integer deliciousness deliciousnessi deliciousness ith item food return number different good meal list modulo 109 7note item different index consider different deliciousness value Example 1input deliciousness 13579output 4explanation the good meal 13 17 35 79their respective sum 4 8 8 16 power 2example 2Input deliciousness 1113337output 15explanation the good meal 11 3 way 13 9 way 17 3 way Constraints1 deliciousnesslength 1050 deliciousnessi 220 | 0array
|
a split integer array good ifThe array split nonempty contiguous subarray name leave mid right respectively leave rightthe sum element leave equal sum element mid sum element mid equal sum element rightGiven num array nonnegative integer return number good way split num as number large return modulo 109 7 Example 1input num 111output 1explanation the good way split num 1 1 1example 2input num 122250output 3explanation there good way split nums1 2 22501 22 25012 22 50example 3input num 321output 0explanation there good way split num Constraints3 numslength 1050 numsi 104 | 0array
|
you give array target consist distinct integer integer array arr duplicatesIn operation insert integer position arr for example arr 1412 add 3 middle 14312 note insert integer beginning end arrayreturn minimum number operation need target subsequence arra 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 target 513 arr 94234output 2explanation you add 5 1 way make arr 5941234 target subsequence arrexample 2input target 648132 arr 47623861output 3 Constraints1 targetlength arrlength 1051 targeti arri 109target contain duplicate | 0array
|
you give stre s integer x y you perform type operation number timesremove substre ab gain x pointsfor example remove ab cabxbae cxbaeremove substre ba gain y pointsfor example remove ba cabxbae cabxeReturn maximum point gain apply operation s Example 1input s cdbcbbaaabab x 4 y 5output 19explanation Remove ba underline cdbcbbaaabab now s cdbcbbaaab 5 point add score Remove ab underline cdbcbbaaab now s cdbcbbaa 4 point add score Remove ba underline cdbcbbaa now s cdbcba 5 point add score Remove ba underline cdbcba now s cdbc 5 point add scoretotal score 5 4 5 5 19example 2input s aabbaaxybbaabb x 5 y 4Output 20 Constraints1 slength 1051 x y 104s consist lowercase english letter | 2string
|
give integer n find sequence satisfie followingthe integer 1 occur sequenceeach integer 2 n occur twice sequenceFor integer 2 n distance occurrence exactly ithe distance number sequence ai aj absolute difference index j iReturn lexicographically large sequence it guarantee give constraint solutionA sequence lexicographically large sequence b length position b differ sequence number great correspond number b for example 0190 lexicographically large 0156 position differ number 9 great 5 example 1input n 3output 31232explanation 23213 valid sequence 31232 lexicographically large valid sequenceexample 2input n 5output 531435242 Constraints1 n 20 | 0array
|
you give array pair pairsi xi yi andThere duplicatesxi yiLet way number root tree satisfy follow conditionsthe tree consist node value appear pairsA pair xi yi exist pair xi ancestor yi yi ancestor xiNote tree binary treeTwo way consider different node different parent waysreturn0 way 01 way 12 way 1A root tree tree single root node edge orient outgoing rootAn ancestor node node path root node exclude node the root ancestor Example 1input pair 1223output 1explanation there exactly valid rooted tree show figureexample 2input pair 122313output 2explanation there multiple valid root tree three show figuresexample 3input pair 12232415output 0explanation there valid rooted tree constraints1 pairslength 1051 xi yi 500the element pair unique | 1graph
|
there hide integer array arr consist n nonnegative integersIt encode integer array encode length n 1 encodedi arri XOR arri 1 for example arr 1021 encode 123you give encode array you give integer element arr ie arr0return original array arr it prove answer exist unique Example 1input encode 123 1output 1021explanation if arr 1021 1 encode 1 XOR 0 0 xor 2 2 xor 1 123example 2input encode 6273 4Output 42074 Constraints2 n 104encodedlength n 10 encodedi 1050 105 | 0array
|
you give integer array job jobsi time take complete ith jobThere k worker assign job each job assign exactly worker the work time worker sum time take complete job assign your goal devise optimal assignment maximum work time worker minimizedreturn minimum possible maximum work time assignment Example 1input job 323 k 3output 3explanation by assign person job maximum time 3example 2input job 12478 k 2output 11explanation Assign job follow wayWorker 1 1 2 8 work time 1 2 8 11worker 2 4 7 work time 4 7 11the maximum work time 11 Constraints1 k jobslength 121 jobsi 107 | 0array
|
you give array rectangle rectanglesi li wi represent ith rectangle length li width wiYou cut ith rectangle form square length k k li k wi for example rectangle 46 cut square length 4let maxLen length large square obtain give rectanglesreturn number rectangle square length maxLen Example 1input rectangle 5839512165output 3explanation the large square rectangle length 5355the large possible square length 5 3 rectanglesExample 2input rectangle 23374337output 3 constraints1 rectangleslength 1000rectanglesilength 21 li wi 109li wi | 0array
|
give array num distinct positive integer return number tuple b c d b c d b c d element num b c d Example 1input num 2346output 8explanation there 8 valid tuples2634 2643 6234 62433426 4326 3462 4362example 2input num 124510output 16explanation there 16 valid tuples11025 11052 10125 1015225110 25101 52110 5210121045 21054 10245 1025445210 45102 54210 54102 Constraints1 numslength 10001 numsi 104All element num distinct | 0array
|
you give binary matrix matrix size m x n allow rearrange column matrix orderreturn area large submatrix matrix element submatrix 1 reorder column optimally example 1input matrix 001111101output 4explanation you rearrange column show abovethe large submatrix 1s bold area 4example 2input matrix 10101output 3explanation you rearrange column show abovethe large submatrix 1s bold area 3example 3input matrix 110101output 2explanation Notice rearrange entire column way submatrix 1s large area 2 Constraintsm matrixlengthn matrixilength1 m n 105matrixij 0 1 | 0array
|
there biker go road trip the road trip consist n 1 point different altitude the biker start trip point 0 altitude equal 0you give integer array gain length n gaini net gain altitude point 1 0 n return high altitude point example 1input gain 51507output 1explanation the altitude 054116 the high 1example 2input gain 4321432output 0explanation the altitude 047910631 the high 0 Constraintsn gainlength1 n 100100 gaini 100 | 0array
|
on social network consist m user friendship user user communicate know common languageyou give integ n array language array friendship wherethere n language number 1 nlanguagesi set language ith user know andfriendshipsi ui vi denote friendship user ui viYou choose language teach user friend communicate Return minimum number user need teachnote friendship transitive meaning x friend y y friend z do not guarantee x friend z Example 1input n 2 language 1212 friendship 121323output 1explanation you teach user 1 second language user 2 languageExample 2input n 3 language 213123 friendship 14123423output 2explanation Teach language user 1 3 yield user teach Constraints2 n 500languageslength m1 m 5001 languagesilength n1 languagesij n1 ui vi languageslength1 friendshipslength 500all tuple ui vi uniquelanguagesi contain unique value | 0array
|
there integer array perm permutation n positive integer n oddIt encode integer array encode length n 1 encodedi permi XOR permi 1 for example perm 132 encode 21given encode array return original array perm it guarantee answer exist unique Example 1input encode 31output 123explanation if perm 123 encode 1 xor 22 xor 3 31example 2input encode 6546output 24153 Constraints3 n 105n oddencodedlength n 1 | 0array
|
you give 2D integer array query for queriesi queriesi ni ki find number different way place positive integer array size ni product integer ki as number way large answer ith query number way modulo 109 7Return integer array answer answerlength querieslength answeri answer ith query Example 1input query 265173660output 4150734910explanation each query independent26 there 4 way fill array size 2 multiply 6 16 23 32 6151 there 1 way fill array size 5 multiply 1 1111173660 there 1050734917 way fill array size 73 multiply 660 1050734917 modulo 109 7 50734910example 2input query 1122334455output 123105 Constraints1 querieslength 1041 ni ki 104 | 0array
|
you give string time form hhmm digit string hide represent the valid time inclusively 0000 2359return late valid time time replace hide digit example 1input time 20output 2350explanation the late hour begin digit 2 23 late minute ending digit 0 50example 2input time 03output 0939example 3input time 122output 1922 Constraintstime format hhmmIt guarantee produce valid time give string | 2string
|
you give string b consist lowercase letter in operation change character b lowercase letterYour goal satisfy follow conditionsevery letter strictly letter b alphabetEvery letter b strictly letter alphabetBoth b consist distinct letterreturn minimum number operation need achieve goal Example 1input aba b caaOutput 2explanation consider good way condition true1 Change b ccc 2 operation letter letter b2 Change bbb b aaa 3 operation letter b letter a3 Change aaa b aaa 2 operation b consist distinct letterthe good way 2 operation condition 1 condition 3example 2input dabadd b cdaoutput 3explanation the good way condition 1 true change b eee Constraints1 alength blength 105a b consist lowercase letter | 2string
|
you give 2D matrix size m x n consist nonnegative integer you give integer kThe value coordinate b matrix XOR matrixij 0 m 0 j b n 0indexedfind kth large value 1indexed coordinate matrix Example 1input matrix 5216 k 1output 7explanation the value coordinate 01 5 XOR 2 7 large valueexample 2input matrix 5216 k 2output 5explanation the value coordinate 00 5 5 2nd large valueexample 3input matrix 5216 k 3output 4explanation the value coordinate 10 5 xor 1 4 3rd large value Constraintsm matrixlengthn matrixilength1 m n 10000 matrixij 1061 k m n | 0array
|
there integer array num consist n unique element forget however remember pair adjacent element numsyou give 2D integer array adjacentPairs size n 1 adjacentPairsi ui vi indicate element ui vi adjacent numsIt guarantee adjacent pair element numsi numsi1 exist adjacentpair numsi numsi1 numsi1 numsi the pair appear orderreturn original array num if multiple solution return Example 1input adjacentpairs 213432output 1234explanation this array adjacent pair adjacentpairsnotice adjacentpairsi lefttoright orderexample 2input adjacentpair 421431output 2413explanation there negative numbersanother solution 3142 acceptedexample 3input adjacentpair 100000100000output 100000100000 Constraintsnumslength nadjacentpairslength n 1adjacentpairsilength 22 n 105105 numsi ui vi 105There exist num adjacentpairs pair | 0array
|
you give 0indexed array positive integer candiescount candiesCounti represent number candy ith type you give 2D array query queriesi favoriteTypei favoriteDayi dailycapiyou play game follow rulesyou start eat candy day 0you eat candy type eat candy type 1you eat candy day eat candiesconstruct boolean array answer answerlength querieslength answeri true eat candy type favoriteTypei day favoritedayi eat dailycapi candy day false note eat different type candy day provide follow rule 2return construct array answer Example 1input candiesCount 74538 query 0224242131000000000output truefalsetrueexplanation1 if eat 2 candy type 0 day 0 2 candy type 0 day 1 eat candy type 0 day 22 you eat 4 candy day if eat 4 candy day eat 4 candy type 0 day 0 4 candy type 0 type 1 day 1 on day 2 eat 4 candy type 1 type 2 eat candy type 4 day 23 if eat 1 candy day eat candy type 2 day 13example 2input candiesCount 52641 query 3124103310100410030131output falsetruetruefalsefalse Constraints1 candiescountlength 1051 candiesCounti 1051 querieslength 105queriesilength 30 favoriteTypei candiescountlength0 favoritedayi 1091 dailycapi 109 | 0array
|
give string s return true possible split string s nonempty palindromic substring otherwise return falseA string say palindrome string reverse Example 1input s abcbddoutput trueexplanation abcbdd bcb dd substring palindromesExample 2Input s bcbddxyoutput falseexplanation s split 3 palindrome Constraints3 slength 2000s consist lowercase english letter | 2string
|
you give integer array num the unique element array element appear exactly arrayreturn sum unique element num Example 1input num 1232output 4explanation the unique element 13 sum 4example 2input num 11111output 0explanation there unique element sum 0example 3input num 12345output 15explanation the unique element 12345 sum 15 Constraints1 numslength 1001 numsi 100 | 0array
|
you give integer array num the absolute sum subarray numsl numsl1 numsr1 numsr absnumsl numsl1 numsr1 numsrReturn maximum absolute sum possibly subarray numsnote absx define followsIf x negative integer absx xIf x nonnegative integer absx x Example 1input num 13234output 5explanation the subarray 23 absolute sum abs23 abs5 5Example 2input num 251432output 8explanation the subarray 514 absolute sum abs514 abs8 8 Constraints1 numslength 105104 numsi 104 | 0array
|
give string s consist character b c you ask apply follow algorithm string number timespick nonempty prefix string s character prefix equalPick nonempty suffix string s character suffix equalthe prefix suffix intersect indexThe character prefix suffix samedelete prefix suffixreturn minimum length s perform operation number time possibly zero time Example 1input s caoutput 2explanation you can not remove character string stay isexample 2input s cabaabacoutput 0explanation an optimal sequence operation take prefix c suffix c remove s abaaba take prefix suffix remove s baab Take prefix b suffix b remove s aa take prefix suffix remove s example 3input s aabccabbaOutput 3explanation an optimal sequence operation take prefix aa suffix remove s bccabb take prefix b suffix bb remove s cca Constraints1 slength 105s consist character b c | 2string
|
you give array event eventsi startdayi enddayi valuei the ith event start startdayi end enddayi attend event receive value valuei you give integer k represent maximum number event attendyou attend event time if choose attend event attend entire event note end day inclusive attend event start end dayreturn maximum sum value receive attend event example 1input event 124343231 k 2output 7Explanation choose green event 0 1 0indexed total value 4 3 7example 2input event 1243432310 k 2output 10explanation Choose event 2 total value 10notice attend event overlap attend k eventsExample 3input event 111222333444 k 3output 9explanation although event overlap attend 3 event Pick highest value Constraints1 k eventslength1 k eventslength 1061 startdayi enddayi 1091 valuei 106 | 0array
|
give array num return true array originally sort nondecrease order rotate number position include zero Otherwise return falsethere duplicate original arrayNote an array a rotate x position result array b length Ai Bix Alength modulo operation Example 1input num 34512output trueExplanation 12345 original sort arrayyou rotate array x 3 position begin element value 3 34512example 2input num 2134output falseexplanation there sort array rotate numsexample 3input num 123output trueExplanation 123 original sort arrayyou rotate array x 0 position ie rotation num Constraints1 numslength 1001 numsi 100 | 0array
|
you give string word1 word2 you want construct string merge follow way word1 word2 nonempty choose follow optionsif word1 nonempty append character word1 merge delete word1For example word1 abc merge dv choose operation word1 bc merge dvaif word2 nonempty append character word2 merge delete word2For example word2 abc merge choose operation word2 bc merge aReturn lexicographically large merge constructa stre lexicographically large string b length position b differ character strictly large corresponding character b for example abcd lexicographically large abcc position differ fourth character d great c example 1input word1 cabaa word2 bcaaaoutput cbcabaaaaaexplanation one way lexicographically large merge take word1 merge c word1 abaa word2 bcaaa take word2 merge cb word1 abaa word2 caaa take word2 merge cbc word1 abaa word2 aaa take word1 merge cbca word1 baa word2 aaa take word1 merge cbcab word1 aa word2 aaa Append remain 5 word1 word2 end mergeexample 2input word1 abcabc word2 abdcabaoutput abdcabcabcaba constraints1 word1length word2length 3000word1 word2 consist lowercase english letter | 2string
|
you give integer array num integer goalYou want choose subsequence num sum element close possible goal that sum subsequence element sum want minimize absolute difference abssum goalreturn minimum possible value abssum goalNote subsequence array array form remove element possibly original array Example 1input num 5735 goal 6output 0explanation Choose array subsequence sum 6this equal goal absolute difference 0example 2input num 79152 goal 5output 1explanation Choose subsequence 792 sum 4the absolute difference abs4 5 abs1 1 minimumExample 3input num 123 goal 7output 7 Constraints1 numslength 40107 numsi 107109 goal 109 | 0array
|
you give string s consist character 0 1 in operation change 0 1 vice versathe string call alternate adjacent character equal for example stre 010 alternate string 0100 notReturn minimum number operation need s alternate Example 1input s 0100output 1explanation if change character 1 s 0101 alternatingexample 2input s 10output 0explanation s alternatingexample 3input s 1111output 2explanation you need operation reach 0101 1010 Constraints1 slength 104si 0 1 | 2string
|
give string s return number homogenous substring s since answer large return modulo 109 7a string homogenous character stre sameA substre contiguous sequence character string Example 1input s abbcccaaoutput 13explanation the homogenous substring list belowa appear 3 timesaa appear 1 timeb appear 2 timesbb appear 1 timec appear 3 timescc appear 2 timesccc appear 1 time3 1 2 1 3 2 1 13example 2input s xyOutput 2explanation the homogenous substring x yexample 3input s zzzzzOutput 15 Constraints1 slength 105s consist lowercase letter | 2string
|
you give integer array num ith bag contain numsi ball you give integer maxoperationsyou perform follow operation maxoperations timestake bag ball divide new bag positive number ballsfor example bag 5 ball new bag 1 4 ball new bag 2 3 ballsYour penalty maximum number ball bag you want minimize penalty operationsreturn minimum possible penalty perform operation Example 1input num 9 maxoperations 2output 3explanation Divide bag 9 ball bag size 6 3 9 63 Divide bag 6 ball bag size 3 3 63 333the bag number ball 3 ball penalty 3 return 3example 2input num 2482 maxoperation 4output 2explanation Divide bag 8 ball bag size 4 4 2482 24442 Divide bag 4 ball bag size 2 2 24442 222442 Divide bag 4 ball bag size 2 2 222442 2222242 Divide bag 4 ball bag size 2 2 2222242 22222222the bag number ball 2 ball penalty 2 return 2 Constraints1 numslength 1051 maxoperation numsi 109 | 0array
|
you give undirected graph you give integer n number node graph array edge edgesi ui vi indicate undirected edge ui via connected trio set nod edge pair themthe degree connect trio number edge endpoint trio notReturn minimum degree connect trio graph 1 graph connect trio Example 1input n 6 edge 121332415236output 3explanation there exactly trio 123 the edge form degree bolde figure aboveexample 2input n 7 edge 1341432556677526output 0explanation there exactly trios1 143 degree 02 256 degree 23 567 degree 2 Constraints2 n 400edgesilength 21 edgeslength n n1 21 ui vi nui vithere repeat edge | 1graph
|
a string s nice letter alphabet s contain appear uppercase lowercase for example ababb nice a appear B b appear however aba b appear b notgiven string s return long substre s nice if multiple return substre early occurrence if return stre Example 1input s YazaAayOutput aaaexplanation aaa nice string Aa letter alphabet s a appearaaa long nice substringExample 2input s BbOutput BbExplanation Bb nice string b b appear the string substringExample 3input s cOutput Explanation there nice substring Constraints1 slength 100s consist uppercase lowercase english letter | 2string
|
Subsets and Splits