question
stringlengths
58
4.29k
label
class label
3 classes
you give m x n matrix mat row sort nondecrease order integer kYou allow choose exactly element row form arrayreturn kth small array sum possible array Example 1input mat 1311246 k 5output 7explanation choose element row k small sum are12 14 32 34 16 where 5th sum 7example 2input mat 1311246 k 9Output 17example 3input mat 11010145236 k 7Output 9explanation choose element row k small sum are112 113 142 143 116 152 153 where 7th sum 9 Constraintsm matlengthn matlengthi1 m n 401 matij 50001 k min200 nmmati nondecrease array
0array
you give integer array target integer nYou stack follow operationspush push integer stackpop remove integ stackyou stream integer range 1 nUse stack operation number stack equal target you follow follow rulesIf stream integer pick integer stream push stackIf stack pop integer stackif moment element stack equal target read new integer stream operation stackreturn stack operation need build target follow mention rule if multiple valid answer return Example 1input target 13 n 3output pushpushpoppushexplanation initially stack s the element stackread 1 stream push stack s 1read 2 stream push stack s 12pop integer stack s 1read 3 stream push stack s 13example 2input target 123 n 3output pushpushpushexplanation initially stack s the element stackread 1 stream push stack s 1read 2 stream push stack s 12read 3 stream push stack s 123example 3input target 12 n 4output pushpushexplanation initially stack s the element stackread 1 stream push stack s 1read 2 stream push stack s 12since stack equal target stop stack operationsthe answer read integer 3 stream accept Constraints1 targetlength 1001 n 1001 targeti ntarget strictly increase
0array
give array integer arrwe want select index j k 0 j k arrlengthLets define b followsa arri arri 1 arrj 1b arrj arrj 1 arrkNote denote bitwisexor operationReturn number triplet j k where b Example 1input arr 23167output 4explanation the triplet 012 022 234 244example 2input arr 11111output 10 Constraints1 arrlength 3001 arri 108
0array
give undirected tree consist n vertex number 0 n1 apple vertex you spend 1 second walk edge tree return minimum time second spend collect apple tree start vertex 0 come vertexthe edge undirected tree give array edge edgesi ai bi mean exist edge connect vertex ai bi additionally boolean array hasapple hasapplei true mean vertex apple apple Example 1input n 7 edge 010214152326 hasapple falsefalsetruefalsetruetruefalseoutput 8 Explanation the figure represent give tree red vertex apple one optimal path collect apple show green arrow Example 2input n 7 edge 010214152326 hasapple falsefalsetruefalsefalsetruefalseOutput 6explanation the figure represent give tree red vertex apple one optimal path collect apple show green arrow Example 3Input n 7 edge 010214152326 hasapple falsefalsefalsefalsefalsefalsefalseoutput 0 Constraints1 n 105edgeslength n 1edgesilength 20 ai bi n 1fromi toihasapplelength n
1graph
give rectangular pizza represent row x col matrix contain follow character a apple cell give integer k you cut pizza k piece k1 cut for cut choose direction vertical horizontal choose cut position cell boundary cut pizza piece if cut pizza vertically leave pizza person if cut pizza horizontally upper pizza person give piece pizza personreturn number way cut pizza piece contain apple since answer huge number return modulo 109 7 Example 1input pizza AAAA k 3output 3 Explanation the figure show way cut pizza note piece contain appleexample 2input pizza AAA k 3Output 1Example 3input pizza AA k 1Output 1 Constraints1 row col 50rows pizzalengthcol pizzailength1 k 10pizza consist character a
0array
the power string maximum length nonempty substring contain unique charactergiven string s return power s Example 1input s leetcodeoutput 2explanation the substring ee length 2 character e onlyExample 2Input s abbcccddddeeeeedcbaoutput 5explanation the substre eeeee length 5 character e Constraints1 slength 500s consist lowercase english letter
2string
give integer n return list simplify fraction 0 1 exclusive denominator lessthanorequalto n you return answer order Example 1input n 2output 12Explanation 12 unique fraction denominator lessthanorequalto 2Example 2Input n 3Output 121323example 3input n 4Output 1213142334explanation 24 simplified fraction simplify 12 Constraints1 n 100
2string
give binary tree root node X tree name good path root X node value great XReturn number good nod binary tree Example 1input root 3143null15output 4explanation Nodes blue goodroot Node 3 good nodenode 4 34 maximum value path start rootNode 5 345 maximum value pathnode 3 313 maximum value pathexample 2input root 33null42output 3explanation Node 2 3 3 2 good 3 high itexample 3input root 1output 1explanation Root consider good ConstraintsThe number nod binary tree range 1 105each node value 104 104
1graph
give array integer cost integer target return maximum integer paint follow rulesThe cost painting digit 1 give costi 0indexedthe total cost equal targetthe integer 0 digitssince answer large return string if way paint integer give condition return 0 example 1input cost 432567255 target 9output 7772explanation the cost paint digit 7 2 digit 2 3 then cost7772 23 31 9 you paint 977 7772 large numberDigit cost 1 4 2 3 3 2 4 5 5 6 6 7 7 2 8 5 9 5example 2input cost 765556878 target 12output 85explanation the cost paint digit 8 7 digit 5 5 then cost85 7 5 12example 3input cost 246246444 target 5output 0explanation it impossible paint integer total cost equal target Constraintscostlength 91 costi target 5000
0array
give integer array starttime endtime give integer queryTimeThe ith student start homework time startTimei finish time endtimeireturn number student homework time querytime more formally return number student querytime lay interval startTimei endtimei inclusive Example 1input starttime 123 endtime 327 queryTime 4output 1explanation we 3 student whereThe student start homework time 1 finished time 3 was not time 4the second student start homework time 2 finished time 2 was not time 4the student start homework time 3 finish time 7 student homework time 4example 2input starttime 4 endtime 4 queryTime 4output 1explanation the student homework queryTime ConstraintsstartTimelength endtimelength1 starttimelength 1001 startTimei endTimei 10001 queryTime 1000
0array
give sentence text a sentence string spaceseparate word follow formatFirst letter upper caseEach word text separate single spaceyour task rearrange word text word rearrange increase order length if word length arrange original orderreturn new text follow format show Example 1input text Leetcode coolOutput Is cool leetcodeexplanation there 3 word Leetcode length 8 length 2 cool length 4Output order length new word start capital letterExample 2input text keep calm code onOutput on calm codeexplanation output order followsOn 2 lettersand 3 letterskeep 4 letter case tie order position original textcalm 4 letterscode 4 lettersexample 3input text to beoutput to Constraintstext begin capital letter contain lowercase letter single space words1 textlength 105
2string
Alice throw n dart large wall you give array darts dartsi xi yi position ith dart Alice throw wallBob know position n dart wall he want place dartboard radius r wall maximum number darts Alice throw lie dartboardGiven integer r return maximum number dart lie dartboard Example 1input dart 20200202 r 2output 4explanation Circle dartboard center 00 radius 2 contain pointsexample 2input dart 303026540978 r 5output 5explanation Circle dartboard center 04 radius 5 contain point point 78 Constraints1 dartslength 100dartsilength 2104 xi yi 1041 r 5000
0array
give sentence consist word separate single space searchword check searchword prefix word sentencereturn index word sentence 1indexed searchword prefix word if searchword prefix word return index word minimum index if word return 1A prefix string s lead contiguous substring s Example 1input sentence love eat burger searchWord burgOutput 4explanation burg prefix burger 4th word sentenceexample 2input sentence problem easy problem searchword prooutput 2explanation pro prefix problem 2nd 6th word sentence return 2 minimal indexExample 3input sentence tired searchWord yououtput 1explanation prefix word sentence Constraints1 sentencelength 1001 searchwordlength 10sentence consist lowercase english letter spacessearchWord consist lowercase english letter
2string
give string s integer k return maximum number vowel letter substre s length kVowel letter english e o u Example 1input s abciiidef k 3output 3explanation the substre iii contain 3 vowel lettersExample 2input s aeiou k 2output 2explanation any substre length 2 contain 2 vowelsExample 3input s leetcode k 3Output 2Explanation lee eet ode contain 2 vowel Constraints1 slength 105s consist lowercase english letters1 k slength
2string
give binary tree node value digit 1 9 a path binary tree say pseudopalindromic permutation node value path palindromereturn number pseudopalindromic path go root node leaf node example 1input root 23131null1output 2 Explanation the figure represent give binary tree there path go root node leaf node red path 233 green path 211 path 231 among path red path green path pseudopalindromic path red path 233 rearrange 323 palindrome green path 211 rearrange 121 palindromeExample 2input root 21113nullnullnullnullnull1output 1 Explanation the figure represent give binary tree there path go root node leaf node green path 211 path 2131 path 21 among path green path pseudopalindromic 211 rearrange 121 palindromeExample 3input root 9output 1 ConstraintsThe number nod tree range 1 1051 Nodeval 9
1graph
give array nums1 nums2Return maximum dot product nonempty subsequence nums1 nums2 lengthA subsequence array new array form original array delete character disturb relative position remain character ie 235 subsequence 12345 153 Example 1input nums1 2125 nums2 306output 18explanation take subsequence 22 nums1 subsequence 36 nums2their dot product 23 26 18example 2input nums1 32 nums2 267output 21explanation take subsequence 3 nums1 subsequence 7 nums2their dot product 37 21example 3input nums1 11 nums2 11output 1explanation take subsequence 1 nums1 subsequence 1 nums2their dot product 1 Constraints1 nums1length nums2length 5001000 nums1i nums2i 1000
0array
you give integer array equal length target arr in step select nonempty subarray arr reverse you allow number stepsreturn true arr equal target false Example 1input target 1234 arr 2413output trueexplanation you follow step convert arr target1 Reverse subarray 241 arr 14232 Reverse subarray 42 arr 12433 Reverse subarray 43 arr 1234there multiple way convert arr target way soexample 2input target 7 arr 7Output trueExplanation arr equal target reversesExample 3input target 379 arr 3711output falseexplanation arr value 9 convert target Constraintstargetlength arrlength1 targetlength 10001 targeti 10001 arri 1000
0array
give binary string s integ k return true binary code length k substring s otherwise return false Example 1input s 00110110 k 2output trueexplanation the binary code length 2 00 01 10 11 they find substring index 0 1 3 2 respectivelyexample 2input s 0110 k 1output trueexplanation the binary code length 1 0 1 clear exist substre Example 3input s 0110 k 2output falseexplanation the binary code 00 length 2 exist array Constraints1 slength 5 105si 0 11 k 20
2string
there total numcourse course label 0 numcourses 1 you give array prerequisite prerequisitesi ai bi indicate course ai want course biFor example pair 0 1 indicate course 0 course 1prerequisite indirect if course prerequisite course b course b prerequisite course c course prerequisite course cyou give array query queriesj uj vj for jth query answer course uj prerequisite course vj notReturn boolean array answer answerj answer jth query Example 1input numcourses 2 prerequisite 10 query 0110output falsetrueexplanation the pair 1 0 indicate course 1 course 0course 0 prerequisite course 1 opposite trueExample 2input numcourses 2 prerequisite query 1001output falsefalseexplanation there prerequisite course independentexample 3input numcourses 3 prerequisite 121020 query 1012output truetrue Constraints2 numcourses 1000 prerequisiteslength numcourses numcourses 1 2prerequisitesilength 20 ai bi n 1ai biall pair ai bi uniquethe prerequisites graph cycles1 querieslength 1040 ui vi n 1ui vi
1graph
you give row x cols matrix grid represent field cherry gridij represent number cherry collect j cellyou robot collect cherry yourobot 1 locate topleft corner 0 0 androbot 2 locate topright corner 0 col 1return maximum number cherry collection robot follow rule belowfrom cell j robot cell 1 j 1 1 j 1 j 1when robot pass cell it pick cherry cell cellWhen robot stay cell take cherriesboth robot outside grid momentboth robot reach row grid Example 1input grid 311251155211output 24explanation Path robot 1 2 describe color green blue respectivelycherrie take Robot 1 3 2 5 2 12cherrie take Robot 2 1 5 5 1 12total cherry 12 12 24example 2input grid 10000012000030209000003054001023006output 28explanation Path robot 1 2 describe color green blue respectivelycherrie take Robot 1 1 9 5 2 17cherrie take Robot 2 1 3 4 3 11total cherry 17 11 28 Constraintsrows gridlengthcol gridilength2 row col 700 gridij 100
0array
give array integer num choose different index j array return maximum value numsi1numsj1 example 1input num 3452output 12 Explanation if choose index i1 j2 index 0 maximum value nums11nums21 4151 34 12 Example 2input num 1545output 16explanation choosing index i1 j3 index 0 maximum value 5151 16example 3input num 37output 12 constraints2 numslength 5001 numsi 103
0array
you give rectangular cake size h x w array integer horizontalcut verticalcut wherehorizontalcutsi distance rectangular cake ith horizontal cut similarly andverticalcutsj distance leave rectangular cake jth vertical cutReturn maximum area piece cake cut horizontal vertical position provide array horizontalcut verticalcut since answer large number return modulo 109 7 Example 1input h 5 w 4 horizontalcut 124 verticalcut 13output 4 Explanation the figure represent give rectangular cake Red line horizontal vertical cut after cut cake green piece cake maximum areaExample 2input h 5 w 4 horizontalcut 31 verticalcut 1output 6explanation the figure represent give rectangular cake Red line horizontal vertical cut after cut cake green yellow piece cake maximum areaExample 3input h 5 w 4 horizontalcut 3 verticalcut 3output 9 constraints2 h w 1091 horizontalcutslength minh 1 1051 verticalCutslength minw 1 1051 horizontalCutsi h1 verticalCutsi wAll element horizontalcut distinctAll element verticalcut distinct
0array
there n city number 0 n 1 n 1 road way travel different city network form tree last year the ministry transport decide orient road direction narrowroad represent connection connectionsi ai bi represent road city ai city bithis year big event capital city 0 people want travel cityYour task consist reorient road city visit city 0 return minimum number edge changedits guarantee city reach city 0 reorder Example 1input n 6 connection 0113234045output 3explanation Change direction edge red node reach node 0 capitalExample 2input n 5 connection 10123234output 2explanation Change direction edge red node reach node 0 capitalExample 3input n 3 connection 1020output 0 Constraints2 n 5 104connectionslength n 1connectionsilength 20 ai bi n 1ai bi
1graph
give array num consist 2n element form x1x2xny1y2ynReturn array form x1y1x2y2xnyn Example 1input num 251347 n 3output 235417 Explanation since x12 x25 x31 y13 y24 y37 answer 235417example 2input num 12344321 n 4Output 14233241example 3input num 1122 n 2Output 1212 Constraints1 n 500numslength 2n1 numsi 103
0array
give array integer arr integer kA value arri say strong value arrj arri m arrj m m median arrayif arri m arrj m arri say strong arrj arri arrjReturn list strongest k value array return answer arbitrary ordermedian middle value order integer list More formally length list n median element position n 1 2 sorted list 0indexedfor arr 6 3 7 2 11 n 5 median obtain sort array arr 3 2 6 7 11 median arrm m 5 1 2 2 the median 6for arr 7 22 173 n 4 median obtain sort array arr 7 3 17 22 median arrm m 4 1 2 1 the median 3 Example 1input arr 12345 k 2Output 51explanation Median 3 element array sort strong 51423 the strong 2 element 5 1 1 5 accept answerplease note 5 3 1 3 5 strong 1 5 1example 2input arr 11355 k 2Output 55explanation Median 3 element array sort strong 55113 the strong 2 element 5 5example 3input arr 6711768 k 5output 118667explanation Median 7 element array sort strong 1186677any permutation 118667 accept Constraints1 arrlength 105105 arri 1051 k arrlength
0array
you browser tab start homepage visit url history number step forward history number stepsimplement BrowserHistory classbrowserhistorystring homepage Initializes object homepage browservoid visitstre url visit url current page it clear forward historystre backint step move step history if return x step history step x return x step return current url move history stepsstring forwardint step move step forward history if forward x step history step x forward x step return current url forwarding history step exampleinputbrowserhistoryvisitvisitvisitbackbackforwardvisitforwardbackbackleetcodecomgooglecomfacebookcomyoutubecom111linkedincom227outputnullnullnullnullfacebookcomgooglecomfacebookcomnulllinkedincomgooglecomleetcodecomexplanationbrowserhistory browserhistory new browserhistoryleetcodecombrowserhistoryvisitgooglecom you leetcodecom visit googlecombrowserhistoryvisitfacebookcom you googlecom visit facebookcombrowserhistoryvisityoutubecom you facebookcom visit youtubecombrowserhistoryback1 you youtubecom facebookcom return facebookcombrowserhistoryback1 you facebookcom googlecom return googlecombrowserhistoryforward1 you googlecom forward facebookcom return facebookcombrowserHistoryvisitlinkedincom you facebookcom visit linkedincombrowserhistoryforward2 you linkedincom forward stepsbrowserhistoryback2 you linkedincom step facebookcom googlecom return googlecombrowserhistoryback7 you googlecom step leetcodecom return leetcodecom Constraints1 homepagelength 201 urllength 201 step 100homepage url consist low case English lettersat 5000 call visit forward
0array
there row m house small city house paint n color label 1 n house paint summer paint againa neighborhood maximal group continuous house paint colorFor example house 12233211 contain 5 neighborhood 1 22 33 2 11given array house m x n matrix cost integer target wherehousesi color house 0 house paint yetcostij cost paint house color j 1return minimum cost painting remain house way exactly target neighborhood if possible return 1 example 1input house 00000 cost 11010110111051 m 5 n 2 target 3output 9explanation Paint house way 12211this array contain target 3 neighborhood 1 22 11cost paint house 1 1 1 1 5 9example 2input house 02120 cost 11010110111051 m 5 n 2 target 3output 11explanation some house paint Paint house way 22122this array contain target 3 neighborhood 22 1 22 cost paint house 10 1 11example 3input house 3123 cost 111111111111 m 4 n 3 target 3output 1explanation Houses paint total 4 neighborhood 3123 different target 3 Constraintsm houseslength costlengthn costilength1 m 1001 n 201 target m0 housesi n1 costij 104
0array
you give integer array price pricesi price ith item shopThere special discount item shop if buy ith item receive discount equivalent pricesj j minimum index j pricesj pricesi otherwise receive discount allReturn integer array answer answeri final price pay ith item shop consider special discount example 1input price 84623output 42423explanation for item 0 price08 receive discount equivalent prices14 final price pay 8 4 4for item 1 price14 receive discount equivalent prices32 final price pay 4 2 2for item 2 price26 receive discount equivalent prices32 final price pay 6 2 4for item 3 4 receive discount allexample 2input price 12345output 12345explanation in case item receive discount allexample 3input price 10116output 9016 Constraints1 priceslength 5001 pricesi 1000
0array
implement class SubrectangleQueries receive row x col rectangle matrix integer constructor support methods1 updateSubrectangleint row1 int col1 int row2 int col2 int newValueUpdates value newvalue subrectangle upper left coordinate row1col1 right coordinate row2col22 getvalueint row int colreturns current value coordinate rowcol rectangle example 1inputsubrectanglequeriesgetvalueupdatesubrectanglegetvaluegetvalueupdatesubrectanglegetvaluegetvalue121434321111020032502313032103102outputnull1null55null105explanationsubrectanglequerie subrectanglequerie new subrectanglequeries121434321111 the initial rectangle 4x3 look like 1 2 1 4 3 4 3 2 1 1 1 1subrectanglequeriesgetvalue0 2 return 1subrectanglequeriesupdatesubrectangle0 0 3 2 5 after update rectangle look like 5 5 5 5 5 5 5 5 5 5 5 5 subrectanglequeriesgetvalue0 2 return 5subrectanglequeriesgetvalue3 1 return 5subrectanglequeriesupdatesubrectangle3 0 3 2 10 after update rectangle look like 5 5 5 5 5 5 5 5 5 10 10 10 subrectanglequeriesgetvalue3 1 return 10subrectanglequeriesgetvalue0 2 return 5example 2inputsubrectanglequeriesgetvalueupdatesubrectanglegetvaluegetvalueupdatesubrectanglegetvalue111222333000022100002211222022outputnull1null100100null20explanationsubrectanglequeries subrectanglequerie new subrectanglequeries111222333subrectanglequeriesgetvalue0 0 return 1subrectanglequeriesupdatesubrectangle0 0 2 2 100subrectanglequeriesgetvalue0 0 return 100subrectanglequeriesgetvalue2 2 return 100subrectanglequeriesupdatesubrectangle1 1 2 2 20subrectanglequeriesgetvalue2 2 return 20 ConstraintsThere 500 operation consider method updateSubrectangle getValue1 row col 100rows rectanglelengthcol rectangleilength0 row1 row2 rows0 col1 col2 cols1 newValue rectangleij 1090 row rows0 col col
0array
you give array integer arr integer targetyou find nonoverlapping subarray arr sum equal target there multiple answer find answer sum length subarray minimumreturn minimum sum length require subarray return 1 find subarray Example 1input arr 32243 target 3output 2explanation only subarray sum 3 3 3 the sum length 2example 2Input arr 7347 target 7output 2explanation although nonoverlapping subarray sum 7 7 34 7 choose subarray sum length 2example 3Input arr 4326234 target 6output 1explanation we subarray sum 6 Constraints1 arrlength 1051 arri 10001 target 108
0array
give array house housesi location ith house street integer k allocate k mailbox streetreturn minimum total distance house near mailboxthe test case generate answer fit 32bit integer Example 1input house 1481020 k 3output 5explanation Allocate mailbox position 3 9 20minimum total distance house near mailbox 31 43 98 109 2020 5 example 2input house 2351218 k 2output 9explanation Allocate mailbox position 3 14minimum total distance house near mailbox 23 33 53 1214 1814 9 Constraints1 k houseslength 1001 housesi 104All integer house unique
0array
give array num we define run sum array runningsumi sumnums0numsireturn run sum num Example 1input num 1234output 13610explanation running sum obtain follow 1 12 123 1234example 2input num 11111output 12345explanation running sum obtain follow 1 11 111 1111 11111example 3input num 312101output 3461617 Constraints1 numslength 1000106 numsi 106
0array
give array integer arr integer k Find number unique integer remove exactly k element Example 1input arr 554 k 1output 1Explanation Remove single 4 5 leftExample 2Input arr 4311332 k 3output 2Explanation Remove 4 2 1s 3s 1 3 leave Constraints1 arrlength 1051 arri 1090 k arrlength
0array
you give integer array bloomDay integer m integer kYou want m bouquet to bouquet need use k adjacent flower gardenthe garden consist n flower ith flower bloom bloomDayi exactly bouquetreturn minimum number day need wait able m bouquet garden if impossible m bouquet return 1 example 1input bloomDay 1103102 m 3 k 1output 3explanation let happen day x mean flower bloom _ mean flower bloom gardenWe need 3 bouquet contain 1 flowerafter day 1 x _ _ _ _ bouquetafter day 2 x _ _ _ x bouquetsafter day 3 x _ x _ x 3 bouquet the answer 3example 2input bloomDay 1103102 m 3 k 2output 1explanation we need 3 bouquet 2 flower mean need 6 flower we 5 flower impossible need bouquet return 1example 3input bloomDay 77771277 m 2 k 3output 12Explanation we need 2 bouquet 3 flowershere garden 7 12 daysAfter day 7 x x x x _ x xWe bouquet flower bloom we bouquet flower bloom adjacentAfter day 12 x x x x x x xIt obvious bouquet different way ConstraintsbloomDaylength n1 n 1051 bloomDayi 1091 m 1061 k n
0array
you give tree n node number 0 n 1 form parent array parent parenti parent ith node the root tree node 0 find kth ancestor give nodeThe kth ancestor tree node kth node path node root nodeImplement TreeAncestor classTreeAncestorint n int parent Initializes object number nod tree parent arrayint getKthAncestorint node int k return kth ancestor give node node if ancestor return 1 Example 1inputtreeancestor getkthancestor getkthancestor getkthancestor7 1 0 0 1 1 2 2 3 1 5 2 6 3outputnull 1 0 1explanationtreeancestor treeancestor new treeancestor7 1 0 0 1 1 2 2treeancestorgetkthancestor3 1 return 1 parent 3treeancestorgetkthancestor5 2 return 0 grandparent 5treeancestorgetkthancestor6 3 return 1 ancestor Constraints1 k n 5 104parentlength nparent0 10 parenti n 0 n0 node nThere 5 104 query
1graph
your country infinite number lake Initially lake rain nth lake nth lake water if rain lake water flood your goal avoid flood lakegiven integer array rain whererainsi 0 mean rain rainsi lakerainsi 0 mean rain day choose lake day dry itreturn array ans whereanslength rainslengthansi 1 rainsi 0ansi lake choose dry ith day rainsi 0if multiple valid answer return if impossible avoid flood return arraynotice choose dry lake choose dry lake change Example 1input rain 1234output 1111explanation after day lake 1after second day lake 12after day lake 123after fourth day lake 1234theres day dry lake flood lakeexample 2input rain 120021output 112111explanation after day lake 1after second day lake 12after day dry lake 2 full lake 1After fourth day dry lake 1 there lakesafter fifth day lake 2after sixth day lake 12it easy scenario floodfree 111211 acceptable scenarioExample 3input rain 12012output Explanation after second day lake 12 we dry lake dayafter rain lake 12 its easy prove matter lake choose dry 3rd day flood Constraints1 rainslength 1050 rainsi 109
0array
give weight undirected connect graph n vertex number 0 n 1 array edge edgesi ai bi weighti represent bidirectional weighted edge node ai bi a minimum span tree MST subset graph edge connect vertex cycle minimum possible total edge weightfind critical pseudocritical edge give graph minimum span tree MST an mst edge deletion graph cause MST weight increase call critical edge on hand pseudocritical edge appear mst allnote return index edge order Example 1input n 5 edge 011121232032043343146output 012345explanation the figure describe graphthe following figure show possible MSTsNotice edge 0 1 appear mst critical edge return list outputthe edge 2 3 4 5 mst consider pseudocritical edge we add second list outputexample 2input n 4 edge 011121231031output 0123explanation we observe 4 edge equal weight choose 3 edge give 4 yield MST therefore 4 edge pseudocritical Constraints2 n 1001 edgeslength min200 n n 1 2edgesilength 30 ai bi n1 weighti 1000all pair ai bi distinct
1graph
you give array unique integer salary salaryi salary ith employeeReturn average salary employee exclude minimum maximum salary Answers 105 actual answer accept Example 1input salary 4000300010002000output 250000000explanation minimum salary maximum salary 1000 4000 respectivelyaverage salary exclude minimum maximum salary 20003000 2 2500example 2input salary 100020003000output 200000000explanation minimum salary maximum salary 1000 3000 respectivelyaverage salary exclude minimum maximum salary 2000 1 2000 Constraints3 salarylength 1001000 salaryi 106all integer salary unique
0array
give binary array num delete element itreturn size long nonempty subarray contain 1s result array Return 0 subarray Example 1input num 1101output 3explanation after delete number position 2 111 contain 3 number value 1sexample 2input num 011101101output 5explanation after delete number position 4 01111101 long subarray value 1s 11111example 3input num 111output 2explanation you delete element Constraints1 numslength 105numsi 0 1
0array
you give integer n indicate n course label 1 n you give array relation relationsi prevCoursei nextCoursei represent prerequisite relationship course prevcoursei course nextCoursei course prevCoursei take course nextCoursei also give integer kIn semester k course long take prerequisite previous semester course takingreturn minimum number semester need course the testcase generate possible course Example 1input n 4 relation 213114 k 2output 3explanation the figure represent give graphin semester course 2 3in second semester course 1in semester course 4example 2input n 5 relation 21314115 k 2output 4explanation the figure represent give graphin semester course 2 3 semesterin second semester course 4in semester course 1in fourth semester course 5 Constraints1 n 151 k n0 relationslength n n1 2relationsilength 21 prevcoursei nextCoursei nprevCoursei nextCourseiAll pair prevcoursei nextCoursei uniquethe give graph direct acyclic graph
1graph
give string path pathi N S E w represent move unit north south east west respectively you start origin 0 0 2D plane walk path specify pathreturn true path crosse point time location previously visit Return false Example 1input path NESOutput false Explanation Notice path do not cross point onceExample 2input path neswwoutput trueExplanation Notice path visit origin twice Constraints1 pathlength 104pathi N S E w
2string
give array integer arr length n integer kWe want divide array exactly n 2 pair sum pair divisible kReturn true if find way false Example 1input arr 12345106789 k 5output trueExplanation pair 19283746 510example 2input arr 123456 k 7output trueExplanation Pairs 1625 and34Example 3Input arr 123456 k 10output falseexplanation you try possible pair way divide arr 3 pair sum divisible 10 Constraintsarrlength n1 n 105n even109 arri 1091 k 105
0array
you give array integer num integer targetreturn number nonempty subsequence num sum minimum maximum element equal target since answer large return modulo 109 7 Example 1input num 3567 target 9output 4explanation there 4 subsequence satisfy condition3 min value max value target 3 3 935 3 5 9356 3 6 936 3 6 9example 2input num 3368 target 10output 6explanation there 6 subsequence satisfy condition num repeat numbers3 3 33 36 36 336example 3input num 233467 target 12output 61explanation there 63 nonempty subsequence satisfy condition 67 7number valid subsequence 63 2 61 Constraints1 numslength 1051 numsi 1061 target 106
0array
you give array point contain coordinate point 2D plane sort xvalues pointsi xi yi xi xj 1 j pointslength you give integer kReturn maximum value equation yi yj xi xj xi xj k 1 j pointslengthIt guarantee exist pair point satisfy constraint xi xj k Example 1input point 1320510610 k 1output 4explanation the point satisfy condition xi xj 1 calculate equation 3 0 1 2 4 third fourth point satisfy condition value 10 10 5 6 1no pair satisfy condition return max 4 1example 2input point 003092 k 3output 3explanation only point absolute difference 3 xvalues value 0 0 0 3 3 constraints2 pointslength 105pointsilength 2108 xi yi 1080 k 2 108xi xj 1 j pointslengthxi form strictly increase sequence
0array
a sequence number call arithmetic progression difference consecutive element sameGiven array number arr return true array rearrange form arithmetic progression otherwise return false Example 1input arr 351output trueexplanation we reorder element 135 531 difference 2 2 respectively consecutive elementsExample 2input arr 124output falseexplanation there way reorder element obtain arithmetic progression constraints2 arrlength 1000106 arri 106
0array
we wooden plank length n unit some ant walk plank ant move speed 1 unit second some ant leave rightwhen ant move different direction meet point change direction continue move Assume change direction additional timewhen ant reach end plank time t fall plank immediatelyGiven integer n integer array leave right position ant move leave right return moment ant fall plank Example 1input n 4 leave 43 right 01output 4explanation in image abovethe ant index 0 name a go rightThe ant index 1 name b go rightThe ant index 3 name C go leftThe ant index 4 name D go leftthe moment ant plank t 4 second after fall immediately plank ie We t 40000000001 ant plankexample 2input n 7 leave right 01234567output 7explanation all ant go right ant index 0 need 7 second fallexample 3input n 7 leave 01234567 right output 7explanation all ant going leave ant index 7 need 7 second fall Constraints1 n 1040 leftlength n 10 lefti n0 rightlength n 10 righti n1 leftlength rightlength n 1all value leave right unique value appear array
0array
give m x n binary matrix mat return number submatrice one example 1input mat 101110110output 13explanation there 6 rectangle 1x1there 2 rectangle 1x2there 3 rectangle 2x1there 1 rectangle 2x2 there 1 rectangle 3x1total number rectangle 6 2 3 1 1 13example 2input mat 011001111110output 24explanation there 8 rectangle 1x1there 5 rectangle 1x2there 2 rectangle 1x3 there 4 rectangle 2x1there 2 rectangle 2x2 there 2 rectangle 3x1 there 1 rectangle 3x2 total number rectangle 8 5 2 4 2 2 1 24 Constraints1 m n 150matij 0 1
0array
you give stre num represent digit large integer integer k you allow swap adjacent digit integer k timesreturn minimum integer obtain stre Example 1input num 4321 k 4Output 1342explanation the step obtain minimum integer 4321 4 adjacent swap shownexample 2input num 100 k 1output 010explanation its ok output lead zero input guarantee lead zerosexample 3input num 36789 k 1000output 36789explanation we number swap Constraints1 numlength 3 104num consist digit contain lead zeros1 k 109
2string
give date string form Day Month Year whereDay set 1st 2nd 3rd 4th 30th 31stmonth set Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov DecYear range 1900 2100convert date string format YYYYMMDD whereYYYY denote 4 digit yearMM denote 2 digit monthdd denote 2 digit day Example 1input date 20th Oct 2052output 20521020example 2input date 6th Jun 1933output 19330606example 3input date 26th May 1960output 19600526 ConstraintsThe give date guarantee valid error handle necessary
2string
you give array num consist n positive integer you compute sum nonempty continuous subarray array sort nondecrease order create new array n n 1 2 numbersReturn sum number index leave index right index 1 inclusive new array since answer huge number return modulo 109 7 Example 1input num 1234 n 4 leave 1 right 5output 13 Explanation all subarray sum 1 3 6 10 2 5 9 3 7 4 after sort nondecrease order new array 1 2 3 3 4 5 6 7 9 10 the sum number index le 1 ri 5 1 2 3 3 4 13 Example 2input num 1234 n 4 leave 3 right 4output 6explanation the give array example 1 we new array 1 2 3 3 4 5 6 7 9 10 the sum number index le 3 ri 4 3 3 6example 3input num 1234 n 4 leave 1 right 10output 50 Constraintsn numslength1 numslength 10001 numsi 1001 leave right n n 1 2
0array
you give integer array numsIn choose element num change valuereturn minimum difference large small value num perform move Example 1input num 5324output 0explanation we 3 movesIn change 2 3 num 5334in second change 4 3 num 5333in change 5 3 num 3333after perform 3 move difference minimum maximum 3 3 0example 2input num 1501014output 1explanation we 3 movesIn change 5 0 num 1001014in second change 10 0 num 100014in change 14 1 num 10001after perform 3 move difference minimum maximum 1 0 0it show way difference 0 3 movesexample 3input num 310020output 0explanation we 3 movesIn change 100 7 num 4720in second change 20 7 num 477in change 4 3 num 777after perform 3 move difference minimum maximum 7 7 0 constraints1 numslength 105109 numsi 109
0array
give array integer num return number good pairsA pair j call good numsi numsj j Example 1input num 123113output 4explanation there 4 good pair 03 04 34 25 0indexedexample 2input num 1111output 6explanation each pair array goodexample 3input num 123output 0 constraints1 numslength 1001 numsi 100
0array
give binary string s return number substring character 1 since answer large return modulo 109 7 Example 1input s 0110111output 9explanation there 9 substre total 1s characters1 5 times11 3 times111 1 timeexample 2input s 101output 2explanation Substring 1 show 2 time sExample 3input s 111111output 21explanation each substring contain 1s character Constraints1 slength 105si 0 1
2string
you give undirected weighted graph n node 0indexe represent edge list edgesi b undirected edge connect node b probability success traverse edge succprobigiven node start end find path maximum probability success start end return success probabilityIf path start end return 0 your answer accept differ correct answer 1e5 example 1input n 3 edge 011202 succprob 050502 start 0 end 2output 025000explanation there path start end have probability success 02 05 05 025example 2input n 3 edge 011202 succprob 050503 start 0 end 2output 030000example 3input n 3 edge 01 succprob 05 start 0 end 2output 000000explanation there path 0 2 constraints2 n 1040 start end nstart end0 b na b0 succproblength edgeslength 21040 succProbi 1There edge node
1graph
you give tree ie connect undirected graph cycle consist n node number 0 n 1 exactly n 1 edge the root tree node 0 node tree label lowercase character give string label ie the node number label labelsithe edge array give form edgesi ai bi mean edge node ai bi treeReturn array size n ansi number nod subtree ith node label node iA subtree tree t tree consist node T descendant node Example 1input n 7 edge 010214152326 label abaedcdOutput 2111111explanation Node 0 label subtree node 2 label answer 2 Notice node subtreeNode 1 label b the subtree node 1 contain node 14 5 node 4 5 different label node 1 answer 1 node itselfexample 2input n 4 edge 011203 label bbbbOutput 4211explanation the subtree node 2 contain node 2 answer 1the subtree node 3 contain node 3 answer 1the subtree node 1 contain node 1 2 label b answer 2the subtree node 0 contain node 0 1 2 3 label b answer 4example 3input n 5 edge 01021304 label aababOutput 32111 Constraints1 n 105edgeslength n 1edgesilength 20 ai bi nai bilabelslength nlabel consist lowercase english letter
1graph
give string s lowercase letter need find maximum number nonempty substring s meet follow conditionsthe substring overlap substring sij sxy j x y trueA substring contain certain character c contain occurrence cFind maximum number substring meet condition if multiple solution number substring return minimum total length it show exist unique solution minimum total lengthnotice return substring order Example 1input s adefaddacccoutput efcccexplanation the follow possible substring meet condition adefaddaccc adefadda ef e f cccIf choose string choose we d 1 if choose adefadda leave ccc do not overlap obtain 2 substring Notice optimal choose ef split therefore optimal way choose efccc give 3 substring no solution number substring existexample 2input s abbaccdoutput dbbccexplanation Notice set substring dabbacc length 3 consider incorrect large total length Constraints1 slength 105s contain lowercase english letter
2string
Winston give mysterious function func he integer array arr integer target want find value l r value funcarr l r target minimum possiblereturn minimum possible value funcarr l r targetnotice func call value l r 0 l r arrlength Example 1input arr 9123715 target 5output 2explanation call func pair lr 001122334401122334021324031404 Winston got follow result 91237158037003000 the value close 5 7 3 minimum difference 2example 2Input arr 100000010000001000000 target 1output 999999explanation Winston call func possible value lr get 1000000 min difference 999999example 3Input arr 124816 target 0output 0 Constraints1 arrlength 1051 arri 1060 target 107
0array
give array integer arr return number subarray odd sumsince answer large return modulo 109 7 Example 1input arr 135output 4explanation all subarray 1131353355all subarray sum 149385Odd sum 1935 answer 4example 2input arr 246output 0explanation all subarray 2242464466all subarray sum 26124106All subarray sum answer 0Example 3Input arr 1234567output 16 Constraints1 arrlength 1051 arri 100
0array
you give string sa split call good split s nonempty string sleft sright concatenation equal s ie sleft sright s number distinct letter sleft sright samereturn number good split s Example 1input s aacabaoutput 2explanation there 5 way split aacaba 2 good acaba leave string right string contain 1 3 different letter respectivelyaa caba Left stre right string contain 1 3 different letter respectivelyaac aba leave string right string contain 2 2 different letter respectively good splitaaca ba Left stre right string contain 2 2 different letter respectively good splitaacab Left string right string contain 3 1 different letter respectivelyexample 2input s abcdOutput 1explanation Split string follow ab cd Constraints1 slength 105s consist lowercase english letter
2string
you give integer array target you integer array initial size target element initially zerosIn operation choose subarray initial increment value onereturn minimum number operation form target array initialthe test case generate answer fit 32bit integer Example 1input target 12321output 3explanation we need 3 operation form target array initial array00000 increment 1 index 0 4 inclusive11111 increment 1 index 1 3 inclusive12221 increment 1 index 212321 target array formedExample 2input target 3112output 4explanation 0000 1111 1112 2112 3112example 3input target 31542output 7explanation 00000 11111 21111 31111 31222 31332 31442 31542 Constraints1 targetlength 1051 targeti 105
0array
you give 0indexed binary string target length n you binary string s length n initially set zero you want s equal targetin operation pick index 0 n flip bit inclusive range n 1 Flip mean change 0 1 1 0return minimum number operation need s equal target example 1input target 10111output 3explanation initially s 00000choose index 2 00000 00111choose index 0 00111 11000choose index 1 11000 10111we need 3 flip operation form targetexample 2input target 101output 3explanation initially s 000choose index 0 000 111choose index 1 111 100choose index 2 100 101we need 3 flip operation form targetexample 3input target 00000output 0explanation we need operation initial s equal target Constraintsn targetlength1 n 105targeti 0 1
2string
you give root binary tree integer distance a pair different leaf node binary tree say good length short path equal distancereturn number good leaf node pair tree Example 1input root 123null4 distance 3output 1explanation the leaf node tree 3 4 length short path 3 this good pairexample 2input root 1234567 distance 3output 2explanation the good pair 45 67 short path 2 the pair 46 good length ther short path 4example 3input root 7146null53nullnullnullnullnull2 distance 3output 1explanation the good pair 25 ConstraintsThe number nod tree range 1 2101 Nodeval 1001 distance 10
1graph
runlength encoding string compression method work replace consecutive identical character repeat 2 time concatenation character number mark count character length run for example compress string aabccc replace aa a2 replace ccc c3 thus compress string a2bc3notice problem add 1 single charactersgiven string s integer k you need delete k character s runlength encode version s minimum lengthfind minimum length runlength encode version s delete k character Example 1input s aaabcccd k 2output 4explanation compress s delete a3bc3d length 6 delete character c decrease length compressed string 5 instance delete 2 s abcccd compress abc3d therefore optimal way delete b d compress version s a3c3 length 4example 2input s aabbaa k 2output 2explanation if delete b character result compressed string a4 length 2example 3input s aaaaaaaaaaa k 0output 3explanation since k zero delete the compressed string a11 length 3 constraints1 slength 1000 k slength contain lowercase english letter
2string
give array integer arr integer b c you need find number good tripletsA triplet arri arrj arrk good follow condition true0 j k arrlengtharri arrj aarrj arrk barri arrk cWhere x denote absolute value xReturn number good triplet Example 1input arr 301197 7 b 2 c 3output 4explanation there 4 good triplet 301 301 311 011example 2input arr 11223 0 b 0 c 1output 0explanation no triplet satisfie condition Constraints3 arrlength 1000 arri 10000 b c 1000
0array
give integer array arr distinct integer integer kA game play element array ie arr0 arr1 in round game compare arr0 arr1 large integer win remain position 0 small integer move end array the game end integer win k consecutive roundsreturn integer win gameIt guarantee winner game Example 1input arr 2135467 k 2output 5explanation Lets round gameRound arr winner win_count 1 2135467 2 1 2 2354671 3 1 3 3546712 5 1 4 5467123 5 2so 4 round play 5 winner win 2 consecutive gamesExample 2Input arr 321 k 10output 3explanation 3 win 10 round consecutively constraints2 arrlength 1051 arri 106arr contain distinct integers1 k 109
0array
give n x n binary grid step choose adjacent row grid swap themA grid say valid cell main diagonal zerosreturn minimum number step need grid valid 1 grid validthe main diagonal grid diagonal start cell 1 1 end cell n n Example 1input grid 001110100output 3example 2input grid 0110011001100110output 1explanation all row similar swap effect gridExample 3input grid 100110111output 0 Constraintsn gridlength gridilength1 n 200gridij 0 1
0array
you give sort array distinct integer nums1 nums2a valid path define followschoose array nums1 nums2 traverse index0traverse current array leave rightIf reading value present nums1 nums2 allow change path array only repeat value consider valid paththe score define sum uniques value valid pathreturn maximum score obtain possible valid path since answer large return modulo 109 7 Example 1input nums1 245810 nums2 4689output 30explanation Valid paths245810 24589 24689 246810 start nums14689 45810 4589 46810 start nums2the maximum obtain path green 246810example 2input nums1 13579 nums2 35100output 109explanation maximum sum obtain path 135100example 3input nums1 12345 nums2 678910output 40explanation there common element nums1 nums2maximum sum obtain path 678910 Constraints1 nums1length nums2length 1051 nums1i nums2i 107nums1 nums2 strictly increase
0array
give array arr positive integer sort strictly increase order integer kReturn kth positive integer miss array Example 1input arr 234711 k 5output 9explanation the miss positive integer 15689101213 the 5th miss positive integer 9example 2Input arr 1234 k 2output 6explanation the miss positive integer 567 the 2nd miss positive integer 6 Constraints1 arrlength 10001 arri 10001 k 1000arri arrj 1 j arrlength Follow upcould solve problem on complexity
0array
give string s t goal convert s t k move lessdure ith 1 k canChoose index j 1indexed s 1 j slength j choose previous shift character index timesDo nothingshifting character mean replace letter alphabet wrap z shift character mean apply shift operation timesRemember index j pick onceReturn true possible convert s t k move return false example 1input s input t ouput k 9output trueexplanation in 6th shift 6 time o and 7th shift n uExample 2Input s abc t bcd k 10output falseexplanation we need shift character s time convert t we shift b 1st however way shift character remain move obtain t sExample 3input s aab t bbb k 27output trueexplanation in 1st shift 1 time b in 27th shift second 27 time b Constraints1 slength tlength 1050 k 109s t contain lowercase english letter
2string
give parenthesis stre s contain character a parenthesis stre balanced ifAny leave parenthesis correspond consecutive right parenthesis left parenthesis correspond consecutive right parenthesis in word treat open parenthesis closing parenthesisfor example balanced balancedyou insert characters position string balance neededreturn minimum number insertion need s balanced Example 1input s output 1explanation the second matching matching we need add end stre balancedExample 2input s output 0explanation the string balancedExample 3input s output 3explanation add match add match Constraints1 slength 105s consist
2string
you give stre s an awesome substre nonempty substre s number swap order palindromereturn length maximum length awesome substre s example 1input s 3242415output 5explanation 24241 long awesome substring form palindrome 24142 swapsexample 2input s 12345678output 1example 3input s 213123output 6explanation 213123 long awesome substring form palindrome 231132 swap Constraints1 slength 105s consist digit
2string
give string s low upper case English lettersA good string string do not adjacent character si si 1 where0 slength 2si lowercase letter si 1 letter uppercase viceversaTo string good choose adjacent character stre bad remove you string goodReturn string make good the answer guarantee unique give constraintsNotice string good Example 1input s leeeetcodeoutput leetcodeexplanation in step choose 1 2 result leEeetcode reduce leetcodeExample 2input s abbaccoutput Explanation we possible scenario lead answer for exampleabBAcC aAcC cc abBAcC abba aa Example 3input s sOutput s constraints1 slength 100s contain low upper case english letter
2string
give positive integer n k binary string Sn form followsS1 0Si Si 1 1 reverseinvertsi 1 1Where denote concatenation operation reversex return reverse string x invertx invert bits x 0 change 1 1 change 0for example string sequence ares1 0s2 011s3 0111001s4 011100110110001return kth bit Sn it guarantee k valid give n Example 1input n 3 k 1output 0explanation S3 0111001the 1st bit 0example 2input n 4 k 11output 1explanation S4 011100110110001the 11th bit 1 constraints1 n 201 k 2n 1
2string
give array num integer target return maximum number nonempty nonoverlapping subarray sum value subarray equal target Example 1input num 11111 target 2output 2explanation there 2 nonoverlapping subarray 11111 sum equal target2Example 2input num 1351429 target 6output 2explanation there 3 subarray sum equal 651 42 351429 2 nonoverlapping Constraints1 numslength 105104 numsi 1040 target 106
0array
give wooden stick length n unit the stick label 0 n for example stick length 6 label followsGiven integer array cut cutsi denote position perform cut atYou perform cut order change order cut wishthe cost cut length stick cut total cost sum cost cut when cut stick split small stick ie sum length length stick cut please refer example well explanationreturn minimum total cost cut Example 1input n 7 cut 1345output 16explanation use cut order 1 3 4 5 input lead follow scenariothe cut rod length 7 cost 7 the second cut rod length 6 ie second cut rod length 4 cut rod length 3 the total cost 7 6 4 3 20rearranging cut 3 5 1 4 example lead scenario total cost 16 show example photo 7 4 3 2 16example 2input n 9 cut 56142output 22explanation if try give cut order cost 25there order total cost 25 example order 4 6 5 2 1 total cost 22 minimum possible Constraints2 n 1061 cutslength minn 1 1001 cutsi n 1all integer cut array distinct
0array
give integer array arr return true consecutive odd number array otherwise return false Example 1input arr 2641output falseexplanation there consecutive oddsexample 2input arr 123434572312output trueExplanation 5723 consecutive odd Constraints1 arrlength 10001 arri 1000
0array
in universe Earth C137 Rick discover special form magnetic force ball new invent basket Rick n basket ith basket positioni Morty m ball need distribute ball basket minimum magnetic force ball maximumRick state magnetic force different ball position x y x yGiven integer array position integer m return required force Example 1input position 12347 m 3output 3explanation distribute 3 ball basket 1 4 7 magnetic force ball pair 3 3 6 the minimum magnetic force 3 we achieve large minimum magnetic force 3example 2input position 543211000000000 m 2output 999999999explanation we use basket 1 1000000000 Constraintsn positionlength2 n 1051 positioni 109All integer position distinct2 m positionlength
0array
give integer n add dot thousand separator return string format Example 1input n 987output 987example 2input n 1234output 1234 Constraints0 n 231 1
2string
give direct acyclic graph n vertex number 0 n1 array edge edgesi fromi toi represent direct edge node fromi node toiFind small set vertex node graph reachable its guarantee unique solution existsnotice return vertex order Example 1input n 6 edge 0102253442output 03explanation its possible reach node single vertex from 0 reach 0125 from 3 reach 3425 so output 03example 2input n 5 edge 0121311424output 023explanation Notice vertex 0 3 2 reachable node include also vertex reach node 1 4 Constraints2 n 1051 edgeslength min105 n n 1 2edgesilength 20 fromi toi nAll pair fromi toi distinct
1graph
you give integer array num you integer array arr length value set 0 initially you follow modify functionYou want use modify function covert arr nums minimum number callsreturn minimum number function call num arrthe test case generate answer fit 32bit sign integer Example 1input num 15output 5explanation Increment 1 second element 0 0 0 1 1 operationdouble element 0 1 0 2 0 4 2 operationsincrement 1 element 0 4 1 4 1 5 2 operationstotal operation 1 2 2 5example 2input num 22output 3explanation Increment 1 element 0 0 0 1 1 1 2 operationsdouble element 1 1 2 2 1 operationtotal operation 2 1 3example 3input num 425output 6explanation initial000 100 101 202 212 424 425num Constraints1 numslength 1050 numsi 109
0array
give integer n integer array round we circular track consist n sector label 1 n a marathon hold track marathon consist m round the ith round start sector roundsi 1 end sector roundsi for example round 1 start sector rounds0 end sector rounds1Return array visit sector sort ascend ordernotice circulate track ascending order sector number counterclockwise direction see example Example 1input n 4 round 1312output 12explanation the marathon start sector 1 the order visit sector follows1 2 3 end round 1 4 1 end round 2 2 end round 3 marathonWe sector 1 2 visit twice visit sector Sectors 3 4 visit onceExample 2input n 2 round 212121212output 2example 3input n 7 round 1357output 1234567 Constraints2 n 1001 m 100roundslength m 11 roundsi nroundsi roundsi 1 0 m
0array
there 3n pile coin vary size friend pile coin followsIn step choose 3 pile coin necessarily consecutiveof choice Alice pick pile maximum number coinsyou pick pile maximum number coinsYour friend Bob pick pilerepeat pile coinsGiven array integer piles pilesi number coin ith pileReturn maximum number coin Example 1input pile 241278output 9explanation Choose triplet 2 7 8 Alice Pick pile 8 coin pile 7 coin Bob onechoose triplet 1 2 4 Alice Pick pile 4 coin pile 2 coin Bob onethe maximum number coin 7 2 9On hand choose arrangement 1 2 8 2 4 7 2 4 6 coin optimalexample 2input pile 245output 4example 3input pile 987651234output 18 Constraints3 pileslength 105pileslength 3 01 pilesi 104
0array
give array arr represent permutation number 1 nyou binary string size n initially bit set zero at step assume binary string arr 1indexed 1 n bit position arri set 1you give integer m find late step exist group one length m a group one contiguous substre 1s extend directionReturn late step exist group one length exactly m if group exist return 1 Example 1input arr 35124 m 1output 4Explanation Step 1 00100 group 1step 2 00101 group 1 1step 3 10101 group 1 1 1step 4 11101 group 111 1step 5 11111 group 11111the late step exist group size 1 step 4example 2Input arr 31542 m 2output 1explanation Step 1 00100 group 1step 2 10100 group 1 1step 3 10101 group 1 1 1step 4 10111 group 1 111step 5 11111 group 11111no group size 2 exist step Constraintsn arrlength1 m n 1051 arri nAll integer arr distinct
0array
there stone arrange row stone associate value integer give array stonevaluein round game Alice divide row nonempty row ie leave row right row Bob calculate value row sum value stone row Bob throw away row maximum value Alices score increase value remain row if value row equal Bob let Alice decide row throw away the round start remain rowthe game end stone remain Alices initially zeroreturn maximum score Alice obtain Example 1input stonevalue 623455output 18explanation in round Alice divide row 623 455 the left row value 11 right row value 14 Bob throw away right row alice score 11in second round Alice divide row 6 23 this time Bob throw away left row Alices score 16 11 5the round Alice choice divide row 2 3 Bob throw away right row Alices score 18 16 2 the game end stone remain rowExample 2input stoneValue 7777777output 28example 3input stonevalue 4output 0 constraints1 stonevaluelength 5001 stoneValuei 106
0array
give array positive integer arr find pattern length m repeat k timesA pattern subarray consecutive subsequence consist value repeat multiple time consecutively overlap a pattern define length number repetitionsreturn true exist pattern length m repeat k times return false Example 1input arr 124444 m 1 k 3output trueexplanation the pattern 4 length 1 repeat 4 consecutive time Notice pattern repeat k time lessexample 2Input arr 12121113 m 2 k 2output trueexplanation the pattern 12 length 2 repeat 2 consecutive time another valid pattern 21 repeat 2 timesExample 3input arr 121213 m 2 k 3output falseexplanation the pattern 12 length 2 repeat 2 time there pattern length 2 repeat 3 time Constraints2 arrlength 1001 arri 1001 m 1002 k 100
0array
give array integer num find maximum length subarray product element positiveA subarray array consecutive sequence zero value take arrayreturn maximum length subarray positive product Example 1input num 1234output 4explanation the array num positive product 24example 2input num 01234output 3explanation the long subarray positive product 123 product 6notice include 0 subarray that ll product 0 positiveExample 3input num 12301output 2explanation the long subarray positive product 12 23 Constraints1 numslength 105109 numsi 109
0array
give array num represent permutation integer 1 n we go construct binary search tree BST insert element num order initially BST Find number different way reorder num construct BST identical form original array numsfor example give num 213 2 root 1 leave child 3 right child the array 231 yield BST 321 yield different BSTReturn number way reorder num BST form identical original BST form numsSince answer large return modulo 109 7 Example 1input num 213output 1explanation we reorder num 231 yield BST there way reorder num yield BSTExample 2input num 34512output 5explanation the follow 5 array yield BST 3124531425314523412534152example 3input num 123output 0explanation there ordering num yield BST Constraints1 numslength 10001 numsi numslengthAll integer num distinct
0array
give square matrix mat return sum matrix diagonalsonly include sum element primary diagonal element secondary diagonal primary diagonal Example 1input mat 123 456 789output 25explanation diagonal sum 1 5 9 3 7 25notice element mat11 5 count onceExample 2input mat 1111 1111 1111 1111output 8example 3input mat 5output 5 Constraintsn matlength matilength1 n 1001 matij 100
0array
give binary string s split s 3 nonempty string s1 s2 s3 s1 s2 s3 sReturn number way s split number one s1 s2 s3 since answer large return modulo 109 7 Example 1input s 10101output 4explanation there way split s 3 part contain number letter 110101101011010110101example 2input s 1001output 0example 3input s 0000output 3explanation there way split s 3 parts000000000000 Constraints3 slength 105si 0 1
2string
give integer array arr remove subarray arr remain element arr nondecreasingReturn length short subarray removeA subarray contiguous subsequence array Example 1input arr 123104235output 3explanation the short subarray remove 1042 length 3 the remain element 12335 sortedanother correct solution remove subarray 3104example 2input arr 54321output 4explanation since array strictly decrease single element therefore need remove subarray length 4 5432 4321example 3input arr 123output 0explanation the array nondecrease we need remove element Constraints1 arrlength 1050 arri 109
0array
you give array distinct positive integer location locationsi represent position city you give integer start finish fuel represent start city end city initial fuel respectivelyAt step city pick city j j 0 j locationslength city j move city city j reduce fuel locationsi locationsj please notice x denote absolute value xNotice fuel negative point time allow visit city include start finishReturn count possible route start finish since answer large return modulo 109 7 Example 1input location 23684 start 1 finish 3 fuel 5output 4explanation the follow possible route use 5 unit fuel1 31 2 31 4 31 4 2 3example 2input location 431 start 1 finish 0 fuel 6output 5explanation the follow possible routes1 0 fuel 11 2 0 fuel 51 2 1 0 fuel 51 0 1 0 fuel 31 0 1 0 1 0 fuel 5Example 3input location 521 start 0 finish 2 fuel 3output 0explanation it impossible 0 2 3 unit fuel short route need 4 unit fuel constraints2 locationslength 1001 locationsi 109All integers location distinct0 start finish locationslength1 fuel 200
0array
give string s contain lowercase english letter character convert characters lowercase letter final string contain consecutive repeat character you modify non charactersIt guarantee consecutive repeat character give stre Return final string conversion possibly zero if solution return it show answer possible give constraint Example 1input s zsoutput azsexplanation there 25 solution problem from azs yzs valid only z invalid modification string consist consecutive repeat character zzsexample 2input s ubvwoutput ubvawExplanation there 24 solution problem only v w invalid modification string consist consecutive repeat character ubvvw ubvww Constraints1 slength 100s consist lowercase english letter
2string
give array integer nums1 nums2 return number triplet form type 1 type 2 follow rulesType 1 Triplet j k nums1i2 nums2j nums2k 0 nums1length 0 j k nums2lengthType 2 Triplet j k nums2i2 nums1j nums1k 0 nums2length 0 j k nums1length Example 1input nums1 74 nums2 5289output 1explanation Type 1 1 1 2 nums112 nums21 nums22 42 2 8 example 2input nums1 11 nums2 111output 9explanation all triplet valid 12 1 1type 1 001 002 012 101 102 112 nums1i2 nums2j nums2ktype 2 001 101 201 nums2i2 nums1j nums1kExample 3Input nums1 7783 nums2 1297output 2explanation there 2 valid tripletsType 1 302 nums132 nums20 nums22Type 2 301 nums232 nums10 nums11 Constraints1 nums1length nums2length 10001 nums1i nums2i 105
0array
Alice Bob undirected graph n node type edgestype 1 can traverse Alice onlytype 2 can traverse Bob onlytype 3 can traverse Alice BobGiven array edge edgesi typei ui vi represent bidirectional edge type typei node ui vi find maximum number edge remove remove edge graph fully traverse Alice Bob the graph fully traverse Alice Bob start node reach nodesReturn maximum number edge remove return 1 Alice Bob fully traverse graph Example 1input n 4 edge 312323113124112234output 2explanation if remove 2 edge 112 113 the graph fully traversable Alice Bob remove additional edge so maximum number edge remove 2example 2input n 4 edge 312323114214output 0explanation notice remove edge graph fully traversable Alice BobExample 3input n 4 edge 323112234output 1explanation in current graph Alice reach node 4 node likewise Bob reach 1 therefore impossible graph fully traversable Constraints1 n 1051 edgeslength min105 3 n n 1 2edgesilength 31 typei 31 ui vi nAll tuple typei ui vi distinct
1graph
give m x n binary matrix mat return number special position matA position j call special matij 1 element row column j 0 row column 0indexe example 1input mat 100001100output 1explanation 1 2 special position mat12 1 element row 1 column 2 0example 2input mat 100010001output 3explanation 0 0 1 1 2 2 special position Constraintsm matlengthn matilength1 m n 100matij 0 1
0array
you give list preference n friend n evenFor person preferencesi contain list friend sort order preference in word friend early list prefer friend later list Friends list denote integer 0 n1all friend divide pair the pairing give list pair pairsi xi yi denote xi paired yi yi pair xiHowever pair cause friend unhappy a friend x unhappy x pair y exist friend u pair v butx prefer u y andu prefer x vReturn number unhappy friend Example 1input n 4 preference 1 2 3 3 2 0 3 1 0 1 2 0 pair 0 1 2 3output 2ExplanationFriend 1 unhappy 1 pair 0 prefer 3 0 3 prefer 1 2friend 3 unhappy 3 pair 2 prefer 1 2 1 prefer 3 0friends 0 2 happyexample 2input n 2 preference 1 0 pair 1 0output 0explanation both friend 0 1 happyExample 3input n 4 preference 1 3 2 2 3 0 1 3 0 0 2 1 pair 1 3 0 2output 4 Constraints2 n 500n evenpreferenceslength npreferencesilength n 10 preferencesij n 1preferencesi contain iAll value preferencesi uniquepairslength n2pairsilength 2xi yi0 xi yi n 1each person contain exactly pair
0array
you give array point represent integer coordinate point 2dplane pointsi xi yiThe cost connect point xi yi xj yj manhattan distance xi xj yi yj val denote absolute value valreturn minimum cost point connect all point connect exactly simple path point example 1input point 00223105270output 20explanation we connect point show minimum cost 20notice unique path pair pointsExample 2input point 3122541output 18 Constraints1 pointslength 1000106 xi yi 106All pair xi yi distinct
0array
give string s t transform string s string t follow operation number timeschoose nonempty substre s sort place character ascend orderFor example apply operation underline substre 14234 result 12344return true possible transform s t otherwise return falseA substre contiguous sequence character string Example 1input s 84532 t 34852output trueexplanation you transform s t follow sort operations84532 index 2 3 8435284352 index 0 2 34852example 2input s 34521 t 23415output trueexplanation you transform s t follow sort operations34521 2345123451 23415example 3input s 12345 t 12435output false constraintsslength tlength1 slength 105s t consist digit
2string
give array positive integer arr return sum possible oddlength subarray arrA subarray contiguous subsequence array Example 1input arr 14253output 58explanation the oddlength subarray arr sums are1 14 42 25 53 3142 7425 11253 1014253 15if add 1 4 2 5 3 7 11 10 15 58example 2input arr 12Output 3explanation there 2 subarray odd length 1 2 their sum 3example 3input arr 101112output 66 Constraints1 arrlength 1001 arri 1000 Follow upcould solve problem on time complexity
0array
we array integer num array request requestsi starti endi the ith request ask sum numsstarti numsstarti 1 numsendi 1 numsendi both starti endi 0indexedreturn maximum total sum request permutation numssince answer large return modulo 109 7 Example 1input num 12345 request 1301output 19explanation one permutation num 21345 follow result requests0 nums1 nums2 nums3 1 3 4 8requests1 nums0 nums1 2 1 3total sum 8 3 11a permutation high total sum 35421 follow resultrequests0 nums1 nums2 nums3 5 4 2 11requests1 nums0 nums1 3 5 8total sum 11 8 19 good doExample 2input num 123456 request 01output 11explanation a permutation max total sum 654321 request sum 11example 3input num 1234510 request 021311output 47explanation a permutation max total sum 4105321 request sum 191810 Constraintsn numslength1 n 1050 numsi 1051 requestslength 105requestsilength 20 starti endi n
0array