question
stringlengths
58
4.29k
label
class label
3 classes
give array integer num integer threshold choose positive integer divisor divide array sum division result Find small divisor result mention equal thresholdeach result division round near integer great equal element for example 73 3 102 5the test case generate answer Example 1input num 1259 threshold 6output 5explanation we sum 17 1259 divisor 1 if divisor 4 sum 7 1123 divisor 5 sum 5 1112 Example 2input num 442233111 threshold 5Output 44 Constraints1 numslength 5 1041 numsi 106numslength threshold 106
0array
Design CombinationIterator classcombinationiteratorstre character int combinationlength Initializes object string character sort distinct lowercase english letter number combinationlength argumentsnext return combination length combinationlength lexicographical orderhasNext return true exist combination Example 1inputcombinationiterator hasnext hasnext hasNextabc 2 Outputnull ab true ac true bc falseexplanationcombinationiterator itr new CombinationIteratorabc 2itrnext return abitrhasNext return Trueitrnext return acitrhasnext return Trueitrnext return bcitrhasnext return false Constraints1 combinationlength characterslength 15all character character uniqueAt 104 call hasNextIt guarantee call function valid
2string
give integer array sort nondecrease order exactly integer array occur 25 time return integer Example 1Input arr 1226666710output 6Example 2Input arr 11output 1 Constraints1 arrlength 1040 arri 105
0array
give array intervals intervalsi li ri represent interval li ri remove interval cover interval listthe interval b cover interval c d c b dreturn number remain interval Example 1input interval 143628output 2explanation interval 36 cover 28 removedExample 2input interval 1423output 1 Constraints1 intervalslength 1000intervalsilength 20 li ri 105All give interval unique
0array
give n x n integer matrix grid return minimum sum fall path nonzero shiftsA fall path nonzero shift choice exactly element row grid element choose adjacent row column Example 1input arr 123456789output 13explanation the possible fall path are159 157 167 168248 249 267 268348 349 357 359the fall path smallest sum 157 answer 13example 2input grid 7output 7 Constraintsn gridlength gridilength1 n 20099 gridij 99
0array
give m x n matrix mat integer threshold return maximum sidelength square sum equal threshold return 0 square Example 1input mat 113243211324321132432 threshold 4Output 2explanation the maximum length square sum 4 2 shownexample 2input mat 2222222222222222222222222 threshold 1output 0 Constraintsm matlengthn matilength1 m n 3000 matij 1040 threshold 105
0array
give array num integer return contain number digit Example 1input num 12345267896output 2explanation 12 contain 2 digit number digits 345 contain 3 digit odd number digits 2 contain 1 digit odd number digits 6 contain 1 digit odd number digit 7896 contain 4 digit number digit therefore 12 7896 contain number digitsexample 2input num 5559014821771output 1 Explanation only 1771 contain number digits Constraints1 numslength 5001 numsi 105
0array
give array integer num positive integer k check possible divide array set k consecutive numbersreturn true possible Otherwise return false Example 1input num 12334456 k 4Output trueExplanation Array divide 1234 3456example 2input num 32123434591011 k 3output trueExplanation Array divide 123 234 345 91011example 3input num 1234 k 3output falseexplanation each array divide subarray size 3 Constraints1 k numslength 1051 numsi 109 note this question 846 httpsleetcodecomproblemshandofstraight
0array
give string s return maximum number ocurrence substring follow rulesThe number unique character substre equal maxlettersthe substring size minSize maxsize inclusive Example 1input s aababcaab maxletter 2 minSize 3 maxsize 4output 2explanation Substring aab 2 ocurrence original stringit satisfie condition 2 unique letter size 3 minSize maxsizeexample 2input s aaaa maxletters 1 minSize 3 maxsize 3output 2explanation Substring aaa occur 2 time stre it overlap Constraints1 slength 1051 maxletters 261 minSize maxsize min26 slength consist lowercase english letter
2string
give array arr replace element array great element element right replace element 1After return array Example 1input arr 17185461output 1866611explanation index 0 great element right index 0 index 1 18 index 1 great element right index 1 index 4 6 index 2 great element right index 2 index 4 6 index 3 great element right index 3 index 4 6 index 4 great element right index 4 index 5 1 index 5 element right index 5 1example 2input arr 400output 1explanation there element right index 0 Constraints1 arrlength 1041 arri 105
0array
give integer array arr target value target return integer value change integer large value give array equal value sum array get close possible absolute difference targetin case tie return minimum integerNotice answer neccesarilly number arr Example 1input arr 493 target 10output 3explanation when 3 arr convert 3 3 3 sum 9 that s optimal answerexample 2input arr 235 target 10output 5Example 3Input arr 6086425176272492129620204 target 56803output 11361 Constraints1 arrlength 1041 arri target 105
0array
you give square board character you board start right square marked character syou need reach leave square marked character e the rest square label numeric character 1 2 9 obstacle x in leave upleft diagonally obstacle therereturn list integer integer maximum sum numeric character collect second number path maximum sum take modulo 109 7In case path return 0 0 example 1input board e232x212soutput 71Example 2Input board e121x121soutput 42example 3input board e11xxx11soutput 00 constraints2 boardlength boardilength 100
0array
give root binary tree return sum value deep leave Example 1input root 12345null67nullnullnullnull8output 15example 2input root 67827139null14nullnullnull5output 19 ConstraintsThe number nod tree range 1 1041 Nodeval 100
1graph
give integer n return array contain n unique integer add 0 example 1input n 5output 71134explanation these array accept 51123 31224example 2input n 3Output 101example 3input n 1output 0 Constraints1 n 1000
0array
give binary search tree root1 root2 return list contain integer tree sort ascending order Example 1input root1 214 root2 103output 011234example 2input root1 1null8 root2 81output 1188 ConstraintsThe number nod tree range 0 5000105 Nodeval 105
1graph
you give string s form digit we want map s english lowercase character followscharacter represent 1 9 respectivelycharacter j z represent 10 26 respectivelyreturn string form mappingThe test case generate unique mapping exist Example 1input s 101112output jkabexplanation j 10 k 11 1 b 2example 2input s 1326output acz Constraints1 slength 1000 consist digits letter valid string mapping possible
2string
you give array arr positive integer you give array query queriesi lefti rightiFor query compute XOR element lefti righti arrlefti XOR arrlefti 1 XOR XOR arrrighti Return array answer answeri answer ith query Example 1input arr 1348 query 01120333output 27148 Explanation the binary representation element array are1 0001 3 0011 4 0100 8 1000 the XOR value query are01 1 xor 3 2 12 3 xor 4 7 03 1 xor 3 xor 4 xor 8 14 33 8example 2Input arr 48210 query 23130003output 8044 Constraints1 arrlength querieslength 3 1041 arri 109queriesilength 20 lefti righti arrlength
0array
give string s in step insert character index stringreturn minimum number step s palindromeA Palindrome String read backward forward Example 1input s zzazzoutput 0explanation the string zzazz palindrome need insertionsexample 2input s mbadmoutput 2explanation String mbdadbm mdbabdmExample 3input s leetcodeoutput 5explanation insert 5 character string leetcodocteel Constraints1 slength 500s consist lowercase english letter
2string
we give list num integer represent list compress runlength encodingConsider adjacent pair element freq val nums2i nums2i1 0 for pair freq element value val concatenate sublist Concatenate sublist leave right generate decompress listReturn decompress list Example 1input num 1234output 2444explanation the pair 12 mean freq 1 val 2 generate array 2the second pair 34 mean freq 3 val 4 generate 444at end concatenation 2 444 2444example 2input num 1123output 133 constraints2 numslength 100numslength 2 01 numsi 100
0array
give m x n matrix mat integer k return matrix answer answerij sum element matrc fori k r kj k c j k andr c valid position matrix Example 1input mat 123456789 k 1Output 122116274533243928example 2input mat 123456789 k 2output 454545454545454545 Constraintsm matlengthn matilength1 m n k 1001 matij 100
0array
give root binary tree return sum value node evenvalue grandparent if node evenvalue grandparent return 0A grandparent node parent parent exist Example 1input root 67827139null14nullnullnull5output 18explanation the red node nod evenvalue grandparent blue node evenvalue grandparentsExample 2input root 1output 0 ConstraintsThe number nod tree range 1 1041 Nodeval 100
1graph
return number distinct nonempty substring text write concatenation string ie write string example 1input text abcabcabcOutput 3explanation the 3 substring abcabc bcabca cabcabExample 2input text leetcodeleetcodeoutput 2explanation the 2 substring ee leetcodeleetcode Constraints1 textlength 2000text lowercase english letter
2string
there n computer number 0 n 1 connect ethernet cable connection form network connectionsi ai bi represent connection computer ai bi any computer reach computer directly indirectly networkyou give initial computer network connection you extract certain cable directly connect computer place pair disconnected computer directly connectedreturn minimum number time need order computer connect if possible return 1 Example 1input n 4 connection 010212output 1explanation Remove cable computer 1 2 place computer 1 3example 2input n 6 connection 0102031213output 2example 3input n 6 connection 01020312output 1explanation there cable Constraints1 n 1051 connectionslength minn n 1 2 105connectionsilength 20 ai bi nai biThere repeat connectionsno computer connect cable
1graph
you keyboard layout show XY plane English uppercase letter locate coordinatefor example letter a locate coordinate 0 0 letter b locate coordinate 0 1 letter p locate coordinate 2 3 letter Z located coordinate 4 1given string word return minimum total distance type string fingersThe distance coordinate x1 y1 x2 y2 x1 x2 y1 y2Note initial position finger consider free count total distance finger start letter letter Example 1input word CAKEOutput 3explanation use finger optimal way type cake Finger 1 letter C cost 0 finger 1 letter a cost distance letter c letter a 2 finger 2 letter K cost 0 Finger 2 letter e cost Distance letter K letter e 1 total distance 3example 2input word HAPPYOutput 6explanation use finger optimal way type HAPPY isfinger 1 letter H cost 0finger 1 letter a cost distance letter h letter a 2finger 2 letter p cost 0finger 2 letter p cost Distance letter p letter p 0finger 1 letter Y cost distance letter a letter Y 4total distance 6 constraints2 wordlength 300word consist uppercase english letter
2string
give binary tree root integer target delete leaf node value targetnote delete leaf node value target parent node leaf node value target delete need continue Example 1input root 1232null24 target 2output 1null3null4explanation Leaf nod green value target 2 remove Picture leave after remove new node leaf node value target 2 picture centerExample 2input root 13332 target 3output 13nullnull2example 3input root 12null2null2 target 2output 1explanation Leaf nod green value target 2 remove step ConstraintsThe number nod tree range 1 30001 Nodeval target 1000
1graph
there onedimensional garden xaxis the garden start point 0 end point n ie the length garden nThere n 1 tap locate point 0 1 n gardengiven integer n integer array range length n 1 rangesi 0indexed mean ith tap water area rangesi rangesi openReturn minimum number tap open water garden if garden water return 1 Example 1input n 5 range 341100output 1explanation the tap point 0 cover interval 33the tap point 1 cover interval 35The tap point 2 cover interval 13the tap point 3 cover interval 24the tap point 4 cover interval 44the tap point 5 cover interval 55opene only second tap water garden 05Example 2input n 3 range 0000output 1explanation even activate tap water garden Constraints1 n 104rangeslength n 10 rangesi 100
0array
give palindromic string lowercase English letter palindrome replace exactly character lowercase english letter result string palindrome lexicographically smallest possiblereturn result string if way replace character palindrome return stringA stre lexicographically small string b length position b differ character strictly small corresponding character b for example abcc lexicographically small abcd position differ fourth character c small d example 1input palindrome abccbaoutput aaccbaexplanation there way abccba palindrome zbccba aaccba abacbaOf way aaccba lexicographically smallestExample 2input palindrome aOutput Explanation there way replace single character palindrome return stre Constraints1 palindromelength 1000palindrome consist lowercase english letter
2string
a matrix diagonal diagonal line cell start cell topmost row leftmost column go bottomright direction reach matrixs end for example matrix diagonal start mat20 mat 6 x 3 matrix include cell mat20 mat31 mat42Given m x n matrix mat integer sort matrix diagonal ascending order return result matrix Example 1input mat 331122121112output 111112221233example 2input mat 1125661697235517451552753136445882227332568484281411550output 5174152711112545869142325445815222731365066842875335568 Constraintsm matlengthn matilength1 m n 1001 matij 100
0array
you give integer array num the value array define sum numsi numsi 1 0 numslength 1you allow select subarray give array reverse you perform operation oncefind maximum possible value final array Example 1input num 23154output 10explanation by reverse subarray 315 array 25134 value 10example 2input num 249242110output 68 constraints1 numslength 3 104105 numsi 105
0array
give array integer arr replace element rankthe rank represent large element the rank follow rulesrank integer start 1the large element large rank if element equal rank sameRank small possible Example 1input arr 40102030output 4123explanation 40 large element 10 small 20 second small 30 smallestexample 2input arr 100100100output 111explanation same element share rankexample 3input arr 37122891005680512output 534286713 constraints0 arrlength 105109 arri 109
0array
you give string s consist letter b in single step remove palindromic subsequence sReturn minimum number step give string emptyA string subsequence give string generate delete character give string change order note subsequence necessarily need contiguousA string call palindrome read backward forward Example 1input s ababaoutput 1explanation s palindrome entirety remove single stepexample 2input s abboutput 2explanation abb bb Remove palindromic subsequence bbExample 3input s baabboutput 2explanation baabb b remove palindromic subsequence baab b Constraints1 slength 1000si b
2string
give array restaurant restaurantsi idi ratingi veganFriendlyi pricei distancei you filter restaurant filtersthe veganfriendly filter true meaning include restaurant veganFriendlyi set true false meaning include restaurant in addition filter maxprice maxdistance maximum value price distance restaurant consider respectivelyReturn array restaurant id filtering order rating highest low for restaurant rating order i d high low for simplicity veganFriendlyi veganfriendly value 1 true 0 false example 1input restaurant 14140102805053813044100103511151 veganfriendly 1 maxprice 50 maxdistance 10output 315 Explanation the restaurant arerestaurant 1 id1 rating4 veganfriendly1 price40 distance10restaurant 2 id2 rating8 veganfriendly0 price50 distance5Restaurant 3 id3 rating8 veganfriendly1 price30 distance4restaurant 4 id4 rating10 veganfriendly0 price10 distance3Restaurant 5 id5 rating1 veganfriendly1 price15 distance1 after filter restaurant veganfriendly 1 maxprice 50 maxdistance 10 restaurant 3 restaurant 1 restaurant 5 order rating highest low Example 2input restaurant 14140102805053813044100103511151 veganfriendly 0 maxprice 50 maxdistance 10output 43215explanation the restaurant example 1 case filter veganfriendly 0 restaurant consideredexample 3input restaurant 14140102805053813044100103511151 veganfriendly 0 maxprice 30 maxdistance 3output 45 Constraints1 restaurantslength 104restaurantsilength 51 idi ratingi pricei distancei 1051 maxprice maxdistance 105veganfriendlyi veganfriendly 0 1all idi distinct
0array
there n city number 0 n1 give array edge edgesi fromi toi weighti represent bidirectional weighted edge city fromi toi give integ distancethresholdreturn city small number city reachable path distance distancethreshold if multiple city return city great numberNotice distance path connect city j equal sum edge weight path Example 1input n 4 edge 013121134231 distancethreshold 4output 3explanation the figure describe graph the neighboring city distancethreshold 4 city arecity 0 city 1 City 2 City 1 City 0 City 2 City 3 City 2 City 0 City 1 City 3 City 3 City 1 City 2 Cities 0 3 2 neighboring city distancethreshold 4 return city 3 great numberExample 2input n 5 edge 012048123142231341 distancethreshold 2output 0explanation the figure describe graph the neighboring city distancethreshold 2 city arecity 0 city 1 City 1 City 0 City 4 City 2 City 3 City 4 City 3 City 2 City 4city 4 City 1 City 2 city 3 the city 0 1 neighboring city distancethreshold 2 constraints2 n 1001 edgeslength n n 1 2edgesilength 30 fromi toi n1 weighti distancethreshold 104all pair fromi toi distinct
1graph
you want schedule list job d day job dependent ie to work ith job finish job j 0 j iYou finish task day the difficulty job schedule sum difficulty day d day the difficulty day maximum difficulty job dayyou give integer array jobDifficulty integer d the difficulty ith job jobDifficultyiReturn minimum difficulty job schedule if find schedule job return 1 Example 1input jobdifficulty 654321 d 2output 7explanation First day finish 5 job total difficulty 6Second day finish job total difficulty 1the difficulty schedule 6 1 7 Example 2input jobdifficulty 999 d 4Output 1explanation if finish job day free day find schedule give jobsExample 3input jobDifficulty 111 d 3output 3explanation the schedule job day total difficulty 3 Constraints1 jobdifficultylength 3000 jobDifficultyi 10001 d 10
0array
you give m x n binary matrix mat 1s represent soldier 0s represent civilian the soldier position civilian that 1s appear leave 0s rowa row weak row j follow truethe number soldier row number soldier row jBoth row number soldier jReturn indice k weak row matrix order weakest strong Example 1input mat 11000 11110 10000 11000 11111 k 3output 203explanation the number soldier row row 0 2 row 1 4 row 2 1 row 3 2 row 4 5 the row order weakest strong 20314example 2input mat 1000 1111 1000 1000 k 2output 02explanation the number soldier row row 0 1 row 1 4 row 2 1 row 3 1 the row order weakest strong 0231 Constraintsm matlengthn matilength2 n m 1001 k mmatrixij 0 1
0array
you give integer array arr you choose set integer remove occurrence integer arrayreturn minimum size set half integer array remove Example 1input arr 3333555227output 2explanation choose 37 new array 55522 size 5 ie equal half size old arraypossible set size 2 353252choosing set 27 possible new array 3333555 size great half size old arrayExample 2Input arr 777777output 1explanation the possible set choose 7 this new array Constraints2 arrlength 105arrlength even1 arri 105
0array
give root binary tree split binary tree subtree remove edge product sum subtree maximizedreturn maximum product sum subtree since answer large return modulo 109 7note need maximize answer take mod take Example 1input root 123456output 110explanation Remove red edge 2 binary tree sum 11 10 their product 110 1110example 2input root 1null234nullnull56output 90explanation Remove red edge 2 binary tree sum 15 6their product 90 156 ConstraintsThe number nod tree range 2 5 1041 Nodeval 104
1graph
give array integer arr integer d in step jump index indexi x x arrlength 0 x di x x 0 0 x din addition jump index index j arri arrj arri arrk indice k j more formally mini j k maxi jYou choose index array start jump Return maximum number index visitNotice jump outside array time Example 1Input arr 641468139710612 d 2output 4explanation you start index 10 you jump 10 8 6 7 shownnote start index 6 jump index 7 you jump index 5 13 9 you jump index 4 index 5 index 4 6 13 9similarly you jump index 3 index 2 index 1Example 2Input arr 33333 d 3output 1explanation you start index you jump indexExample 3Input arr 7654321 d 1output 7Explanation Start index 0 you visit indicie Constraints1 arrlength 10001 arri 1051 d arrlength
0array
give array integer arr integers k threshold return number subarray size k average great equal threshold Example 1input arr 22225558 k 3 threshold 4Output 3explanation Subarrays 255555 558 average 4 5 6 respectively all subarray size 3 average 4 thresholdexample 2Input arr 1113172329317523 k 3 threshold 5output 6explanation the 6 subarray size 3 average great 5 note average integer Constraints1 arrlength 1051 arri 1041 k arrlength0 threshold 104
0array
give array arr integer check exist index j j0 j arrlengtharri 2 arrj Example 1input arr 10253output trueexplanation for 0 j 2 arri 10 2 5 2 arrjexample 2input arr 31711output falseexplanation there j satisfy condition constraints2 arrlength 500103 arri 103
0array
you give string length s t in step choose character t replace characterreturn minimum number step t anagram sAn Anagram string string contain character different order Example 1input s bab t abaoutput 1explanation Replace t b t bba anagram sExample 2Input s leetcode t practiceoutput 5explanation replace p r c t proper character t anagram sExample 3Input s anagram t mangaarOutput 0explanation anagram mangaar anagram Constraints1 slength 5 104slength tlength t consist lowercase english letter
2string
give m n matrix seat represent seat distribution classroom if seat break denote character denote characterstudents answer sit leave right upper left upper right answer student sit directly return maximum number student exam cheat possiblestudent place seat good condition example 1input seat output 4explanation teacher place 4 student available seat do not cheat exam example 2input seat Output 3explanation Place student available seat Example 3input seat Output 10explanation Place student available seat column 1 3 5 Constraintsseats contain character andm seatslengthn seatsilength1 m 81 n 8
0array
give m x n matrix grid sort nonincrease order rowwise columnwise return number negative number grid Example 1input grid 4321321111121123output 8explanation there 8 negative number matrixexample 2input grid 3210output 0 Constraintsm gridlengthn gridilength1 m n 100100 gridij 100 follow could find on m solution
0array
design algorithm accept stream integer retrieve product k integer streamimplement productofnumber classproductofnumber Initializes object streamvoid addint num Appends integer num streamint getproductint k Returns product k number current list you assume current list k numbersthe test case generate time product contiguous sequence number fit single 32bit integer overflowing exampleinputproductofnumbersaddaddaddaddaddgetproductgetproductgetproductaddgetproduct3025423482outputnullnullnullnullnullnull20400null32explanationproductofnumber productofnumber new productofnumbersproductofnumbersadd3 3productOfNumbersadd0 30productofnumbersadd2 302productOfNumbersadd5 3025productOfNumbersadd4 30254productofnumbersgetproduct2 return 20 the product 2 number 5 4 20productofnumbersgetproduct3 return 40 the product 3 number 2 5 4 40productofnumbersgetproduct4 return 0 the product 4 number 0 2 5 4 0productofnumbersadd8 302548productofnumbersgetproduct2 return 32 the product 2 number 4 8 32 constraints0 num 1001 k 4 104at 4 104 call add getproductthe product stream point time fit 32bit integer
0array
you give array event eventsi startdayi enddayi every event start startdayi end enddayiyou attend event day d startTimei d endTimei you attend event time dReturn maximum number event attend Example 1input event 122334output 3explanation you attend eventsone way attend shownattend event day 1attend second event day 2attend event day 3example 2input event 12233412output 4 Constraints1 eventslength 105eventsilength 21 startdayi enddayi 105
0array
you give array target n integer from start array arr consist n 1s perform follow procedure let x sum element currently arraychoose index 0 n set value arr index xYou repeat procedure time neededreturn true possible construct target array arr return false Example 1input target 935output trueexplanation Start arr 1 1 1 1 1 1 sum 3 choose index 11 3 1 sum 5 choose index 21 3 5 sum 9 choose index 09 3 5 DoneExample 2input target 1112output falseexplanation impossible create target array 1111example 3input target 85output true Constraintsn targetlength1 n 5 1041 targeti 109
0array
you give integer array arr Sort integer array ascend order number 1s binary representation case integer number 1s sort ascend orderreturn array sort Example 1input arr 012345678output 012483567explantion 0 integer 0 bits1248 1 bit356 2 bits7 3 bitsThe sorted array bit 012483567example 2input arr 10245122561286432168421output 12481632641282565121024explantion all integer 1 bit binary representation sort ascend order Constraints1 arrlength 5000 arri 104
0array
there supermarket frequent customer the product sell supermarket represent parallel integer array product price ith product ID productsi price pricesiWhen customer pay bill represent parallel integer array product jth product purchase ID productj amountj product buy their subtotal calculate sum amountj price jth productThe supermarket decide sale every nth customer pay grocery give percentage discount the discount give discount give discount percent subtotal more formally subtotal bill actually pay bill 100 discount 100implement Cashier classcashierint n int discount int product int price Initializes object n discount product pricesdouble getbillint product int return final total bill discount apply Answers 105 actual value accept Example 1inputcashiergetbillgetbillgetbillgetbillgetbillgetbillgetbill350123456710020030040030020010012123710101234567111111141073101075316421010109997235532outputnull500040000800040000400007350025000explanationcashier cashier new Cashier3501234567100200300400300200100cashiergetBill1212 return 5000 1st customer discount bill 1 100 2 200 500cashiergetbill371010 return 40000 2nd customer discount bill 10 300 10 100 4000cashiergetbill12345671111111 return 8000 3rd customer 50 discount original bill 1600 actual bill 1600 100 50 100 800cashiergetbill410 return 40000 4th customer discountcashiergetbill731010 return 40000 5th customer discountcashiergetbill75316421010109997 return 73500 6th customer 50 discount original bill 14700 actual bill 14700 100 50 100 7350cashiergetbill235532 return 25000 6th customer discount Constraints1 n 1040 discount 1001 productslength 200priceslength productslength1 productsi 2001 pricesi 1000The element product unique1 productlength productslengthamountlength productlengthproductj exist products1 amountj 1000The element product uniqueAt 1000 call getBillAnswers 105 actual value accept
0array
give string s consist character b cReturn number substring contain occurrence character b c Example 1input s abcabcoutput 10explanation the substring contain occurrence character b c abc abca abcab abcabc bca bcab bcabc cab cabc abc Example 2Input s aaacboutput 3explanation the substring contain occurrence character b c aaacb aacb acb Example 3input s abcoutput 1 constraints3 slength 5 x 104s consist b c character
2string
write program count number day datesthe date give string format YYYYMMDD show example example 1input date1 20190629 date2 20190630output 1example 2input date1 20200115 date2 20191231output 15 ConstraintsThe give date valid date year 1971 2100
2string
you n binary tree node number 0 n 1 node child leftChildi rightChildi return true give node form exactly valid binary treeif node leave child leftchildi equal 1 similarly right childnote node value use node number problem Example 1input n 4 leftchild 1131 rightchild 2111output trueExample 2input n 4 leftchild 1131 rightchild 2311output falseexample 3input n 2 leftchild 10 rightchild 11output false Constraintsn leftchildlength rightchildlength1 n 1041 leftchildi rightchildi n 1
1graph
give array digit digit return large multiple form concatenate give digit order if answer return stringsince answer fit integer datum type return answer string note return answer contain unnecessary lead zero example 1input digit 819output 981example 2input digit 86710output 8760example 3input digit 1output Constraints1 digitslength 1040 digitsi 9
0array
give array num numsi find number array small that numsi count number valid js j numsj numsiReturn answer array Example 1input num 81223output 40113explanation for nums08 exist small number 1 2 2 3 for nums11 exist small number itFor nums22 exist small number 1 for nums32 exist small number 1 for nums43 exist small number 1 2 2example 2input num 6548output 2103example 3input num 7777output 0000 constraints2 numslength 5000 numsi 100
0array
give binary tree root link list head node Return true element link list start head correspond downward path connect binary tree return FalseIn context downward path mean path start node go downwards Example 1input head 428 root 144null22null1null68nullnullnullnull13output trueExplanation Nodes blue form subpath binary Tree Example 2input head 1426 root 144null22null1null68nullnullnullnull13output trueExample 3input head 14268 root 144null22null1null68nullnullnullnull13output falseexplanation there path binary tree contain element link list head ConstraintsThe number nod tree range 1 2500the number node list range 1 1001 Nodeval 100 node link list binary tree
1graph
you give stre s reorder string follow algorithmpick small character s append resultpick small character s great appended character result append itrepeat step 2 pick characterspick large character s append resultpick large character s small appended character result append itrepeat step 5 pick charactersrepeat step 1 6 pick character sin step if small large character appear choose occurrence append resultreturn result string sort s algorithm Example 1input s aaaabbbbccccoutput abccbaabccbaexplanation after step 1 2 3 iteration result abcafter step 4 5 6 iteration result abccbafirst iteration now s aabbcc step 1after step 1 2 3 second iteration result abccbaabcafter step 4 5 6 second iteration result abccbaabccbaexample 2input s ratoutput artexplanation the word rat art reorder mention algorithm Constraints1 slength 500s consist lowercase english letter
2string
give string s return size long substre contain vowel number time that e o u appear number times Example 1input s eleetminicoworoepoutput 13explanation the long substring leetminicowor contain vowel e o zero vowel uExample 2input s leetcodeisgreatoutput 5explanation the long substring leetc contain esExample 3input s bcbcbcoutput 6explanation in case give string bcbcbc long vowel e o u appear zero time Constraints1 slength 5 x 105s contain lowercase english letter
2string
you give root binary treeA ZigZag path binary tree define followchoose node binary tree direction right leftIf current direction right right child current node leave childChange direction right left leave rightrepeat second step can not treezigzag length define number node visit 1 a single node length 0return long ZigZag path contain tree Example 1input root 1null111nullnull11null1nullnullnull1null1output 3explanation Longest ZigZag path blue node right leave rightexample 2input root 111null1nullnull11null1output 4explanation Longest ZigZag path blue node leave right leave rightexample 3input root 1output 0 ConstraintsThe number nod tree range 1 5 1041 Nodeval 100
1graph
give binary tree root return maximum sum key subtree Binary Search Tree bstassume BST define followsthe leave subtree node contain node key node keythe right subtree node contain nod key great node keyBoth leave right subtree binary search tree Example 1input root 1432425nullnullnullnullnullnull46output 20explanation maximum sum valid Binary search tree obtain root node key equal 3example 2input root 43null12output 2explanation maximum sum valid Binary search tree obtain single root node key equal 2example 3input root 425output 0explanation all value negative return BST ConstraintsThe number nod tree range 1 4 1044 104 Nodeval 4 104
1graph
give integer n return string n character character string occur odd number timesthe return string contain lowercase english letter if multiple valid string return Example 1input n 4output pppzExplanation pppz valid string character p occur time character z occur note valid string ohhh loveExample 2input n 2output xyexplanation xy valid string character x y occur note valid string ag urExample 3Input n 7Output holasss Constraints1 n 500
2string
you 1indexed binary string length n bit 0 initially we flip bit binary string ie change 0 1 you give 1indexed integer array flip flipsi indicate bit index flip ith stepA binary string prefixaligne ith step bits inclusive range 1 one bit zerosreturn number time binary string prefixaligne flipping process Example 1input flip 32415output 2explanation the binary string initially 00000after apply step 1 the string 00100 prefixalignedafter apply step 2 the string 01100 prefixalignedafter apply step 3 the string 01110 prefixalignedafter apply step 4 the string 11110 prefixalignedafter apply step 5 the string 11111 prefixalignedwe string prefixaligne 2 time return 2example 2input flip 4123output 1explanation the binary string initially 0000after apply step 1 the string 0001 prefixalignedafter apply step 2 the string 1001 prefixalignedafter apply step 3 the string 1101 prefixalignedafter apply step 4 the string 1111 prefixalignedwe string prefixaligne 1 time return 1 Constraintsn flipslength1 n 5 104flips permutation integer range 1 n
0array
a company n employee unique ID employee 0 n 1 the head company headIDEach employee direct manager give manager array manageri direct manager ith employee managerheadID 1 also guarantee subordination relationship tree structureThe head company wants inform company employee urgent piece news he inform direct subordinate inform subordinate employee know urgent newsThe ith employee need informTimei minute inform direct subordinate ie after informTimei minute direct subordinate start spread newsreturn number minute need inform employee urgent news Example 1input n 1 headid 0 manager 1 informtime 0output 0explanation the head company employee companyexample 2input n 6 headid 2 manager 221222 informtime 001000output 1explanation the head company i d 2 direct manager employee company need 1 minute inform allthe tree structure employee company show Constraints1 n 1050 headID nmanagerlength n0 manageri nmanagerheadID 1informtimelength n0 informTimei 1000informtimei 0 employee subordinatesIt guarantee employee inform
1graph
give undirected tree consist n vertex number 1 n a frog start jump vertex 1 in second frog jump current vertex unvisited vertex directly connect the frog jump visit vertex in case frog jump vertex jump randomly probability otherwise frog jump unvisited vertex jump forever vertexthe edge undirected tree give array edge edgesi ai bi mean exist edge connect vertex ai biReturn probability t second frog vertex target Answers 105 actual answer accept Example 1input n 7 edge 121317242635 t 2 target 4Output 016666666666666666 Explanation the figure show give graph the frog start vertex 1 jump 13 probability vertex 2 second 1 jump 12 probability vertex 4 second 2 thus probability frog vertex 4 2 second 13 12 16 016666666666666666 Example 2input n 7 edge 121317242635 t 1 target 7output 03333333333333333explanation the figure show give graph the frog start vertex 1 jump 13 03333333333333333 probability vertex 7 second 1 Constraints1 n 100edgeslength n 1edgesilength 21 ai bi n1 t 501 target n
1graph
give binary tree original clone give reference node target original treethe cloned tree copy original treeReturn reference node clone treenote allow change tree target node answer reference node clone tree Example 1input tree 743nullnull619 target 3output 3explanation in example original cloned tree show the target node green node original tree the answer yellow node clone treeExample 2input tree 7 target 7Output 7Example 3input tree 8null6null5null4null3null2null1 target 4Output 4 ConstraintsThe number nod tree range 1 104the value nod tree uniquetarget node node original tree null Follow could solve problem repeat value tree allow
1graph
give m x n matrix distinct number return lucky number matrix ordera lucky number element matrix minimum element row maximum column example 1input matrix 37891113151617output 15explanation 15 lucky number minimum row maximum columnexample 2input matrix 11042938715161712output 12Explanation 12 lucky number minimum row maximum columnexample 3input matrix 7812Output 7Explanation 7 lucky number minimum row maximum column Constraintsm matlengthn matilength1 n m 501 matrixij 105All element matrix distinct
0array
design stack support follow operationsimplement CustomStack classcustomstackint maxsize Initializes object maxsize maximum number element stack stack reach maxsizevoid pushint x Adds x stack stack have not reach maxsizeint pop Pops return stack 1 stack emptyvoid incint k int val Increments k element stack val if k element stack increment element stack Example 1inputcustomstackpushpushpoppushpushpushincrementincrementpoppoppoppop31223451002100outputnullnullnull2nullnullnullnullnull1032022011explanationcustomstack customstack new CustomStack3 Stack Empty customstackpush1 stack 1customstackpush2 stack 1 2customstackpop return 2 return stack 2 stack 1customstackpush2 stack 1 2customstackpush3 stack 1 2 3customstackpush4 stack 1 2 3 do not add element size 4customstackincrement5 100 stack 101 102 103customstackincrement2 100 stack 201 202 103customstackpop return 103 Return stack 103 stack 201 202customstackpop return 202 return stack 102 stack 201customstackpop return 201 Return stack 101 stack customstackpop return 1 Stack return 1 Constraints1 maxSize 10001 x 10001 k 10000 val 100at 1000 call method increment push pop separately
0array
give root binary search tree return balanced binary search tree node value if answer return themA binary search tree balanced depth subtree node differ 1 Example 1input root 1null2null3null4nullnulloutput 213nullnullnull4explanation this correct answer 314null2 correctExample 2input root 213output 213 ConstraintsThe number nod tree range 1 1041 Nodeval 105
1graph
you give integer n k integer array speed efficiency length n there n engineer number 1 n speedi efficiencyi represent speed efficiency ith engineer respectivelyChoose k different engineer n engineer form team maximum performanceThe performance team sum engineer speed multiplied minimum efficiency engineersreturn maximum performance team since answer huge number return modulo 109 7 Example 1input n 6 speed 2103158 efficiency 543972 k 2output 60explanation we maximum performance team select engineer 2 speed10 efficiency4 engineer 5 speed5 efficiency7 that performance 10 5 min4 7 60example 2input n 6 speed 2103158 efficiency 543972 k 3output 68explanationthis example k 3 we select engineer 1 engineer 2 engineer 5 maximum performance team that performance 2 10 5 min5 4 7 68example 3input n 6 speed 2103158 efficiency 543972 k 4Output 72 Constraints1 k n 105speedlength nefficiencylength n1 speedi 1051 efficiencyi 108
0array
give integer array arr1 arr2 integer d return distance value arraysthe distance value define number element arr1i element arr2j arr1iarr2j d Example 1input arr1 458 arr2 10918 d 2output 2explanation for arr104 4106 d2 495 d2 413 d2 484 d2 for arr115 5105 d2 594 d2 514 d2 583 d2For arr128 have8102 d2891 d2817 d2880 d2example 2input arr1 1423 arr2 436102030 d 3output 2example 3Input arr1 211003 arr2 521037 d 6output 1 Constraints1 arr1length arr2length 5001000 arr1i arr2j 10000 d 100
0array
a cinema n row seat number 1 n seat row label 1 10 show figure aboveGiven array reservedseat contain number seat reserve example reservedseatsi 38 mean seat locate row 3 label 8 reservedreturn maximum number fourperson group assign cinema seat a fourperson group occupy adjacent seat single row Seats aisle 33 34 consider adjacent exceptional case aisle split fourperson group case aisle split fourperson group middle mean people Example 1input n 3 reservedseat 1213182631310output 4explanation the figure show optimal allocation group seat mark blue reserve contiguous seat mark orange groupExample 2input n 2 reservedseat 211826output 2example 3input n 4 reservedseat 43144617output 4 Constraints1 n 1091 reservedseatslength min10n 104reservedseatsilength 21 reservedseatsi0 n1 reservedseatsi1 10all reservedSeatsi distinct
0array
there pizza 3n slice vary size friend slice pizza followsyou pick pizza sliceYour friend Alice pick slice anticlockwise direction pickyour friend Bob pick slice clockwise direction pickrepeat slice pizzasgiven integer array slice represent size pizza slice clockwise direction return maximum possible sum slice size pick Example 1input slice 123456output 10explanation Pick pizza slice size 4 Alice Bob pick slice size 3 5 respectively then Pick slice size 6 finally Alice Bob pick slice size 2 1 respectively total 4 6example 2input slice 898611output 16explanation Pick pizza slice size 8 turn if pick slice size 9 partner pick slice size 8 Constraints3 n sliceslength1 sliceslength 5001 slicesi 1000
0array
give array integer num index your task create target array follow rulesinitially target array emptyFrom leave right read numsi indexi insert index indexi value numsi target arrayrepeat previous step element read num indexReturn target arrayit guarantee insertion operation valid Example 1input num 01234 index 01221output 04132explanationnums index target0 0 01 1 012 2 0123 2 01324 1 04132example 2input num 12340 index 01230output 01234explanationnums index target1 0 12 1 123 2 1234 3 12340 0 01234example 3input num 1 index 0output 1 Constraints1 numslength indexlength 100numslength indexlength0 numsi 1000 indexi
0array
give integer array num return sum divisor integer array exactly divisor if integer array return 0 example 1input num 2147output 32explanation 21 4 divisor 1 3 7 214 3 divisor 1 2 47 2 divisor 1 7the answer sum divisor 21 onlyExample 2input num 2121output 64example 3input num 12345output 0 Constraints1 numslength 1041 numsi 105
0array
a string call happy prefix nonempty prefix suffix exclude itselfgiven string s return long happy prefix s Return string prefix exist Example 1input s leveloutput lExplanation s contain 4 prefix exclude l le lev leve suffix l el vel evel the large prefix suffix give lExample 2input s abababoutput ababexplanation abab large prefix suffix they overlap original string Constraints1 slength 105s contain lowercase english letter
2string
give array integer arr lucky integer integer frequency array equal valuereturn large lucky integer array if lucky integer return 1 Example 1input arr 2234output 2explanation the lucky number array 2 frequency2 2example 2Input arr 122333output 3explanation 1 2 3 lucky number return large themExample 3input arr 22233output 1explanation there lucky number array Constraints1 arrlength 5001 arri 500
0array
there n soldier stand line each soldier assign unique rating valueyou form team 3 soldier follow rulesChoose 3 soldier index j k rating ratingi ratingj ratingkA team valid ratingi ratingj ratingk ratingi ratingj ratingk 0 j k nReturn number team form give condition soldier multiple team example 1input rating 25341output 3explanation we form team give condition 234 541 531 Example 2input rating 213output 0explanation we can not form team give conditionsexample 3input rating 1234output 4 Constraintsn ratinglength3 n 10001 ratingi 105All integer rating unique
0array
an underground railway system keep track customer travel time different station they datum calculate average time take travel station anotherimplement UndergroundSystem classvoid checkinint i d string stationname int ta customer card ID equal i d check station stationname time tA customer check place timevoid checkoutint i d string stationname int ta customer card ID equal i d check station stationname time tdouble getaveragetimestre startstation stre endstationreturn average time take travel startstation endstationthe average time compute previous traveling time startstation endstation happen directly mean check startstation follow check endstationthe time take travel startstation endstation different time take travel endstation startStationThere customer travel startstation endstation getaveragetime calledyou assume call checkin checkout method consistent if customer check time t1 check time t2 t1 t2 all event happen chronological order Example 1InputUndergroundSystemcheckIncheckIncheckIncheckOutcheckOutcheckOutgetAverageTimegetAverageTimecheckIngetAverageTimecheckOutgetAverageTime45Leyton332Paradise827Leyton1045Waterloo1527Waterloo2032Cambridge22ParadiseCambridgeLeytonWaterloo10Leyton24LeytonWaterloo10Waterloo38LeytonWaterlooOutputnullnullnullnullnullnullnull14000001100000null1100000null1200000ExplanationUndergroundSystem undergroundSystem new UndergroundSystemundergroundSystemcheckIn45 Leyton 3undergroundsystemcheckin32 Paradise 8undergroundsystemcheckin27 Leyton 10undergroundsystemcheckout45 Waterloo 15 Customer 45 Leyton Waterloo 153 12undergroundsystemcheckout27 Waterloo 20 Customer 27 Leyton Waterloo 2010 10undergroundsystemcheckout32 Cambridge 22 Customer 32 Paradise Cambridge 228 14undergroundsystemgetaveragetimeparadise Cambridge return 1400000 one trip Paradise Cambridge 14 1 14undergroundsystemgetaveragetimeleyton Waterloo return 1100000 two trip Leyton Waterloo 10 12 2 11undergroundsystemcheckin10 Leyton 24undergroundsystemgetaveragetimeleyton Waterloo return 1100000undergroundsystemcheckout10 Waterloo 38 Customer 10 Leyton Waterloo 3824 14undergroundsystemgetaveragetimeleyton Waterloo return 1200000 three trip Leyton Waterloo 10 12 14 3 12example 2inputundergroundsystemcheckincheckoutgetaveragetimecheckincheckoutgetaveragetimecheckincheckoutgetaveragetime10leyton310paradise8leytonparadise5leyton105paradise16leytonparadise2leyton212paradise30leytonparadiseoutputnullnullnull500000nullnull550000nullnull666667explanationundergroundsystem undergroundSystem new undergroundsystemundergroundsystemcheckin10 Leyton 3undergroundsystemcheckout10 Paradise 8 Customer 10 Leyton Paradise 83 5undergroundsystemgetaveragetimeleyton Paradise return 500000 5 1 5undergroundsystemcheckin5 Leyton 10undergroundsystemcheckout5 Paradise 16 Customer 5 Leyton Paradise 1610 6undergroundsystemgetaveragetimeleyton Paradise return 550000 5 6 2 55undergroundsystemcheckin2 Leyton 21undergroundsystemcheckout2 Paradise 30 Customer 2 Leyton Paradise 3021 9undergroundsystemgetaveragetimeleyton Paradise return 666667 5 6 9 3 666667 Constraints1 i d t 1061 stationnamelength startstationlength endstationlength 10all string consist uppercase lowercase english letter digitsthere 2 104 call total checkin checkout getaveragetimeanswer 105 actual value accept
2string
give string s1 s2 size n stre evil return number good stringsA good string size n alphabetically great equal s1 alphabetically small equal s2 contain stre evil substring since answer huge number return modulo 109 7 Example 1input n 2 s1 aa s2 da evil bOutput 51 Explanation there 25 good string start aaacadaz then 25 good string start c cacccdcz finally good string start d da Example 2input n 8 s1 leetcode s2 leetgoe evil leetOutput 0 Explanation all string greater equal s1 small equal s2 start prefix leet good stringexample 3input n 2 s1 gx s2 gz evil xOutput 2 constraintss1length ns2length ns1 s21 n 5001 evillength 50All string consist lowercase english letter
2string
give string s integ k return true use character s construct k palindrome string false Example 1input s annabelle k 2output trueexplanation you construct palindrome character ssome possible construction anna elble anbna elle anellena bExample 2input s leetcode k 3output falseexplanation it impossible construct 3 palindrome character sExample 3input s true k 4output trueexplanation the possible solution character separate string Constraints1 slength 105s consist lowercase english letters1 k 105
2string
a chef collect data satisfaction level n dish Chef cook dish 1 unit timeliketime coefficient dish define time take cook dish include previous dish multiply satisfaction level ie timei satisfactioniReturn maximum sum liketime coefficient chef obtain dish preparationdishe prepare order chef discard dish maximum value Example 1input satisfaction 18059output 14explanation after remove second dish maximum total liketime coefficient equal 11 02 53 14each dish prepare unit timeexample 2input satisfaction 432output 20explanation dish prepare order 21 32 43 20example 3input satisfaction 145output 0explanation People like dish no dish prepare Constraintsn satisfactionlength1 n 5001000 satisfactioni 1000
0array
give array num obtain subsequence array sum element strictly great sum non include element subsequence if multiple solution return subsequence minimum size exist multiple solution return subsequence maximum total sum element a subsequence array obtain erase possibly zero element array note solution give constraint guarantee unique also return answer sort nonincreasing order Example 1input num 431098output 109 Explanation the subsequence 109 108 minimal sum element strictly great sum element include however subsequence 109 maximum total sum element Example 2input num 44767Output 776 Explanation the subsequence 77 sum element equal 14 strictly great sum element include 14 4 4 6 therefore subsequence 767 minimal satisfying condition note subsequence return nondecrease order Constraints1 numslength 5001 numsi 100
0array
give binary representation integer string s return number step reduce 1 follow rulesIf current number divide 2if current number odd add 1 itit guarantee reach test case Example 1input s 1101output 6explanation 1101 corresspond number 13 decimal representationstep 1 13 odd add 1 obtain 14 step 2 14 divide 2 obtain 7step 3 7 odd add 1 obtain 8step 4 8 divide 2 obtain 4 step 5 4 divide 2 obtain 2 step 6 2 divide 2 obtain 1 Example 2input s 10output 1explanation 10 corresspond number 2 decimal representationstep 1 2 divide 2 obtain 1 Example 3input s 1output 0 Constraints1 slength 500s consist character 0 1s0 1
2string
a string s call happy satisfie follow conditions contain letters b cs contain aaa bbb ccc substrings contain occurrence letter contain b occurrence letter bs contain c occurrence letter cGiven integer b c return long possible happy string if multiple long happy string return if string return string a substre contiguous sequence character string Example 1input 1 b 1 c 7output ccaccbccExplanation ccbccacc correct answerExample 2input 7 b 1 c 0output aabaaexplanation it correct answer case Constraints0 b c 100a b c 0
2string
Alice Bob continue game pile stone there stone arrange row stone associate value integer give array stonevaluealice Bob turn Alice start on player turn player 1 2 3 stone remain stone rowthe score player sum value stone take the score player 0 initiallythe objective game end high score winner player high score tie the game continue stone takenassume Alice Bob play optimallyreturn Alice Alice win Bob Bob win Tie end game score example 1input value 1237output BobExplanation Alice lose her good pile score 6 now score Bob 7 Bob winsexample 2input value 1239output AliceExplanation Alice choose pile win leave Bob negative scoreif Alice choose pile score 1 Bobs score 5 in Alice pile value 9 loseif Alice choose pile score 3 Bobs score 3 in Alice pile value 9 loseremember play optimally Alice choose scenario make winexample 3input value 1236output TieExplanation Alice win game she end game draw decide choose pile lose constraints1 stonevaluelength 5 1041000 stoneValuei 1000
0array
give array query positive integer 1 m process queriesi i0 iquerieslength1 accord follow rulesin begin permutation p123mfor current find position queriesi permutation p indexing 0 begin permutation p Notice position queriesi p result queriesireturn array contain result give query example 1input query 3121 m 5output 2121 Explanation the query process follow for i0 queriesi3 P12345 position 3 p 2 3 begin p result P31245 for i1 queriesi1 P31245 position 1 p 1 1 begin p result P13245 for i2 queriesi2 P13245 position 2 p 2 2 begin p result P21345 for i3 queriesi1 P21345 position 1 p 1 1 begin p result P12345 therefore array contain result 2121 example 2input query 4122 m 4output 3120example 3input query 75583 m 8Output 65075 Constraints1 m 1031 querieslength m1 queriesi m
0array
html entity parser parser take HTML code input replace entity special character character itselfthe special character entity html arequotation Mark entity quot symbol character Single Quote Mark entity apos symbol character Ampersand entity amp symbol character great than Sign entity gt symbol character Less than Sign entity lt symbol character Slash entity frasl symbol character give input text stre html parser implement entity parserreturn text replace entity special character example 1input text amp html entity ambassador notOutput HTML entity ambassador notexplanation the parser replace amp entity example 2input text I quote quotquotoutput I quote Constraints1 textlength 105the string contain possible character 256 ascii character
2string
give array integer num start initial positive value startvaluein iteration calculate step step sum startvalue plus element num leave rightreturn minimum positive value startvalue step step sum 1 example 1input num 32342output 5explanation if choose startvalue 4 iteration step step sum 1step step sumstartvalue 4 startvalue 5 num 4 3 1 5 3 2 3 1 2 3 2 2 4 2 3 3 0 4 3 1 3 0 4 4 1 4 5 4 4 2 6 5 2 7 2example 2input num 12output 1explanation minimum start value positive Example 3input num 123output 5 Constraints1 numslength 100100 numsi 100
0array
a happy string string thatconsist letter set b csi si 1 value 1 slength 1 string 1indexedfor example string abc ac b abcbabcbcb happy string string aa baa ababbc happy stringsGiven integer n k consider list happy string length n sort lexicographical orderreturn kth string list return string k happy string length n Example 1input n 1 k 3output cExplanation the list b c contain happy string length 1 the string cExample 2input n 1 k 4Output Explanation there 3 happy string length 1example 3input n 3 k 9output cabexplanation there 12 different happy string length 3 aba abc aca acb bab bac bca bcb cab cac cba cbc you find 9th string cab Constraints1 n 101 k 100
2string
a program suppose print array integer the program forget print whitespace array print string digit s know integer array range 1 k lead zero arrayGiven string s integ k return number possible array print s mention program since answer large return modulo 109 7 Example 1input s 1000 k 10000output 1explanation the possible array 1000example 2input s 1000 k 10output 0explanation there array print way integer 1 10example 3input s 1317 k 2000output 8explanation possible array 13171317131713171317131713171317 Constraints1 slength 105s consist digit contain lead zeros1 k 109
2string
you give alphanumeric string s alphanumeric string string consist lowercase English letter digitsyou find permutation string letter follow letter digit follow digit that adjacent character typereturn reformatte string return string impossible reformat string Example 1input s a0b1c2output 0a1b2cexplanation no adjacent character type 0a1b2c a0b1c2 0a1b2c 0c2a1b valid permutationsExample 2input s leetcodeoutput Explanation leetcode character separate digitsExample 3input s 1229857369output Explanation 1229857369 digit separate character Constraints1 slength 500s consist lowercase english letter andor digit
2string
you give string croakOfFrogs represent combination string croak different frog multiple frogs croak time multiple croak mixedreturn minimum number different frog finish croak give stringa valid croak mean frog printing letter c r o k sequentially the frog print letter finish croak if give string combination valid croak return 1 example 1input croakoffrog croakcroakoutput 1 Explanation one frog yell croak twiceexample 2input croakoffrog crcoakroakoutput 2 Explanation the minimum number frog the frog yell crcoakroakThe second frog yell later crcoakroakexample 3input croakoffrog croakcrookoutput 1explanation the give string invalid combination croak different frog Constraints1 croakoffrogslength 105croakoffrogs c r o k
2string
give string s zero one return maximum score splitting string nonempty substring ie leave substre right substringthe score splitting string number zero leave substring plus number one right substre Example 1input s 011101output 5 Explanation all possible way split s nonempty substring areleft 0 right 11101 score 1 4 5 leave 01 right 1101 score 1 3 4 leave 011 right 101 score 1 2 3 leave 0111 right 01 score 1 1 2 leave 01110 right 1 score 2 1 3example 2input s 00111output 5explanation when leave 00 right 111 maximum score 2 3 5example 3input s 1111output 3 constraints2 slength 500the string s consist character 0 1
2string
there card arrange row card associate number point the point give integer array cardpointsin step card begin end row you exactly k cardsyour score sum point card takenGiven integer array cardpoint integer k return maximum score obtain Example 1input cardpoint 1234561 k 3output 12Explanation after step score 1 however choose rightmost card maximize total score the optimal strategy card right give final score 1 6 5 12example 2input cardpoint 222 k 2output 4explanation regardless card score 4example 3input cardpoint 9779779 k 7output 55explanation you card your score sum point card Constraints1 cardpointslength 1051 cardpointsi 1041 k cardpointslength
0array
give 2D integer array num return element num diagonal order show image Example 1input num 123456789output 142753869example 2input num 12345678910111213141516output 16287394121051311141516 Constraints1 numslength 1051 numsilength 1051 sumnumsilength 1051 numsij 105
0array
give integer array num integer k return maximum sum nonempty subsequence array consecutive integer subsequence numsi numsj j condition j k satisfiedA subsequence array obtain delete number element zero array leave remain element original order Example 1input num 10210520 k 2output 37explanation the subsequence 10 2 5 20example 2input num 123 k 1output 1explanation the subsequence nonempty choose large numberexample 3input num 10210520 k 2output 23explanation the subsequence 10 2 5 20 Constraints1 k numslength 105104 numsi 104
0array
there n kid candy you give integer array candies candiesi represent number candy ith kid integer extracandie denote number extra candy havereturn boolean array result length n resulti true give ith kid extracandie great number candy kid false otherwisenote multiple kid great number candy Example 1input candy 23513 extracandie 3output truetruetruefalsetrue Explanation if extracandie Kid 1 2 3 5 candy great kid Kid 2 3 3 6 candy great kid Kid 3 5 3 8 candy great kid Kid 4 1 3 4 candy great kid Kid 5 3 3 6 candy great kidsExample 2input candy 42112 extracandie 1output truefalsefalsefalsefalse Explanation there 1 extra candykid 1 great number candy different kid give extra candyexample 3input candy 12112 extracandie 10output truefalsetrue Constraintsn candieslength2 n 1001 candiesi 1001 extracandie 50
0array
give string s1 s2 size check permutation string s1 break permutation string s2 viceversa in word s2 break s1 viceversaA string x break stre y size n xi yi alphabetical order 0 n1 Example 1input s1 abc s2 xyaOutput trueExplanation ayx permutation s2xya break stre abc permutation s1abcexample 2input s1 abe s2 acdoutput false Explanation all permutation s1abe abe aeb bae bea eab eba permutation s2acd acd adc cad cda dac dca however permutation s1 break permutation s2 viceversaexample 3input s1 leetcodee s2 interviewoutput true constraintss1length ns2length n1 n 105All string consist lowercase english letter
2string
there n people 40 type hat label 1 40given 2D integer array hats hatsi list hat prefer ith personreturn number way n people wear different hat othersince answer large return modulo 109 7 Example 1input hat 34455output 1explanation there way choose hat give condition First person choose hat 3 second person choose hat 4 hat 5example 2input hat 35135output 4explanation there 4 way choose hats35 53 13 15example 3input hat 1234123412341234output 24explanation each person choose hat label 1 4number Permutations 1234 24 Constraintsn hatslength1 n 101 hatsilength 401 hatsij 40hatsi contain list unique integer
0array
you give array path pathsi cityAi cityBi mean exist direct path go cityAi cityBi Return destination city city path outgoing cityit guarantee graph path form line loop exactly destination city example 1input path LondonNew YorkNew YorkLimaLimaSao PauloOutput Sao Paulo Explanation Starting London city reach Sao Paulo city destination city your trip consist London New York Lima Sao PauloExample 2input path bcdbcaoutput AExplanation all possible trip D b C a b c a c a a clearly destination city AExample 3input path AZOutput Z Constraints1 pathslength 100pathsilength 21 cityAilength citybilength 10cityAi cityBiAll string consist lowercase uppercase English letter space character
2string
give binary array num integer k return true 1s k place away return false Example 1input num 10001001 k 2output trueexplanation each 1 2 place away otherExample 2input num 100101 k 2output falseexplanation the second 1 1 apart Constraints1 numslength 1050 k numslengthnumsi 0 1
0array
give array integer num integer limit return size long nonempty subarray absolute difference element subarray equal limit example 1input num 8247 limit 4output 2 explanation all subarray 8 maximum absolute diff 88 0 482 maximum absolute diff 82 6 4 824 maximum absolute diff 82 6 48247 maximum absolute diff 82 6 42 maximum absolute diff 22 0 424 maximum absolute diff 24 2 4247 maximum absolute diff 27 5 44 maximum absolute diff 44 0 447 maximum absolute diff 47 3 47 maximum absolute diff 77 0 4 therefore size long subarray 2example 2input num 1012472 limit 5output 4 Explanation the subarray 2472 long maximum absolute diff 27 5 5example 3input num 42224422 limit 0output 3 Constraints1 numslength 1051 numsi 1090 limit 109
0array