question
stringlengths
58
4.29k
label
class label
3 classes
there n ring ring red green blue the ring distribute rod label 0 9you give string ring length 2n describe n ring place rod every character ring form colorposition pair describe ring whereThe character ith pair denote ith ring color r G BThe second character ith pair denote rod ith ring place 0 9for example R3G2B1 describe n 3 ring red ring place rod label 3 green ring place rod label 2 blue ring place rod label 1return number rod color ring Example 1input ring B0B6G0R6R0R6G9Output 1explanation the rod label 0 hold 3 ring color red green blue the rod label 6 hold 3 ring red blue the rod label 9 hold green ringthu number rod color 1example 2input ring B0R0G0R9R0B0G0Output 1explanation the rod label 0 hold 6 ring color red green blue the rod label 9 hold red ringthu number rod color 1example 3input ring g4output 0explanation only ring give Thus rod color constraintsringslength 2 n1 n 100ringsi R G B 0indexedringsi odd digit 0 9 0indexed
2string
you give integer array num the range subarray num difference large small element subarrayreturn sum subarray range numsA subarray contiguous nonempty sequence element array Example 1input num 123output 4explanation the 6 subarray num following1 range large small 1 1 0 2 range 2 2 03 range 3 3 012 range 2 1 123 range 3 2 1123 range 3 1 2so sum range 0 0 0 1 1 2 4example 2input num 133output 4explanation the 6 subarray num following1 range large small 1 1 03 range 3 3 03 range 3 3 013 range 3 1 233 range 3 3 0133 range 3 1 2so sum range 0 0 0 2 0 2 4example 3input num 42341output 59explanation the sum subarray range num 59 Constraints1 numslength 1000109 numsi 109 Followup could find solution on time complexity
0array
Alice Bob want water n plant garden the plant arrange row label 0 n 1 leave right ith plant locate x ieach plant need specific water Alice Bob water initially they water plant follow wayalice water plant order leave right start 0th plant Bob water plant order right leave start n 1th plant they begin water plant simultaneouslyIt take time water plant regardless water needsAliceBob water plant fully water otherwise refill instantaneously water plantin case Alice Bob reach plant water currently hisher watering water plant if water Alice water plantGiven 0indexe integer array plant n integer plantsi water ith plant need integer capacityA capacityB represent capacity Alices Bobs watering can respectively return number time refill water plant example 1input plant 2233 capacitya 5 capacityB 5output 1explanation Initially Alice Bob 5 unit water watering can Alice water plant 0 Bob water plant 3 Alice Bob 3 unit 2 unit water respectively Alice water plant 1 water Bob water plant 2 refill water itso total number time refill water plant 0 0 1 0 1example 2input plant 2233 capacitya 3 capacityB 4output 2explanation Initially Alice Bob 3 unit 4 unit water watering can respectively Alice water plant 0 Bob water plant 3 Alice Bob 1 unit water need water plant 1 2 respectively since water current plant refill can water plantsSo total number time refill water plant 0 1 1 0 2example 3input plant 5 capacitya 10 capacityb 8output 0explanation There plant alice water 10 unit water Bobs 8 unit since Alice water water plantso total number time refill 0 Constraintsn plantslength1 n 1051 plantsi 106maxplantsi capacityA capacityB 109
0array
fruit available position infinite xaxis you give 2D integer array fruit fruitsi positioni amounti depict amounti fruit position positioni fruit sort positioni ascending order positioni uniqueyou give integer startpos integer k Initially position startpos from position walk leave right it take step unit xaxis walk k step total for position reach harvest fruit position fruit disappear positionreturn maximum total number fruit harvest Example 1input fruit 286386 startpos 5 k 4output 9explanation the optimal way move right position 6 harvest 3 fruit move right position 8 harvest 6 fruitsYou move 3 step harvest 3 6 9 fruit totalexample 2input fruit 0941576274109 startpos 5 k 4Output 14explanation you k 4 step reach position 0 10the optimal way Harvest 7 fruit start position 5 move leave position 4 harvest 1 fruit move right position 6 harvest 2 fruit move right position 7 harvest 4 fruitsYou move 1 3 4 step harvest 7 1 2 4 14 fruit totalexample 3input fruit 036485 startpos 3 k 2output 0explanationyou k 2 step reach position fruit Constraints1 fruitslength 105fruitsilength 20 startpos positioni 2 105positioni1 positioni 0 0indexed1 amounti 1040 k 2 105
0array
you give integer array price represent daily price history stock pricesi stock price ith dayA smooth descent period stock consist contiguous day price day low price precede day exactly 1 the day period exempt rulereturn number smooth descent period example 1input price 3214output 7explanation there 7 smooth descent periods3 2 1 4 32 21 321note period day smooth descent period definitionexample 2input price 8677output 4explanation there 4 smooth descent period 8 6 7 7note 86 smooth descent period 8 6 1example 3input price 1output 1explanation there 1 smooth descent period 1 Constraints1 priceslength 1051 pricesi 105
0array
you give 0indexed array arr consist n positive integer positive integer kThe array arr call Kincreasing arrik arri hold index k n1For example arr 4 1 5 2 6 2 Kincreasing k 2 becausearr0 arr2 4 5arr1 arr3 1 2arr2 arr4 5 6arr3 arr5 2 2however arr Kincreasing k 1 arr0 arr1 k 3 arr0 arr3In operation choose index change arri positive integerReturn minimum number operation require array kincreasing give k Example 1input arr 54321 k 1Output 4explanationfor k 1 resultant array nondecreasingsome Kincreasing array form 56789 11111 22344 all require 4 operationsIt suboptimal change array example 678910 5 operationsIt show array kincreasing 4 operationsexample 2input arr 415262 k 2output 0explanationthis example problem descriptionHere index 2 5 arri2 arrisince give array kincreasing need perform operationsexample 3input arr 415262 k 3output 2explanationindice 3 5 one satisfy arri3 arri 3 5one way array kincreasing change arr3 4 arr5 5the array 415465note way array kincreasing require 2 operation Constraints1 arrlength 1051 arri k arrlength
0array
a parenthesis stre nonempty string consist it valid follow condition trueIt it write AB a concatenate B A b valid parenthesis stringsIt write a a valid parenthesis stringYou give parenthesis stre s string lock length n locked binary string consist 0s 1s for index lockedIf lockedi 1 change siBut lockedi 0 change si return true s valid parenthesis stre otherwise return false example 1input s lock 010100output trueexplanation locked1 1 locked3 1 change s1 s3we change s0 s4 leave s2 s5 unchanged s validExample 2input s lock 0000output trueexplanation we need change s validExample 3input s lock 0output falseexplanation lock permit change s0 change s0 s valid Constraintsn slength lockedlength1 n 105si lockedi 0 1
2string
there n x n grid topleft cell 0 0 bottomright cell n 1 n 1 you give integer n integer array startpos startpos startrow startcol indicate robot initially cell startrow startcolyou give 0indexed string s length m si ith instruction robot L leave r right u D downthe robot begin execute ith instruction s it execute instruction end s stop condition metthe instruction robot gridThere instruction leave executeReturn array answer length m answeri number instruction robot execute robot begin execute ith instruction s Example 1input n 3 startpos 01 s rrddluoutput 154310explanation start startpos begin execution ith instruction 0th RRDDLU only instruction r execute move grid 1st RDDLU all instruction execute stay grid end 1 1 2nd DDLU all instruction execute stay grid end 1 0 3rd DLU all instruction execute stay grid end 0 0 4th LU only instruction l execute move grid 5th u if move gridExample 2input n 2 startpos 11 s LURDOutput 4100explanation 0th LURD 1st URD 2nd RD 3rd DExample 3input n 1 startpos 00 s lrudoutput 0000explanation no matter instruction robot begin execution grid Constraintsm slength1 n m 500startposlength 20 startrow startcol n consist L R u d
2string
you give 0indexed array n integer arrthe interval element arr define absolute difference index more formally interval arri arrj jReturn array interval length n intervalsi sum intervals arri element arr value arriNote x absolute value x Example 1input arr 2131233output 4272445explanation Index 0 another 2 find index 4 0 4 4 index 1 another 1 find index 3 1 3 2 Index 2 two 3s find index 5 6 2 5 2 6 7 index 3 another 1 find index 1 3 1 2 index 4 another 2 find index 0 4 0 4 index 5 two 3s find index 2 6 5 2 5 6 4 Index 6 two 3s find index 2 5 6 2 6 5 5example 2input arr 1051010output 5034explanation Index 0 two 10 find index 2 3 0 2 0 3 5 index 1 there 5 array sum interval identical element 0 index 2 two 10 find index 0 3 2 0 2 3 3 Index 3 two 10 find index 0 2 3 0 3 2 4 Constraintsn arrlength1 n 1051 arri 105
0array
Alice 0indexed array arr consist n positive integer she choose arbitrary positive integer k create new 0indexed integer array lower high follow mannerloweri arri k index 0 nhigheri arri k index 0 nUnfortunately Alice lose array however remember integer present array low high array integer belong help Alice recover original arrayGiven array num consist 2n integer exactly n integer present lower remain high return original array arr in case answer unique return valid arrayNote the test case generate exist valid array arr Example 1input num 21064812output 3711explanationif arr 3711 k 1 low 2610 high 4812combining lower high give 26104812 permutation numsanother valid possibility arr 579 k 3 in case low 246 high 81012 Example 2input num 1133output 22explanationif arr 22 k 1 low 11 high 33combining low high give 1133 equal numsNote arr 13 case possible way obtain 1133 k 0this invalid k positiveexample 3input num 5435output 220explanationthe possible combination arr 220 k 215 use low 5 high 435 Constraints2 n numslength1 n 10001 numsi 109The test case generate exist valid array arr
0array
give string s consist character b return true appear b string otherwise return false example 1input s aaabbboutput trueexplanationthe index 0 1 2 bs index 3 4 5hence appear b return trueExample 2input s ababoutput falseExplanationThere index 2 b index 1hence appear b return falseexample 3Input s bbboutput trueexplanationthere appear b return true Constraints1 slength 100si b
2string
you give integer mass represent original mass planet you give integer array asteroid asteroidsi mass ith asteroidYou arrange planet collide asteroids arbitrary order if mass planet great equal mass asteroid asteroid destroy planet gain mass asteroid Otherwise planet destroyedReturn true asteroid destroy otherwise return false Example 1input mass 10 asteroid 3919521output trueexplanation one way order asteroid 9195321 the planet collide asteroid mass 9 new planet mass 10 9 19 the planet collide asteroid mass 19 new planet mass 19 19 38 the planet collide asteroid mass 5 new planet mas 38 5 43 the planet collide asteroid mass 3 new planet mass 43 3 46 the planet collide asteroid mass 21 new planet mass 46 21 67all asteroid destroyedexample 2input mass 5 asteroid 49234output falseexplanation the planet gain mass destroy asteroid mass 23after planet destroy asteroid mass 5 4 9 4 22this 23 collision destroy asteroid Constraints1 mass 1051 asteroidslength 1051 asteroidsi 105
0array
a company organize meeting list n employee wait invite they arrange large circular table capable seating number employeesthe employee number 0 n 1 each employee favorite person attend meet sit favorite person table the favorite person employee themselfGiven 0indexe integer array favorite favoritei denote favorite person ith employee return maximum number employee invite meet Example 1input favorite 2212output 3explanationthe figure show company invite employee 0 1 2 seat round tableall employee invite employee 2 sit employee 0 1 3 simultaneouslynote company invite employee 1 2 3 desire seatsthe maximum number employee invite meet 3 Example 2input favorite 120output 3explanation each employee favorite person employee way company invite invite employeeThe seat arrangement figure give example 1 employee 0 sit employee 2 1 employee 1 sit employee 0 2 employee 2 sit employee 1 0the maximum number employee invite meet 3Example 3input favorite 30141output 4explanationthe figure show company invite employee 0 1 3 4 seat round tableemployee 2 invite spot favorite employee 1 takenSo company leave meetingthe maximum number employee invite meet 4 Constraintsn favoritelength2 n 1050 favoritei n 1favoritei
1graph
you give string title consist word separate single space word consist english letter Capitalize string change capitalization word thatIf length word 1 2 letter change letter lowercaseotherwise change letter uppercase remain letter lowercasereturn capitalize title Example 1input title capiTalIze the titleoutput Capitalize the titleexplanationsince word length 3 letter word uppercase remain letter lowercaseexample 2input title First leTTeR each WordOutput First Letter each WordExplanationThe word length 2 lowercasethe remain word length 3 letter remain word uppercase remain letter lowercaseExample 3input title lOve leetcodeoutput love LeetcodeExplanationThe word length 1 lowercasethe remain word length 3 letter remain word uppercase remain letter lowercase Constraints1 titlelength 100title consist word separate single space lead trail spacesEach word consist uppercase lowercase english letter nonempty
2string
you give m x n binary matrix grid cell 0 1 occupiedyou give stamp size stampheight x stampwidth we want fit stamp follow give restriction requirementsCover cellsDo cover occupy cellsWe stamp wantstamp overlap otherstamp allow rotatedstamp stay completely inside gridReturn true possible fit stamp follow give restriction requirement otherwise return false example 1input grid 10001000100010001000 stampheight 4 stampwidth 3output trueexplanation we overlap stamp label 1 2 image able cover cellsexample 2input grid 1000010000100001 stampheight 2 stampwidth 2 output false Explanation there way fit stamp cell stamp go outside grid Constraintsm gridlengthn gridrlength1 m n 1051 m n 2 105gridrc 0 11 stampheight stampwidth 105
0array
an n x n matrix valid row column contain integer 1 n inclusiveGiven n x n integer matrix matrix return true matrix valid otherwise return false example 1input matrix 123312231output trueexplanation in case n 3 row column contain number 1 2 3hence return trueexample 2input matrix 111123123output falseexplanation in case n 3 row column contain number 2 3hence return false Constraintsn matrixlength matrixilength1 n 1001 matrixij n
0array
a swap define take distinct position array swap value themA circular array define array consider element element adjacentGiven binary circular array num return minimum number swap require group 1s present array location Example 1input num 0101100output 1explanation here way group 1s together0011100 1 swap0111000 1 swap1100001 2 swap circular property arraythere way group 1s 0 swapsThus minimum number swap require 1example 2input num 011100110output 2explanation here way group 1s together111000011 2 swap circular property array111110000 2 swapsthere way group 1 0 1 swapsthu minimum number swap require 2example 3input num 11001output 0explanation all 1s group circular property arraythus minimum number swap require 0 Constraints1 numslength 105numsi 0 1
0array
you n flower seed every seed plant begin grow bloom planting seed take time growth seed you give 0indexed integer array planttime growTime length n eachplanttimei number day take plant ith seed every day work plant exactly seed you work planting seed consecutive day planting seed complete work plantTimei day plant totalgrowtimei number day take ith seed grow completely plant after day growth flower bloom stay bloomed foreverfrom begin day 0 plant seed orderreturn early possible day seed bloom Example 1input planttime 143 growTime 231output 9explanation the gray pot represent planting day colored pot represent grow day flower represent day bloomsOne optimal way ison day 0 plant 0th seed the seed grow 2 day bloom day 3on day 1 2 3 4 plant 1st seed the seed grow 3 day bloom day 8on day 5 6 7 plant 2nd seed the seed grow 1 day bloom day 9thus day 9 seed bloomingExample 2input planttime 1232 growtime 2121output 9explanation the gray pot represent planting day colored pot represent grow day flower represent day bloomsOne optimal way ison day 1 plant 0th seed the seed grow 2 day bloom day 4on day 0 3 plant 1st seed the seed grow 1 day bloom day 5on day 2 4 5 plant 2nd seed the seed grow 2 day bloom day 8on day 6 7 plant 3rd seed the seed grow 1 day bloom day 9thus day 9 seed bloomingExample 3input planttime 1 growTime 1output 2explanation on day 0 plant 0th seed the seed grow 1 day bloom day 2thus day 2 seed bloom Constraintsn planttimelength growtimelength1 n 1051 plantTimei growTimei 104
0array
a string s partitioned group size k following procedurethe group consist k character stre second group consist k character string each character exactly groupfor group stre k character remain character fill complete groupnote partition remove fill character group exist concatenate group order resultant string sGiven string s size group k character fill return string array denote composition group s divide procedure Example 1Input s abcdefghi k 3 fill xOutput abcdefghiexplanationthe 3 character abc form groupThe 3 character def form second groupThe 3 character ghi form groupsince group completely fill character stre need use fillThus group form abc def ghiExample 2Input s abcdefghij k 3 fill xOutput abcdefghijxxExplanationSimilar previous example form group abc def ghiFor group use character j string to complete group add x twicethus 4 group form abc def ghi jxx Constraints1 slength 100s consist lowercase english letter only1 k 100fill lowercase english letter
2string
you give 0indexed 2D integer array question questionsi pointsi brainpowerithe array describe question exam process question order ie start question 0 decision solve skip question solve question earn pointsi point unable solve brainpoweri question if skip question decision questionfor example give question 3 2 4 3 4 4 2 5if question 0 solve earn 3 point unable solve question 1 2if instead question 0 skip question 1 solve earn 4 point unable solve question 2 3return maximum point earn exam Example 1input question 32434425output 5explanation the maximum point earn solve question 0 3 Solve question 0 earn 3 point unable solve 2 question unable solve question 1 2 Solve question 3 Earn 2 pointstotal point earn 3 2 5 there way earn 5 pointsExample 2input question 1122334455output 7explanation the maximum point earn solve question 1 4 Skip question 0 Solve question 1 earn 2 point unable solve 2 question unable solve question 2 3 Solve question 4 Earn 5 pointstotal point earn 2 5 7 there way earn 7 point Constraints1 questionslength 105questionsilength 21 pointsi brainpoweri 105
0array
you n computer you give integer n 0indexed integer array battery ith battery run computer batteriesi minute you interest running n computer simultaneously give batteriesinitially insert battery computer after integer time moment remove battery computer insert battery number time the insert battery totally new battery battery computer you assume remove insert process timenote battery rechargedreturn maximum number minute run n computer simultaneously example 1input n 2 battery 333output 4explanation initially insert battery 0 computer battery 1 second computerafter minute remove battery 1 second computer insert battery 2 instead note battery 1 run minuteAt end minute battery 0 drain need remove computer insert battery 1 insteadBy end fourth minute battery 1 drain computer long runningwe run computer simultaneously 4 minute return 4example 2input n 2 battery 1111output 2explanation initially insert battery 0 computer battery 2 second computer after minute battery 0 battery 2 drain need remove insert battery 1 computer battery 3 second computer after minute battery 1 battery 3 drain second computer long runningwe run computer simultaneously 2 minute return 2 Constraints1 n batterieslength 1051 batteriesi 109
0array
a shop sell candy discount for candy sell shop give candy freeThe customer choose candy away free long cost choose candy equal minimum cost candy boughtfor example 4 candy cost 1 2 3 4 customer buy candy cost 2 3 candy cost 1 free candy cost 4given 0indexed integer array cost costi denote cost ith candy return minimum cost buying candy example 1input cost 123output 5explanation we buy candy cost 2 3 candy cost 1 freethe total cost buying candy 2 3 5 this way buy candiesnote buy candy cost 1 3 candy cost 2 freethe cost free candy equal minimum cost purchase candiesexample 2input cost 657922output 23explanation the way minimum cost describe Buy candy cost 9 7 take candy cost 6 free we buy candy cost 5 2 take remain candy cost 2 freehence minimum cost buy candy 9 7 5 2 23example 3input cost 55output 10explanation since 2 candy buy there candy freehence minimum cost buy candy 5 5 10 constraints1 costlength 1001 costi 100
0array
you give 0indexed array n integer difference describe difference pair consecutive integer hide sequence length n 1 more formally hide sequence hide differencesi hiddeni 1 hiddeniyou give integer low upper describe inclusive range value lower upper hide sequence containfor example give difference 1 3 4 low 1 upper 6 hide sequence sequence length 4 element 1 6 inclusive3 4 1 5 4 5 2 6 possible hide sequences5 6 3 7 possible contain element great 61 2 3 4 possible difference correctreturn number possible hide sequence if possible sequence return 0 example 1input difference 134 low 1 upper 6output 2explanation the possible hide sequence 3 4 1 5 4 5 2 6thus return 2example 2input difference 34512 low 4 upper 5output 4explanation the possible hide sequence 3 0 4 1 2 0 2 1 3 2 3 1 1 2 2 3 4 2 0 3 1 4 5 3thus return 4example 3input difference 472 low 3 upper 6output 0explanation there possible hide sequence thus return 0 Constraintsn differenceslength1 n 105105 differencesi 105105 lower upper 105
0array
along long library corridor line seat decorative plant you give 0indexed string corridor length n consist letter S P S represent seat p represent plantOne room divider instal left index 0 right index n 1 additional room divider instal for position index 1 1 n 1 divid installeddivide corridor nonoverlapping section section exactly seat number plant there multiple way perform division two way different position room divider instal way second wayreturn number way divide corridor since answer large return modulo 109 7 if way return 0 example 1input corridor SSPPSPSOutput 3explanation there 3 different way divide corridorthe black bar image indicate room divider installednote way section exactly seatsexample 2input corridor PPSPSPOutput 1explanation there 1 way divide corridor instal additional dividersinstalling create section exactly seatsexample 3input corridor SOutput 0explanation there way divide corridor section exactly seat Constraintsn corridorlength1 n 105corridori S P
2string
give integer array num return number element strictly small strictly great element appear num Example 1input num 117215output 2explanation the element 7 element 2 strictly small element 11 strictly great itelement 11 element 7 strictly small element 15 strictly great itin total 2 element having strictly small strictly great element appear numsexample 2input num 33390output 2explanation the element 3 element 3 strictly small element 90 strictly great itsince element value 3 total 2 element having strictly small strictly great element appear num Constraints1 numslength 100105 numsi 105
0array
you give 0indexed integer array num length consist equal number positive negative integersyou rearrange element num modify array follow give conditionsEvery consecutive pair integer opposite signsFor integer sign order present num preservedThe rearrange array begin positive integerreturn modify array rearrange element satisfy aforementione condition Example 1input num 312524output 321524explanationthe positive integer num 312 the negative integer 254the possible way rearrange satisfy condition 321524other way 122534 312254 235142 incorrect satisfy condition Example 2input num 11output 11explanation1 positive integer 1 negative integer numsSo num rearrange 11 constraints2 numslength 2 105numslength even1 numsi 105nums consist equal number positive negative integer
0array
you give integer array num a number x lonely appear adjacent number ie x 1 x 1 appear arrayreturn lonely number num you return answer order Example 1input num 10658output 108explanation 10 lonely number appear exactly 9 11 appear num 8 lonely number appear exactly 7 9 appear num 5 lonely number 6 appear num vice versaHence lonely number num 10 8note 8 10 returnedExample 2input num 1353output 15explanation 1 lonely number appear exactly 0 2 appear num 5 lonely number appear exactly 4 6 appear num 3 lonely number appear twicehence lonely number num 1 5note 5 1 return Constraints1 numslength 1050 numsi 106
0array
there type personsthe good person the person tell truththe bad person the person tell truth lieYou give 0indexed 2d integer array statement size n x n represent statement n people more specifically statementsij following0 represent statement person person j bad person1 represent statement person person j good person2 represent statement person person jAdditionally person make statement Formally statementsii 2 0 nreturn maximum number people good base statement n people example 1input statement 212122202output 2explanation each person make single statement person 0 state person 1 good Person 1 state person 0 good Person 2 state person 1 badlet person 2 key assume person 2 good person base statement person 2 person 1 bad person now know sure person 1 bad person 2 good base statement person 1 person 1 bad tell truth there contradiction case assumption invalid lie in case person 0 bad person lie statement follow person 2 good person good person group assume person 2 bad person base statement person 2 person 2 bad tell truth follow scenario person 0 1 bad explain follow person 2 bad tell truth good person group lie in case person 1 good person since person 1 good person person 0 good person follow person 2 bad lie good person groupWe 2 person good good case return 2note way arrive conclusionexample 2input statement 2002output 1explanation each person make single statement person 0 state person 1 bad Person 1 state person 0 badlet person 0 key assume person 0 good person base statement person 0 person 1 bad person lie follow person 0 good person good person group assume person 0 bad person base statement person 0 person 0 bad tell truth follow scenario person 0 1 bad follow person 0 bad tell truth good person group lie in case person 1 good person follow person 0 bad lie good person groupWe person good good case return 1note way arrive conclusion Constraintsn statementslength statementsilength2 n 15statementsij 0 1 2statementsii 2
0array
you give array integer num you give integer original number need search numsyou follow stepsIf original find num multiply ie set original 2 originalotherwise stop processRepeat process new number long find numberreturn final value original Example 1input num 536112 original 3output 24explanation 3 find num 3 multiply 2 obtain 6 6 find num 6 multiply 2 obtain 12 12 find num 12 multiply 2 obtain 24 24 find num thus 24 returnedExample 2input num 279 original 4Output 4explanation 4 find num thus 4 return Constraints1 numslength 10001 numsi original 1000
0array
you give 0indexed binary array num length n num divide index 0 n array possibly numsleft numsrightnumsleft element nums index 0 1 inclusive numsright element nums index n 1 inclusiveif 0 numsleft numsright element numsif n numsleft element num numsright emptythe division score index sum number 0s numsleft number 1s numsrightreturn distinct index high possible division score you return answer order Example 1input num 0010output 24explanation Division index 0 numsleft numsright 0010 the score 0 1 1 1 numsleft 0 numsright 010 the score 1 1 2 2 numsleft 00 numsright 10 the score 2 1 3 3 numsleft 001 numsright 0 the score 2 0 2 4 numsleft 0010 numsright the score 3 0 3indice 2 4 high possible division score 3note answer 42 acceptedexample 2input num 000output 3explanation Division index 0 numsleft numsright 000 the score 0 0 0 1 numsleft 0 numsright 00 the score 1 0 1 2 numsleft 00 numsright 0 the score 2 0 2 3 numsleft 000 numsright the score 3 0 3only index 3 high possible division score 3example 3input num 11output 0explanation Division index 0 numsleft numsright 11 the score 0 2 2 1 numsleft 1 numsright 1 the score 0 1 1 2 numsleft 11 numsright the score 0 0 0only index 0 high possible division score 2 Constraintsn numslength1 n 105numsi 0 1
0array
the hash 0indexed string s length k give integer p m compute follow functionhashs p m vals0 p0 vals1 p1 valsk1 pk1 mod mWhere valsi represent index si alphabet vala 1 valz 26you give string s integer power modulo k hashValue Return sub substre s length k hashsub power modulo hashValueThe test case generate answer existsA substre contiguous nonempty sequence character string Example 1input s leetcode power 7 modulo 20 k 2 hashValue 0output eeexplanation the hash ee compute hashee 7 20 5 1 5 7 mod 20 40 mod 20 0 ee substre length 2 hashvalue 0 hence return eeexample 2Input s fbxzaad power 31 modulo 100 k 3 hashvalue 32output fbxexplanation the hash fbx compute hashfbx 31 100 6 1 2 31 24 312 mod 100 23132 mod 100 32 the hash bxz compute hashbxz 31 100 2 1 24 31 26 312 mod 100 25732 mod 100 32 fbx substre length 3 hashvalue 32 hence return fbxnote bxz hash 32 appear later fbx Constraints1 k slength 2 1041 power modulo 1090 hashValue modulos consist lowercase english letter onlythe test case generate answer exist
2string
you give 0indexed array string word each string consists lowercase english letter no letter occur string wordsTwo string s1 s2 say connect set letter s2 obtain set letter s1 follow operationsadde exactly letter set letter s1delete exactly letter set letter s1replace exactly letter set letter s1 letter include itselfThe array word divide nonintersecte group a string belong group follow trueIt connect string groupit string present groupnote string word group manner string belong group connect string present group it prove arrangement uniquereturn array an size 2 whereans0 maximum number group word divide andans1 size large group Example 1input word ababcdeoutput 23explanation words0 obtain words1 replace b words2 add b so words0 connect words1 words2 words1 obtain words0 replace b words2 add so words1 connect words0 words2 words2 obtain words0 delete b words1 delete so words2 connect words0 words1 words3 connect string wordsthu word divide 2 group abab cde the size large group 3 Example 2input word aababcoutput 13explanation words0 connect words1 words1 connect words0 words2 words2 connect words1since string connect group togetherThus size large group 3 Constraints1 wordslength 2 1041 wordsilength 26wordsi consists lowercase english letter onlyNo letter occur wordsi
2string
you give 0indexed integer array num integer pivot Rearrange num follow condition satisfiedEvery element pivot appear element great pivotevery element equal pivot appear element great pivotthe relative order element pivot element great pivot maintainedMore formally consider pi pj pi new position ith element pj new position jth element for element pivot j numsi pivot numsj pivot pi pj Similarly element great pivot j numsi pivot numsj pivot pi pjreturn num rearrangement Example 1input num 91251014310 pivot 10output 95310101214explanation the element 9 5 3 pivot leave arraythe element 12 14 great pivot right arraythe relative ordering element great pivot maintain 9 5 3 12 14 respective orderingsExample 2input num 3432 pivot 2output 3243explanation the element 3 pivot leave arraythe element 4 3 great pivot right arraythe relative ordering element great pivot maintain 3 4 3 respective ordering Constraints1 numslength 105106 numsi 106pivot equal element num
0array
you give 0indexed integer array num consist 3 n elementsYou allow remove subsequence element size exactly n num the remain 2 n element divide equal partsthe n element belong sum sumfirstThe n element belong second sum sumsecondthe difference sum part denote sumfirst sumsecondFor example sumfirst 3 sumsecond 2 difference 1similarly sumfirst 2 sumsecond 3 difference 1return minimum difference possible sum part removal n element Example 1input num 312output 1explanation here num 3 element n 1 thus remove 1 element num divide array equal part if remove nums0 3 array 12 the difference sum part 1 2 1 if remove nums1 1 array 32 the difference sum part 3 2 1 if remove nums2 2 array 31 the difference sum part 3 1 2the minimum difference sum part min112 1 Example 2input num 795813output 1explanation here n 2 so remove 2 element divide remain array part contain element eachIf remove nums2 5 nums3 8 resultant array 7913 the difference sum 79 13 12to obtain minimum difference remove nums1 9 nums4 1 the resultant array 7583 the difference sum part 75 83 1it show possible obtain difference small 1 constraintsnumslength 3 n1 n 1051 numsi 105
0array
you give 0indexed integer array num Rearrange value num accord follow rulessort value odd index num nonincrease orderfor example num 4123 step 4321 the value odd index 1 3 sort nonincrease ordersort value index num nondecrease orderfor example num 4123 step 2143 the value indice 0 2 sort nondecrease orderreturn array form rearrange value num Example 1input num 4123output 2341explanation first sort value present odd index 1 3 nonincreasing orderso num change 4123 4321next sort value present index 0 2 nondecrease orderso num change 4123 2341thus array form rearrange value 2341example 2input num 21output 21explanation since exactly odd index index rearrangement value take placethe resultant array form 21 initial array Constraints1 numslength 1001 numsi 100
0array
a Bitset data structure compactly store bitsimplement Bitset classbitsetint size Initializes Bitset size bit 0void fixint idx Updates value bit index idx 1 if value 1 change occursvoid unfixint idx Updates value bit index idx 0 if value 0 change occursvoid flip Flips value bit Bitset in word bit value 0 value 1 vice versaboolean check value bite Bitset 1 return true satisfie condition false otherwiseboolean Checks bit Bitset value 1 return true satisfie condition false otherwiseint count Returns total number bit Bitset value 1string tostre return current composition Bitset Note resultant string character ith index coincide value ith bit Bitset Example 1inputbitset fix fix flip unfix flip unfix count tostring5 3 1 0 0 outputnull null null null false null null true null 2 01010ExplanationBitset bs new Bitset5 bitset 00000bsfix3 value idx 3 update 1 bitset 00010bsfix1 value idx 1 update 1 bitset 01010 bsflip value bit flip bitset 10101 bsall return false value bitset 1bsunfix0 value idx 0 update 0 bitset 00101bsflip value bit flip bitset 11010 bsone return true 1 index value 1bsunfix0 value idx 0 update 0 bitset 01010bscount return 2 2 bit value 1bstostring return 01010 composition bitset Constraints1 size 1050 idx size 1At 105 call total fix unfix flip count toStringAt count tostringat 5 call tostre
0array
you give 0indexed binary string s represent sequence train car si 0 denote ith car contain illegal good si 1 denote ith car contain illegal goodsAs train conductor like rid car contain illegal good you follow operation number timesremove train car leave end ie remove s0 take 1 unit timeremove train car right end ie remove sslength 1 take 1 unit timeremove train car sequence take 2 unit timereturn minimum time remove car contain illegal goodsnote sequence car consider car contain illegal good Example 1input s 1100101output 5explanation one way remove car contain illegal good sequence remove car leave end 2 time Time take 2 1 2 remove car right end Time take 1 remove car contain illegal good find middle Time take 2this obtain total time 2 1 2 5 an alternative way remove car leave end 2 time Time take 2 1 2 remove car right end 3 time Time take 3 1 3this obtain total time 2 3 55 minimum time take remove car contain illegal good there way remove timeexample 2input s 0010output 2explanationone way remove car contain illegal good sequence remove car leave end 3 time Time take 3 1 3this obtain total time 3another way remove car contain illegal good sequence remove car contain illegal good find middle Time take 2this obtain total time 2another way remove car contain illegal good sequence remove car right end 2 time Time take 2 1 2 this obtain total time 22 minimum time take remove car contain illegal good there way remove time Constraints1 slength 2 105si 0 1
2string
you give 0indexed array num consist n positive integersThe array num call alternate ifnumsi 2 numsi 2 n 1numsi 1 numsi 1 n 1in operation choose index change numsi positive integerreturn minimum number operation require array alternate Example 1input num 313243output 3explanationone way array alternate convert 313131the number operation require case 3it prove possible array alternate 3 operation Example 2input num 12222output 2explanationone way array alternate convert 12121the number operation require case 2note array convert 22222 case nums0 nums1 violate condition alternate array Constraints1 numslength 1051 numsi 105
0array
you give array positive integer bean integer represent number magic bean find particular magic bagremove number bean possibly bag number bean remain nonempty bag contain bean equal once bean remove bag allow return bagsreturn minimum number magic bean remove Example 1input bean 4165output 4explanation we remove 1 bean bag 1 bean this result remain bag 4065 then remove 2 bean bag 6 bean this result remain bag 4045 then remove 1 bean bag 5 bean this result remain bag 4044we remove total 1 2 1 4 bean remain nonempty bag equal number beansThere solution remove 4 bean fewerexample 2input bean 21032output 7explanation we remove 2 bean bag 2 bean this result remain bag 01032 then remove 2 bean bag 2 bean this result remain bag 01030 then remove 3 bean bag 3 bean this result remain bag 01000we remove total 2 2 3 7 bean remain nonempty bag equal number beansthere solution remove 7 bean few Constraints1 beanslength 1051 beansi 105
0array
you give integer array num length n integer numslots 2 numslot n there numslots slot number 1 numslotsyou place n integer slot slot contain number the and sum give placement sum bitwise and number respective slot numberfor example and sum place number 1 3 slot 1 4 6 slot 2 equal 1 and 1 3 and 1 4 and 2 6 and 2 1 1 0 2 4return maximum possible and sum num give numslots slot Example 1input num 123456 numslot 3output 9explanation one possible placement 1 4 slot 1 2 6 slot 2 3 5 slot 3 this give maximum and sum 1 and 1 4 and 1 2 and 2 6 and 2 3 and 3 5 and 3 1 0 2 2 3 1 9example 2input num 1310471 numslot 9output 24explanation one possible placement 1 1 slot 1 3 slot 3 4 slot 4 7 slot 7 10 slot 9This give maximum and sum 1 and 1 1 and 1 3 and 3 4 and 4 7 and 7 10 and 9 1 1 3 4 7 8 24note slot 2 5 6 8 permit Constraintsn numslength1 numslot 91 n 2 numslots1 numsi 15
0array
give 0indexed integer array num length n integer k return number pair j 0 j n numsi numsj j divisible k Example 1input num 3122213 k 2Output 4ExplanationThere 4 pair meet requirement nums0 nums6 0 6 0 divisible 2 nums2 nums3 2 3 6 divisible 2 nums2 nums4 2 4 8 divisible 2 nums3 nums4 3 4 12 divisible 2example 2input num 1234 k 1output 0explanation since value num repeat pair ij meet requirement constraints1 numslength 1001 numsi k 100
0array
you give 0indexe array nums1 nums2 length n permutation 0 1 n 1A good triplet set 3 distinct value present increase order position nums1 nums2 in word consider pos1v index value v nums1 pos2v index value v nums2 good triplet set x y z 0 x y z n 1 pos1x pos1y pos1z pos2x pos2y pos2zreturn total number good triplet Example 1input nums1 2013 nums2 0123output 1explanation there 4 triplet xyz pos1x pos1y pos1z they 201 203 213 013 out triplet triplet 013 satisfie pos2x pos2y pos2z hence 1 good tripletExample 2input nums1 40132 nums2 41023output 4explanation the 4 good triplet 403 402 413 412 Constraintsn nums1length nums2length3 n 1050 nums1i nums2i n 1nums1 nums2 permutation 0 1 n 1
0array
you give string s integer repeatlimit construct new string repeatlimitedstre character s letter appear repeatlimit time row you use character sReturn lexicographically large repeatlimitedstre possibleA string lexicographically large string b position b differ string letter appear later alphabet corresponding letter b if minalength blength character differ long stre lexicographically large Example 1input s cczazcc repeatlimit 3output zzcccacexplanation we use character s construct repeatlimitedstre zzcccacthe letter appear 1 time rowthe letter c appear 3 time rowthe letter z appear 2 time rowhence letter appear repeatlimit time row string valid repeatlimitedstringthe string lexicographically large repeatlimitedstre possible return zzcccacnote string zzcccca lexicographically large letter c appear 3 time row valid repeatlimitedstringexample 2Input s aababab repeatlimit 2output bbabaaexplanation we use character s construct repeatlimitedstre bbabaa the letter appear 2 time rowthe letter b appear 2 time rowhence letter appear repeatlimit time row string valid repeatlimitedstringthe string lexicographically large repeatlimitedstre possible return bbabaanote string bbabaaa lexicographically large letter appear 2 time row valid repeatlimitedstre Constraints1 repeatlimit slength 105s consist lowercase english letter
2string
give 0indexed integer array num length n integer k return number pair j that0 j n 1 andnumsi numsj divisible k Example 1input num 12345 k 2output 7explanation the 7 pair index correspond product divisible 2 are0 1 0 3 1 2 1 3 1 4 2 3 3 4their product 2 4 6 8 10 12 20 respectivelyother pair 0 2 2 4 product 3 15 respectively divisible 2 example 2input num 1234 k 5output 0explanation there exist pair index correspond product divisible 5 Constraints1 numslength 1051 numsi k 105
0array
you give string s t in step append character s treturn minimum number step s t anagram otherAn anagram string string contain character different order Example 1input s leetcode t coatsoutput 7explanation in 2 step append letter s leetcode form s leetcodea in 5 step append letter leede t coat form t coatsleedeleetcodeas coatsleede anagram otherWe total 2 5 7 stepsIt show way anagram 7 stepsexample 2input s night t thingOutput 0explanation the give string anagram thus need step Constraints1 slength tlength 2 105s t consist lowercase english letter
2string
you give array time timei denote time take ith bus complete tripeach bus multiple trip successively trip start immediately complete current trip also bus operate independently trip bus influence trip busyou give integer totaltrip denote number trip bus total Return minimum time require bus complete totaltrip trip Example 1input time 123 totaltrip 5output 3explanation at time t 1 number trip complete bus 100 the total number trip complete 1 0 0 1 at time t 2 number trip complete bus 210 the total number trip complete 2 1 0 3 at time t 3 number trip complete bus 311 the total number trip complete 3 1 1 5so minimum time need bus complete 5 trip 3example 2input time 2 totaltrip 1Output 2explanationthere bus complete trip t 2so minimum time need complete 1 trip 2 Constraints1 timelength 1051 timei totaltrip 107
0array
you give 0indexed 2D integer array tires tiresi fi ri indicate ith tire finish xth successive lap fi rix1 secondsFor example fi 3 ri 2 tire finish 1st lap 3 second 2nd lap 3 2 6 second 3rd lap 3 22 12 second etcyou give integ changetime integer numLapsThe race consist numlap lap start race tire you unlimited supply tire lap change give tire include current tire type wait changeTime secondsReturn minimum time finish race Example 1input tire 2334 changetime 5 numlap 4Output 21explanation Lap 1 Start tire 0 finish lap 2 secondsLap 2 continue tire 0 finish lap 2 3 6 secondslap 3 Change tire new tire 0 5 second finish lap 2 secondsLap 4 continue tire 0 finish lap 2 3 6 secondstotal time 2 6 5 2 6 21 secondsthe minimum time complete race 21 secondsexample 2input tire 1102234 changeTime 6 numlap 5output 25explanation Lap 1 Start tire 1 finish lap 2 secondsLap 2 continue tire 1 finish lap 2 2 4 secondsLap 3 Change tire new tire 1 6 second finish lap 2 secondsLap 4 continue tire 1 finish lap 2 2 4 secondslap 5 Change tire tire 0 6 second finish lap 1 secondtotal time 2 4 6 2 4 6 1 25 secondsthe minimum time complete race 25 second Constraints1 tireslength 105tiresilength 21 fi changetime 1052 ri 1051 numlap 1000
0array
you give 0indexed integer array num you give integer key present numsfor unique integer target num count number time target immediately follow occurrence key num in word count number index that0 numslength 2numsi key andnumsi 1 targetreturn target maximum count the test case generate target maximum count unique Example 1input num 11002001100 key 1output 100explanation for target 100 2 occurrence index 1 4 follow occurrence keyNo integer follow occurrence key return 100example 2input num 22223 key 2output 2explanation for target 2 3 occurrence index 1 2 3 follow occurrence keyFor target 3 occurrence index 4 follow occurrence keytarget 2 maximum number occurrence follow occurrence key return 2 constraints2 numslength 10001 numsi 1000The test case generate answer unique
0array
you give 0indexed integer array mapping represent mapping rule shuffle decimal system mappingi j mean digit map digit j systemthe map value integer new integer obtain replace occurrence digit integer mappingi 0 9you give integer array num Return array num sort nondecrease order base map value elementsnoteselement map value appear relative order inputThe element num sort base map value replace Example 1input mapping 8940213576 num 99133838output 33838991explanation Map number 991 follows1 mapping9 6 occurrence digit 9 62 mapping1 9 occurrence digit 1 9Therefore map value 991 669338 map 007 7 remove lead zeros38 map 07 7 remove lead zerosSince 338 38 share map value remain relative order 338 come 38thus sort array 33838991example 2input mapping 0123456789 num 789456123output 123456789explanation 789 map 789 456 map 456 123 map 123 thus sort array 123456789 Constraintsmappinglength 100 mappingi 9all value mappingi unique1 numslength 3 1040 numsi 109
0array
you give positive integer n represent number nod Directed Acyclic Graph DAG the node number 0 n 1 inclusiveYou give 2d integer array edge edgesi fromi toi denote unidirectional edge fromi toi graphReturn list answer answeri list ancestor ith node sort ascend orderA node u ancestor node v u reach v set edge Example 1input n 8 edgelist 030413242735363746output 0102013012340123explanationthe diagram represent input graph Nodes 0 1 2 ancestor Node 3 ancestor 0 1 Node 4 ancestor 0 2 Node 5 ancestor 0 1 3 Node 6 ancestor 0 1 2 3 4 Node 7 ancestor 0 1 2 3example 2input n 5 edgelist 01020304121314232434output 0010120123explanationthe diagram represent input graph Node 0 ancestor Node 1 ancestor 0 Node 2 ancestor 0 1 Node 3 ancestor 0 1 2 Node 4 ancestor 0 1 2 3 constraints1 n 10000 edgeslength min2000 n n 1 2edgesilength 20 fromi toi n 1fromi toithere duplicate edgesthe graph direct acyclic
1graph
you give string s consist lowercase English lettersIn select adjacent character s swap themreturn minimum number move need s palindromenote input generate s convert palindrome Example 1input s aabboutput 2explanationwe obtain palindrome s abba baab we obtain abba s 2 move aabb abab abba we obtain baab s 2 move aabb abab baabThus minimum number move need s palindrome 2example 2input s leteltoutput 2explanationone palindrome obtain s 2 move lettelone way obtain letelt letetl lettelOther palindrome tleelt obtain 2 movesit show possible obtain palindrome 2 move Constraints1 slength 2000s consist lowercase English letterss convert palindrome finite number move
2string
a cell r c excel sheet represent string colrow wherecol denote column number c cell it represent alphabetical lettersfor example 1st column denote a 2nd b 3rd C onrow row number r cell the rth row represent integer rYou give string s format col1row1col2row2 col1 represent column c1 row1 represent row r1 col2 represent column c2 row2 represent row r2 r1 r2 c1 c2return list cell x y r1 x r2 c1 y c2 the cell represent string format mention sort nondecrease order column row Example 1input s K1L2Output K1K2L1L2ExplanationThe diagram show cell present listthe red arrow denote order cell presentedexample 2input s A1F1Output a1b1c1d1e1f1explanationthe diagram show cell present listthe red arrow denote order cell present Constraintsslength 5A s0 s3 Z1 s1 s4 9s consist uppercase English letter digit
2string
you give integer array num integer k Append k unique positive integer appear num num result total sum minimumReturn sum k integer append num Example 1input num 14251025 k 2output 5explanation the unique positive integer appear num append 2 3the result sum num 1 4 25 10 25 2 3 70 minimumthe sum integer append 2 3 5 return 5example 2input num 56 k 6output 25explanation the unique positive integer appear num append 1 2 3 4 7 8the result sum num 5 6 1 2 3 4 7 8 36 minimum the sum integer append 1 2 3 4 7 8 25 return 25 Constraints1 numslength 1051 numsi 1091 k 108
0array
you give array integer num perform follow stepsfind adjacent number num noncoprimeif number find stop processotherwise delete number replace LCM Least Common MultipleRepeat process long find adjacent noncoprime numbersReturn final modify array it show replace adjacent noncoprime number arbitrary order lead resultthe test case generate value final array equal 108two value x y noncoprime GCDx y 1 GCDx y Greatest Common Divisor x y Example 1input num 6432762output 1276explanation 6 4 noncoprime LCM6 4 12 now num 1232762 12 3 noncoprime LCM12 3 12 now num 122762 12 2 noncoprime LCM12 2 12 now num 12762 6 2 noncoprime LCM6 2 6 now num 1276there adjacent noncoprime number numsthus final modify array 1276note way obtain resultant arrayExample 2input num 2211333output 2113explanation 3 3 noncoprime LCM3 3 3 now num 221133 3 3 noncoprime LCM3 3 3 now num 22113 2 2 noncoprime LCM2 2 2 now num 2113there adjacent noncoprime number numsthus final modify array 2113note way obtain resultant array Constraints1 numslength 1051 numsi 105the test case generate value final array equal 108
0array
you give 0indexed integer array num integer key k A kdistant index index num exist index j j k numsj keyReturn list kdistant index sort increase order Example 1input num 3491395 key 9 k 1output 123456explanation here nums2 key nums5 key for index 0 0 2 k 0 5 k j 0 j k numsj key thus 0 kdistant index for index 1 1 2 k nums2 key 1 kdistant index for index 2 2 2 k nums2 key 2 kdistant index for index 3 3 2 k nums2 key 3 kdistant index for index 4 4 5 k nums5 key 4 kdistant index for index 5 5 5 k nums5 key 5 kdistant index for index 6 6 5 k nums5 key 6 kdistant indexthu return 123456 sort increase order Example 2input num 22222 key 2 k 2output 01234explanation for index num exist index j j k numsj key index kdistant index hence return 01234 Constraints1 numslength 10001 numsi 1000key integer array nums1 k numslength
0array
there n x n 0indexed grid artifact bury you give integer n 0indexed 2D integer array artifact describe position rectangular artifact artifactsi r1i c1i r2i c2i denote ith artifact bury subgrid wherer1i c1i coordinate topleft cell ith artifact andr2i c2i coordinate bottomright cell ith artifactYou excavate cell grid remove mud if cell artifact bury underneath uncover if part artifact uncover extract itgiven 0indexe 2D integer array dig digi ri ci indicate excavate cell ri ci return number artifact extractthe test case generate thatNo artifact overlapeach artifact cover 4 cellsthe entry dig unique Example 1input n 2 artifact 00000111 dig 0001output 1explanation the different color represent different artifact excavate cell label D gridThere 1 artifact extract red artifactthe blue artifact cell 11 remain uncover extract itthu return 1example 2input n 2 artifact 00000111 dig 000111output 2explanation both red blue artifact part uncover label D extract return 2 Constraints1 n 10001 artifactslength diglength minn2 105artifactsilength 4digilength 20 r1i c1i r2i c2i ri ci n 1r1i r2ic1i c2ino artifact overlapthe number cell cover artifact 4the entry dig unique
0array
you give 0indexed integer array num represent content pile nums0 topmost element pileIn perform followingIf pile remove topmost element pileif remove element add pile this element new topmost elementyou give integer k denote total number move madereturn maximum value topmost element pile possible exactly k move in case possible obtain nonempty pile k move return 1 example 1input num 522406 k 4Output 5explanationone way end 5 pile 4 move follow step 1 Remove topmost element 5 the pile 22406 Step 2 Remove topmost element 2 the pile 2406 step 3 Remove topmost element 2 the pile 406 step 4 add 5 pile the pile 5406note way end 5 pile it show 5 large answer possible 4 movesexample 2input num 2 k 1output 1explanation in option pop topmost element pilesince possible obtain nonempty pile return 1 Constraints1 numslength 1050 numsi k 109
0array
you give integer n denote number node weight direct graph the node number 0 n 1you give 2D integer array edge edgesi fromi toi weighti denote exist direct edge fromi toi weight weightilastly give distinct integer src1 src2 dest denote distinct node graphreturn minimum weight subgraph graph possible reach d src1 src2 set edge subgraph in case subgraph exist return 1A subgraph graph vertex edges subset original graph the weight subgraph sum weight constituent edge Example 1input n 6 edge 022056103145211233234342451 src1 0 src2 1 d 5output 9explanationthe figure represent input graphthe blue edge represent subgraph yield optimal answernote subgraph 103056 yield optimal answer it possible subgraph weight satisfy constraintsexample 2input n 3 edge 011211 src1 0 src2 1 d 2output 1explanationthe figure represent input graphit see exist path node 1 node 2 subgraph satisfy constraint Constraints3 n 1050 edgeslength 105edgesilength 30 fromi toi src1 src2 dest n 1fromi toisrc1 src2 dest pairwise distinct1 weighti 105
1graph
you give integer array num consist 2 n integersyou need divide num n pair thateach element belong exactly pairthe element present pair equalreturn true num divide n pair return false Example 1input num 323222output trueexplanation there 6 element num divide 6 2 3 pairsif num divide pair 2 2 3 3 2 2 satisfy conditionsExample 2input num 1234output falseexplanation there way divide num 4 2 2 pair pair satisfy condition Constraintsnumslength 2 n1 n 5001 numsi 500
0array
you give 0indexed string text 0indexed string pattern length 2 consist lowercase English lettersYou add pattern0 pattern1 text exactly note character add beginning end textreturn maximum number time pattern occur subsequence modify texta subsequence string derive string delete character change order remain character example 1input text abdcdbc pattern acoutput 4explanationif add pattern0 text1 text2 abadcdbc now number time ac occur subsequence 4some string 4 subsequence ac add character text aabdcdbc abdacdbchowever string abdcadbc abdccdbc abdcdbcc obtainable 3 subsequence ac suboptimalit show possible 4 subsequence ac add characterexample 2input text aabb pattern abOutput 6explanationsome string obtain text 6 subsequence ab aaabb aaabb aabbb Constraints1 textlength 105patternlength 2text pattern consist lowercase english letter
2string
you give array num positive integer in operation choose number num reduce exactly half number note choose reduce number future operationsreturn minimum number operation reduce sum num half Example 1input num 51981output 3explanation the initial sum num equal 5 19 8 1 33the follow way reduce sum halfpick number 19 reduce 95pick number 95 reduce 475pick number 8 reduce 4the final array 5 475 4 1 total sum 5 475 4 1 1475 the sum num reduce 33 1475 1825 half initial sum 1825 332 165overall 3 operation return 3it show reduce sum half 3 operationsexample 2input num 3820output 3explanation the initial sum num equal 3 8 20 31the follow way reduce sum halfpick number 20 reduce 10pick number 10 reduce 5pick number 3 reduce 15the final array 15 8 5 total sum 15 8 5 145 the sum num reduce 31 145 165 half initial sum 165 312 165overall 3 operation return 3it show reduce sum half 3 operation Constraints1 numslength 1051 numsi 107
0array
you give 0indexed binary string floor represent color tile floorfloori 0 denote ith tile floor color blackOn hand floori 1 denote ith tile floor color whiteyou give numCarpets carpetlen you numcarpets black carpet length carpetlen tile Cover tile give carpet number white tile visible minimum Carpets overlap anotherreturn minimum number white tile visible Example 1input floor 10110101 numcarpet 2 carpetLen 2output 2explanation the figure show way cover tile carpet 2 white tile visibleNo way cover tile carpet leave 2 white tile visibleexample 2input floor 11111 numcarpet 2 carpetlen 3output 0explanation the figure show way cover tile carpet white tile visiblenote carpet able overlap Constraints1 carpetLen floorlength 1000floori 0 11 numcarpets 1000
2string
you give 0indexed integer array num an index hill num close nonequal neighbor small numsi Similarly index valley num close nonequal neighbor large numsi Adjacent indice j hill valley numsi numsjNote index hill valley nonequal neighbor leave right indexreturn number hill valley num Example 1input num 241165output 3explanationat index 0 there nonequal neighbor 2 leave index 0 hill valleyAt index 1 the close nonequal neighbor 4 2 1 since 4 2 4 1 index 1 hill at index 2 the close nonequal neighbor 1 4 6 since 1 4 1 6 index 2 valleyAt index 3 the close nonequal neighbor 1 4 6 since 1 4 1 6 index 3 valley note valley index 2at index 4 the close nonequal neighbor 6 1 5 since 6 1 6 5 index 4 hillAt index 5 there nonequal neighbor 5 right index 5 hill valley there 3 hill valley return 3example 2input num 665541output 0explanationat index 0 there nonequal neighbor 6 leave index 0 hill valleyAt index 1 there nonequal neighbor 6 leave index 1 hill valleyAt index 2 the close nonequal neighbor 5 6 4 since 5 6 5 4 index 2 hill valleyAt index 3 the close nonequal neighbor 5 6 4 since 5 6 5 4 index 3 hill valleyAt index 4 the close nonequal neighbor 4 5 1 since 4 5 4 1 index 4 hill valleyAt index 5 there nonequal neighbor 1 right index 5 hill valleythere 0 hill valley return 0 constraints3 numslength 1001 numsi 100
0array
there n car infinitely long road the car number 0 n 1 leave right car present unique pointyou give 0indexed string direction length n directionsi l R S denote ith car move leave right stay current point respectively each move car speedthe number collision calculate followswhen car move opposite direction collide number collision increase 2when move car collide stationary car number collision increase 1after collision car involve long stay point collide other car change state direction motionreturn total number collision happen road example 1input direction RLRSLLOutput 5explanationthe collision happen road car 0 1 collide since move opposite direction number collision 0 2 2 car 2 3 collide since car 3 stationary number collision 2 1 3 car 3 4 collide since car 3 stationary number collision 3 1 4 car 4 5 collide after car 4 collide car 3 stay point collision hit car 5 the number collision 4 1 5thus total number collision happen road 5 example 2input direction LLRROutput 0explanationno car collide thus total number collision happen road 0 Constraints1 directionslength 105directionsi L R S
2string
Alice Bob opponent archery competition the competition set follow rulesAlice shoot numarrow arrow Bob shoot numArrows arrowsthe point calculate followsThe target integer scoring section range 0 11 inclusivefor section target score k 0 11 Alice Bob shoot ak bk arrow section respectively if ak bk Alice take k point if ak bk Bob take k pointshowever ak bk 0 take k pointsfor example Alice Bob shoot 2 arrow section score 11 Alice take 11 point on hand Alice shoot 0 arrow section score 11 Bob shoot 2 arrow section Bob take 11 pointsyou give integer numArrows integer array alicearrow size 12 represent number arrow Alice shoot scoring section 0 11 now Bob wants maximize total number point obtainreturn array bobarrows represent number arrow Bob shoot scoring section 0 11 the sum value bobarrows equal numarrowsif multiple way Bob earn maximum total point return Example 1input numarrow 9 alicearrow 110100210120output 000011001231explanation the table show competition score Bob earn total point 4 5 8 9 10 11 47it show Bob obtain score high 47 pointsExample 2input numarrow 3 alicearrow 001000000002output 000000001110explanation the table show competition scoredBob earn total point 8 9 10 27it show Bob obtain score high 27 point Constraints1 numarrow 105alicearrowslength bobarrowslength 120 aliceArrowsi bobarrowsi numArrowssumaliceArrowsi numArrows
0array
give 0indexed integer array nums1 nums2 return list answer size 2 whereanswer0 list distinct integer nums1 present nums2answer1 list distinct integer nums2 present nums1note integer list return order Example 1input nums1 123 nums2 246output 1346explanationfor nums1 nums11 2 present index 0 nums2 nums10 1 nums12 3 present nums2 therefore answer0 13For nums2 nums20 2 present index 1 nums1 nums21 4 nums22 6 present nums2 therefore answer1 46example 2input nums1 1233 nums2 1122output 3explanationfor nums1 nums12 nums13 present nums2 since nums12 nums13 value include answer0 3every integer nums2 present nums1 therefore answer1 Constraints1 nums1length nums2length 10001000 nums1i nums2i 1000
0array
you give 0indexed integer array num the array num beautiful ifnumslength evennumsi numsi 1 2 0note array consider beautifulyou delete number element num when delete element element right delete element shift unit leave fill gap create element leave delete element remain unchangedreturn minimum number element delete num beautiful Example 1input num 11235output 1explanation you delete nums0 nums1 num 1235 beautiful it prove need 1 deletion num beautifulExample 2input num 112233output 2explanation you delete nums0 nums5 num 1223 beautiful it prove need 2 deletion num beautiful Constraints1 numslength 1050 numsi 105
0array
give integer array query positive integer intlength return array answer answeri queriesith small positive palindrome length intlength 1 palindrome existsA palindrome number read backwards forward palindrome lead zero example 1input query 1234590 intlength 3output 101111121131141999explanationthe palindrome length 3 are101 111 121 131 141 151 161 171 181 191 202 the 90th palindrome length 3 999example 2input query 246 intlength 4output 111113311551explanationthe palindrome length 4 are1001 1111 1221 1331 1441 1551 Constraints1 querieslength 5 1041 queriesi 1091 intlength 15
0array
there n pile coin table each pile consist positive number coin assort denominationsIn choose coin pile remove add walletgiven list pile pilesi list integer denote composition ith pile positive integer k return maximum total value coin wallet choose exactly k coin optimally Example 1input pile 11003789 k 2output 101explanationthe diagram show different way choose k coinsthe maximum total obtain 101example 2input pile 100100100100100100111111700 k 7Output 706explanationthe maximum total obtain choose coin pile Constraintsn pileslength1 n 10001 pilesij 1051 k sumpilesilength 2000
0array
you give 0indexed integer array num numsi digit 0 9 inclusivethe triangular sum num value element present num follow process terminatesLet num comprise n element if n 1 end process otherwise create new 0indexed integer array newnums length n 1for index 0 n 1 assign value newNumsi numsi numsi1 10 denote modulo operatorreplace array num newnumsrepeat entire process start step 1return triangular sum num Example 1input num 12345output 8explanationthe diagram depict process obtain triangular sum arrayExample 2input num 5Output 5ExplanationSince element num triangular sum value element Constraints1 numslength 10000 numsi 9
0array
you give 0indexed binary string s represent type buildings street wheresi 0 denote ith building office andsi 1 denote ith building restaurantAs city official like select 3 building random inspection however ensure variety consecutive building select building typefor example give s 001101 select 1st 3rd 5th building form 011 allow having consecutive building typereturn number valid way select 3 building Example 1input s 001101output 6explanation the follow set index select valid 024 001101 form 010 034 001101 form 010 124 001101 form 010 134 001101 form 010 245 001101 form 101 345 001101 form 101no selection valid thus 6 total waysExample 2input s 11100output 0explanation it show valid selection constraints3 slength 105si 0 1
2string
you give string current correct represent 24hour times24hour time format HHMM HH 00 23 MM 00 59 the early 24hour time 0000 late 2359in operation increase time current 1 5 15 60 minute you perform operation number timesreturn minimum number operation need convert current correct Example 1input current 0230 correct 0435output 3explanationwe convert current correct 3 operation follow add 60 minute current current 0330 add 60 minute current current 0430 Add 5 minute current current 0435it prove possible convert current correct few 3 operationsexample 2input current 1100 correct 1101output 1explanation we add minute current minimum number operation need 1 Constraintscurrent correct format HHMMcurrent correct
2string
you give integer array match matchesi winneri loseri indicate player winneri defeat player loseri matchReturn list answer size 2 whereanswer0 list player lose matchesanswer1 list player lose exactly matchThe value list return increase ordernoteyou consider player play matchThe testcase generate match outcome Example 1input match 1323365657454849104109output 12104578explanationplayer 1 2 10 lose matchesplayer 4 5 7 8 lose matchplayer 3 6 9 lose matchesthus answer0 1210 answer1 4578example 2input match 23135464output 1256explanationplayer 1 2 5 6 lose matchesplayer 3 4 lose matchesthus answer0 1256 answer1 Constraints1 matcheslength 105matchesilength 21 winneri loseri 105winneri loseriAll matchesi unique
0array
you give 0indexed integer array candy each element array denote pile candy size candiesi you divide pile number sub pile merge pile togetheryou give integer k you allocate pile candy k child child get number candy each child pile candy pile candy unusedreturn maximum number candy child Example 1input candy 586 k 3output 5explanation we divide candies1 2 pile size 5 3 candies2 2 pile size 5 1 we pile candy size 5 5 3 5 1 we allocate 3 pile size 5 3 child it prove child receive 5 candiesExample 2input candy 25 k 11output 0explanation there 11 child 7 candy total impossible ensure child receive candy Thus child get candy answer 0 Constraints1 candieslength 1051 candiesi 1071 k 1012
0array
you give 0indexed string expression form num1num2 num1 num2 represent positive integersAdd pair parenthese expression addition parenthese expression valid mathematical expression evaluate small possible value the left parenthesis add leave right parenthesis add right return expression add pair parenthese expression evaluate small possible value if multiple answer yield result return themthe input generate original value expression value expression add pair parenthesis meet requirement fit sign 32bit integer Example 1input expression 24738output 24738explanation the expression evaluate 2 47 38 2 85 170note 24738 invalid right parenthesis right it show 170 small possible valueexample 2input expression 1234output 1234explanation the expression evaluate 1 2 3 4 1 5 4 20example 3input expression 999999output 999999explanation the expression evaluate 999 999 1998 Constraints3 expressionlength 10expression consist digit 1 9 expression start end digitsexpression contain exactly the original value expression value expression add pair parenthesis meet requirement fit sign 32bit integer
2string
you give array nonnegative integer num integer k in operation choose element num increment 1return maximum product num k operation since answer large return modulo 109 7 note maximize product take modulo Example 1input num 04 k 5output 20explanation increment number 5 timesNow num 5 4 product 5 4 20it show 20 maximum product possible return 20note way increment num maximum productExample 2input num 6332 k 2output 216explanation increment second number 1 time increment fourth number 1 timenow num 6 4 3 3 product 6 4 3 3 216it show 216 maximum product possible return 216note way increment num maximum product Constraints1 numslength k 1050 numsi 106
0array
Alice caretaker n garden want plant flower maximize total beauty gardensyou give 0indexed integer array flower size n flowersi number flower plant ith garden Flowers plant remove you give integer newflowers maximum number flower Alice additionally plant you give integer target partialA garden consider complete target flower the total beauty garden determine sum followingthe number complete garden multiply fullThe minimum number flower incomplete garden multiply partial if incomplete garden value 0return maximum total beauty Alice obtain plant newflowers flower Example 1input flower 1311 newFlowers 7 target 6 12 partial 1output 14explanation Alice plant 2 flower 0th garden 3 flower 1st garden 1 flower 2nd garden 1 flower 3rd gardenthe garden 3622 she plant total 2 3 1 1 7 flowersthere 1 garden completethe minimum number flower incomplete garden 2Thus total beauty 1 12 2 1 12 2 14no way planting flower obtain total beauty high 14example 2input flower 2453 newflowers 10 target 5 2 partial 6output 30explanation Alice plant 3 flower 0th garden 0 flower 1st garden 0 flower 2nd garden 2 flower 3rd gardenthe garden 5455 she plant total 3 0 0 2 5 flowersthere 3 garden completethe minimum number flower incomplete garden 4thus total beauty 3 2 4 6 6 24 30no way planting flower obtain total beauty high 30note Alice garden complete case obtain low total beauty Constraints1 flowerslength 1051 flowersi target 1051 newflowers 10101 partial 105
0array
give integer array num size n return number value close 0 num if multiple answer return number large value Example 1input num 42148output 1explanationthe distance 4 0 4 4the distance 2 0 2 2the distance 1 0 1 1the distance 4 0 4 4the distance 8 0 8 8thus close number 0 array 1example 2input num 211output 1explanation 1 1 close number 0 1 large return Constraints1 n 1000105 numsi 105
0array
there ATM machine store banknote 5 denomination 20 50 100 200 500 dollar initially ATM the user use machine deposit withdraw moneywhen withdraw machine prioritize banknote large valuesfor example want withdraw 300 2 50 banknote 1 100 banknote 1 200 banknote machine use 100 200 banknoteshowever try withdraw 600 3 200 banknote 1 500 banknote withdraw request reject machine try use 500 banknote unable use banknote complete remain 100 note machine allow use 200 banknote instead 500 banknoteimplement ATM classATM Initializes ATM objectvoid depositint banknotescount deposit new banknote order 20 50 100 200 500int withdrawint return array length 5 number banknote hand user order 20 50 100 200 500 update number banknote ATM withdraw return 1 possible withdraw banknote case Example 1inputatm deposit withdraw deposit withdraw withdraw 00121 600 01011 600 550Outputnull null 00101 null 1 01001explanationatm atm new atmatmdeposit00121 deposit 1 100 banknote 2 200 banknote 1 500 banknoteatmwithdraw600 return 00101 the machine use 1 100 banknote 1 500 banknote the banknote leave machine 00020atmdeposit01011 deposit 1 50 200 500 banknote the banknote machine 01031atmwithdraw600 return 1 the machine try use 500 banknote unable complete remain 100 withdraw request reject since request reject number banknote machine modifiedatmwithdraw550 return 01001 the machine use 1 50 banknote 1 500 banknote ConstraintsbanknotesCountlength 50 banknotesCounti 1091 109at 5000 call total withdraw depositAt function withdraw deposit
0array
you give string s consist digit integer kA round complete length s great k in round followingdivide s consecutive group size k k characters group k character second group Note size group small kReplace group s string represent sum digit for example 346 replace 13 3 4 6 13merge consecutive group form new string if length string great k repeat step 1return s round complete Example 1input s 11111222223 k 3output 135explanation for round divide s group size 3 111 112 222 23 then calculate digit sum group 1 1 1 3 1 1 2 4 2 2 2 6 2 3 5 so s 3 4 6 5 3465 round for second round divide s 346 5 then calculate digit sum group 3 4 6 13 5 5 so s 13 5 135 second round now slength k return 135 answerexample 2input s 00000000 k 3output 000explanation we divide s 000 000 00then calculate digit sum group 0 0 0 0 0 0 0 0 0 0 0 s 0 0 0 000 length equal k return 000 Constraints1 slength 1002 k 100s consist digit
2string
you give 0indexed integer array task tasksi represent difficulty level task in round complete 2 3 task difficulty levelreturn minimum round require complete task 1 possible complete task Example 1input task 2233244444output 4explanation to complete task possible plan in round complete 3 task difficulty level 2 in second round complete 2 task difficulty level 3 in round complete 3 task difficulty level 4 in fourth round complete 2 task difficulty level 4 it show task complete few 4 round answer 4example 2input task 233output 1explanation there 1 task difficulty level 2 round complete 2 3 task difficulty level hence complete task answer 1 Constraints1 taskslength 1051 tasksi 109
0array
you give 2D integer array grid size m x n cell contain positive integerA cornered path define set adjacent cell turn more specifically path exclusively horizontally vertically turn return previously visit cell after turn path exclusively alternate direction vertically move horizontally vice versa return previously visit cellThe product path define product value pathreturn maximum number trail zero product corner path find gridnotehorizontal movement mean move left right directionvertical movement mean move direction Example 1input grid 231715320812027119462214091106227453output 3explanation the grid leave show valid cornered pathIt product 15 20 6 1 10 18000 3 trail zerosIt show maximum trail zero product corner pathThe grid middle cornered path turnthe grid right cornered path require return previously visit cellexample 2input grid 432761888output 0explanation the grid show figure abovethere corner path grid result product trail zero Constraintsm gridlengthn gridilength1 m n 1051 m n 1051 gridij 1000
0array
give 2D integer array num numsi nonempty array distinct positive integer return list integer present array num sort ascending order Example 1input num 3124512343456output 34explanation the integer present nums0 31245 nums1 1234 nums2 3456 3 4 return 34example 2input num 123456output Explanation there exist integer present nums0 nums1 return list Constraints1 numslength 10001 sumnumsilength 10001 numsij 1000all value numsi unique
0array
give 2D integer array circles circlesi xi yi ri represent center xi yi radius ri ith circle draw grid return number lattice point present inside circlenotea lattice point point integer coordinatespoint lie circumference circle consider inside Example 1input circle 221output 5explanationthe figure show give circlethe lattice point present inside circle 1 2 2 1 2 2 2 3 3 2 show greenother point 1 1 1 3 show red consider inside circlehence number lattice point present inside circle 5example 2Input circle 222341output 16explanationthe figure show give circlesThere exactly 16 lattice point present inside circle some 0 2 2 0 2 4 3 2 4 4 Constraints1 circleslength 200circlesilength 31 xi yi 1001 ri minxi yi
0array
you give 2D integer array rectangle rectanglesi li hi indicate ith rectangle length li height hi you give 2D integer array point pointsj xj yj point coordinate xj yjThe ith rectangle bottomleft corner point coordinate 0 0 topright corner point li hiReturn integer array count length pointslength countj number rectangle contain jth pointThe ith rectangle contain jth point 0 xj li 0 yj hi Note point lie edge rectangle consider contain rectangle example 1input rectangle 122325 point 2114output 21explanation the rectangle contain pointsthe second rectangle contain point 2 1the rectangle contain point 2 1 1 4the number rectangle contain point 2 1 2the number rectangle contain point 1 4 1therefore return 2 1example 2input rectangle 112233 point 1311output 13explanationthe rectangle contain point 1 1the second rectangle contain point 1 1the rectangle contain point 1 3 1 1the number rectangle contain point 1 3 1the number rectangle contain point 1 1 3therefore return 1 3 constraints1 rectangleslength pointslength 5 104rectanglesilength pointsjlength 21 li xj 1091 hi yj 100All rectangle uniqueall point unique
0array
you give 0indexed 2D integer array flower flowersi starti endi mean ith flower bloom starti endi inclusive you give 0indexed integer array person size n personsi time ith person arrive flowersReturn integer array answer size n answeri number flower bloom ith person arrive Example 1input flower 1637912413 person 23711output 1222explanation the figure show time flower bloom people arriveFor person return number flower bloom arrivalexample 2input flower 11033 person 332output 221explanation the figure show time flower bloom people arriveFor person return number flower bloom arrival Constraints1 flowerslength 5 104flowersilength 21 starti endi 1091 personslength 5 1041 personsi 109
0array
you give 0indexed integer array num length nthe average difference index absolute difference average 1 element num average n 1 element both average round near integerReturn index minimum average difference if multiple index return small onenotethe absolute difference number absolute value differenceThe average n element sum n element divide integer division nThe average 0 element consider 0 example 1input num 253953output 3explanation the average difference index 0 2 1 5 3 9 5 3 5 2 1 25 5 2 5 3 the average difference index 1 2 5 2 3 9 5 3 4 7 2 20 4 3 5 2 the average difference index 2 2 5 3 3 9 5 3 3 10 3 17 3 3 5 2 the average difference index 3 2 5 3 9 4 5 3 2 19 4 8 2 4 4 0 the average difference index 4 2 5 3 9 5 5 3 1 24 5 3 1 4 3 1 the average difference index 5 2 5 3 9 5 3 6 0 27 6 0 4 0 4the average difference index 3 minimum average difference return 3example 2input num 0output 0explanationthe index 0 return 0the average difference index 0 0 1 0 0 0 0 constraints1 numslength 1050 numsi 105
0array
you give integer m n represent 0indexed m x n grid you give 2D integer array guard wall guardsi rowi coli wallsj rowj colj represent position ith guard jth wall respectivelyA guard cell cardinal direction north east south west starting position obstruct wall guard a cell guard guard itreturn number unoccupied cell guard Example 1input m 4 n 6 guard 001123 wall 012214output 7explanation the guard unguarded cell show red green respectively diagramthere total 7 unguarded cell return 7example 2Input m 3 n 3 guard 11 wall 01102112output 4explanation the unguarded cell show green diagramthere total 4 unguarded cell return 4 Constraints1 m n 1052 m n 1051 guardslength wallslength 5 1042 guardslength wallslength m nguardsilength wallsjlength 20 rowi rowj m0 coli colj nAll position guard wall unique
0array
you give string number represent positive integer character digitReturn result string remove exactly occurrence digit number value result stre decimal form maximize the test case generate digit occur number example 1input number 123 digit 3output 12explanation there 3 123 after remove 3 result 12example 2input number 1231 digit 1output 231explanation we remove 1 231 remove second 1 123since 231 123 return 231example 3input number 551 digit 5output 51explanation we remove second 5 551both result stre 51 constraints2 numberlength 100number consist digit 1 9digit digit 1 9digit occur number
2string
you give integer array card cardsi represent value ith card a pair card match card valuereturn minimum number consecutive card pick pair matching card pick card if impossible matching card return 1 example 1input card 342347output 4explanation we pick card 3423 contain match pair card value 3 note pick card 4234 optimalExample 2input card 1053output 1explanation there way pick set consecutive card contain pair matching card Constraints1 cardslength 1050 cardsi 106
0array
give integer array nums integer k p return number distinct subarray k element divisible pTwo array nums1 nums2 say distinct ifthey different length orthere exist index nums1i nums2iA subarray define nonempty contiguous sequence element array Example 1input num 23322 k 2 p 2output 11explanationthe element indice 0 3 4 divisible p 2the 11 distinct subarray k 2 element divisible 2 are2 23 233 2332 3 33 332 3322 32 322 22note subarray 2 3 occur num count oncethe subarray 23322 count 3 element divisible 2example 2input num 1234 k 4 p 1Output 10explanationall element num divisible p 1Also subarray num 4 element divisible 1since subarray distinct total number subarray satisfy constraint 10 constraints1 numslength 2001 numsi p 2001 k numslength Follow upcan solve problem on2 time complexity
0array
the appeal string number distinct character find stringfor example appeal abbca 3 3 distinct character b cGiven string s return total appeal substringsa substre contiguous sequence character string Example 1input s abbcaoutput 28explanation the follow substring abbca Substrings length 1 b b c appeal 1 1 1 1 1 respectively the sum 5 Substrings length 2 ab bb bc appeal 2 1 2 2 respectively the sum 7 Substrings length 3 abb bbc bca appeal 2 2 3 respectively the sum 7 Substrings length 4 abbc bbca appeal 3 3 respectively the sum 6 Substrings length 5 abbca appeal 3 the sum 3the total sum 5 7 7 6 3 28example 2input s codeoutput 20explanation the follow substring code Substrings length 1 c o d e appeal 1 1 1 1 respectively the sum 4 Substrings length 2 co od de appeal 2 2 2 respectively the sum 6 Substrings length 3 cod ode appeal 3 3 respectively the sum 6 Substrings length 4 code appeal 4 the sum 4the total sum 4 6 6 4 20 Constraints1 slength 105s consist lowercase english letter
2string
you give stre num represent large integer an integer good meet follow conditionsIt substre num length 3it consist unique digitReturn maximum good integer string string integer existsnotea substre contiguous sequence character stringthere lead zeroes num good integer Example 1input num 6777133339output 777explanation there distinct good integer 777 333777 large return 777example 2input num 2300019output 000explanation 000 good integerExample 3input num 42352338output Explanation no substre length 3 consist unique digit therefore good integer Constraints3 numlength 1000num consist digit
2string
give root binary tree return number node value node equal average value subtreeNoteThe average n element sum n element divide n round near integerA subtree root tree consist root descendant Example 1input root 48501null6output 5explanation for node value 4 the average subtree 4 8 5 0 1 6 6 24 6 4for node value 5 the average subtree 5 6 2 11 2 5for node value 0 the average subtree 0 1 0for node value 1 the average subtree 1 1 1for node value 6 the average subtree 6 1 6example 2input root 1output 1explanation for node value 1 the average subtree 1 1 1 ConstraintsThe number nod tree range 1 10000 Nodeval 1000
1graph
Alice texte Bob phone the mapping digit letter show figure belowIn order add letter Alice press key corresponding digit times position letter keyfor example add letter s Alice press 7 time similarly add letter k Alice press 5 twiceNote digits 0 1 map letter Alice use themhowever error transmission Bob receive alice text message receive string press key insteadfor example Alice send message bob Bob receive string 2266622given string pressedkey represent string receive Bob return total number possible text message Alice sentsince answer large return modulo 109 7 Example 1input pressedkey 22233output 8explanationthe possible text message Alice send areaaadd abdd badd cdd aaae abe bae ceSince 8 possible message return 8example 2input pressedkey 222222222222222222222222222222222222output 82876089explanationthere 2082876103 possible text message Alice sentsince need return answer modulo 109 7 return 2082876103 109 7 82876089 Constraints1 pressedkeyslength 105pressedkey consist digit 2 9
2string
a parenthesis stre nonempty string consist it valid follow condition trueIt it write AB a concatenate B A b valid parenthesis stringsIt write a a valid parenthesis stringYou give m x n matrix parenthese grid a valid parenthesis string path grid path satisfying follow conditionsThe path start upper left cell 0 0the path end bottomright cell m 1 n 1the path move rightthe result parenthesis stre form path validReturn true exist valid parenthesis string path grid otherwise return false example 1input grid output trueexplanation the diagram show possible path form valid parenthesis stringsthe path show result valid parenthesis stre the second path show result valid parenthesis stre note valid parenthesis stre pathsExample 2input grid output falseexplanation the possible path form parenthese string since valid parenthese string return false Constraintsm gridlengthn gridilength1 m n 100gridij
0array
the kbeauty integer num define number substring num read string meet follow conditionsIt length kit divisor numGiven integer num k return kbeauty numNoteLeading zero allowed0 divisor valueA substre contiguous sequence character string Example 1input num 240 k 2output 2explanation the follow substring num length k 24 240 24 divisor 240 40 240 40 divisor 240therefore kbeauty 2example 2input num 430043 k 2output 2explanation the follow substring num length k 43 430043 43 divisor 430043 30 430043 30 divisor 430043 00 430043 0 divisor 430043 04 430043 4 divisor 430043 43 430043 43 divisor 430043therefore kbeauty 2 Constraints1 num 1091 k numlength take num string
2string
you give 0indexed integer array nums length nnum contain valid split index follow truethe sum 1 element greater equal sum n 1 elementsthere element right that 0 n 1return number valid split num Example 1input num 10487output 2explanation there way split num nonempty part Split num index 0 then 10 sum 10 the second 487 sum 3 since 10 3 0 valid split Split num index 1 then 104 sum 14 the second 87 sum 1 since 14 1 1 valid split Split num index 2 then 1048 sum 6 the second 7 sum 7 since 6 7 2 valid splitthu number valid split num 2example 2input num 2310output 2explanation there valid split num Split num index 1 then 23 sum 5 the second 10 sum 1 since 5 1 1 valid split Split num index 2 then 231 sum 6 the second 0 sum 0 since 6 0 2 valid split constraints2 numslength 105105 numsi 105
0array
you give 2D integer array tile tilesi li ri represent tile j range li j ri color whiteYou give integer carpetLen length single carpet place anywhereReturn maximum number white tile cover carpet Example 1input tile 151011121820253032 carpetLen 10output 9explanation Place carpet start tile 10 it cover 9 white tile return 9note place carpet cover 9 white tilesIt show carpet cover 9 white tilesexample 2input tile 101111 carpetLen 2output 2Explanation Place carpet start tile 10 it cover 2 white tile return 2 Constraints1 tileslength 5 104tilesilength 21 li ri 1091 carpetLen 109the tile nonoverlapping
0array
the variance string define large difference number occurrence 2 character present string note character sameGiven string s consist lowercase English letter return large variance possible substring sa substre contiguous sequence character string Example 1input s aababbboutput 3explanationall possible variance respective substring list Variance 0 substring aa ab abab aababb ba b bb bbb Variance 1 substring aab aba abb aabab ababb aababbb bab Variance 2 substring aaba ababbb abbb babb Variance 3 substre babbbsince large possible variance 3 return itExample 2input s abcdeoutput 0explanationno letter occur s variance substre 0 Constraints1 slength 104s consist lowercase english letter
0array