question
stringlengths
58
4.29k
label
class label
3 classes
give string s1 s2 return low ascii sum delete character string equal Example 1input s1 sea s2 eatoutput 231explanation Deleting s sea add ascii value s 115 sumdeleting t eat add 116 sumAt end string equal 115 116 231 minimum sum possible achieve thisexample 2input s1 delete s2 leetoutput 403explanation delete dee delete turn string letadd 100d 101e 101e sumDeleting e leet add 101e sumAt end string equal let answer 100101101101 403if instead turn string lee eet answer 433 417 high Constraints1 s1length s2length 1000s1 s2 consist lowercase english letter
2string
give array integer num integer k return number contiguous subarray product element subarray strictly k Example 1input num 10526 k 100Output 8explanation the 8 subarray product 100 are10 5 2 6 10 5 5 2 2 6 5 2 6note 10 5 2 include product 100 strictly kExample 2input num 123 k 0output 0 Constraints1 numslength 3 1041 numsi 10000 k 106
0array
you give array price pricesi price give stock ith day integer fee represent transaction feefind maximum profit achieve you complete transaction like need pay transaction fee transactionnote you engage multiple transaction simultaneously ie sell stock buy Example 1input price 132849 fee 2output 8explanation the maximum profit achieve buy prices0 1 sell prices3 8 buying prices4 4 selling prices5 9the total profit 8 1 2 9 4 2 8example 2input price 1375103 fee 3output 6 Constraints1 priceslength 5 1041 pricesi 5 1040 fee 5 104
0array
we special charactersthe character represent bit 0the second character represent bit 10 11given binary array bit end 0 return true character onebit character Example 1input bit 100output trueexplanation the way decode twobit character onebit characterSo character onebit characterexample 2input bit 1110output falseexplanation the way decode twobit character twobit characterSo character onebit character Constraints1 bitslength 1000bitsi 0 1
0array
give integer array nums1 nums2 return maximum length subarray appear array Example 1input nums1 12321 nums2 32147output 3explanation the repeat subarray maximum length 321example 2input nums1 00000 nums2 00000output 5explanation the repeat subarray maximum length 00000 Constraints1 nums1length nums2length 10000 nums1i nums2i 100
0array
the distance pair integer b define absolute difference bGiven integer array num integer k return kth small distance pair numsi numsj 0 j numslength Example 1input num 131 k 1output 0explanation here pairs13 211 031 2Then 1st small distance pair 11 distance 0example 2input num 111 k 2output 0example 3input num 161 k 3output 5 Constraintsn numslength2 n 1040 numsi 1061 k n n 1 2
0array
give array integer num calculate pivot index arrayThe pivot index index sum number strictly leave index equal sum number strictly indexs rightIf index leave edge array leave sum 0 element leave this apply right edge arrayReturn leftmost pivot index if index exist return 1 example 1input num 173656output 3explanationthe pivot index 3left sum nums0 nums1 nums2 1 7 3 11right sum nums4 nums5 5 6 11example 2input num 123Output 1explanationthere index satisfie condition problem statementexample 3input num 211Output 0explanationthe pivot index 0left sum 0 element leave index 0right sum nums1 nums2 1 1 0 constraints1 numslength 1041000 numsi 1000 note this question 1991 httpsleetcodecomproblemsfindthemiddleindexinarray
0array
give string formula represent chemical formula return count atomthe atomic element start uppercase character zero lowercase letter represent nameone digit represent element count follow count great 1 if count 1 digit followfor example H2O H2O2 possible H1O2 impossibleTwo formula concatenate produce formulafor example H2O2He3Mg4 formulaA formula place parenthesis count optionally add formulaFor example H2O2 H2O23 formulasreturn count element string follow form sort order follow count count 1 follow second sorted order follow count count 1 onthe test case generate value output fit 32bit integer Example 1input formula h2ooutput h2oexplanation the count element h 2 o 1example 2input formula MgOH2Output H2MgO2Explanation the count element h 2 Mg 1 o 2example 3input formula k4onso322output k4n2o14s4explanation the count element k 4 n 2 o 14 s 4 Constraints1 formulalength 1000formula consist english letter digit formula valid
2string
give string s return number different nonempty palindromic subsequence s since answer large return modulo 109 7a subsequence string obtain delete zero character stringa sequence palindromic equal sequence reversedTwo sequences a1 a2 b1 b2 different ai bi Example 1input s bccboutput 6explanation the 6 different nonempty palindromic subsequence b c bb cc bcb bccbNote bcb count occur twiceexample 2input s abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcbaoutput 104860361explanation there 3104860382 different nonempty palindromic subsequence 104860361 modulo 109 7 constraints1 slength 1000si b c d
2string
we give array asteroid integer represent asteroid rowfor asteroid absolute value represent size sign represent direction positive meaning right negative meaning leave each asteroid move speedfind state asteroid collision if asteroid meet small explode if size explode two asteroid move direction meet Example 1input asteroid 5105output 510explanation the 10 5 collide result 10 the 5 10 collideExample 2input asteroid 88output Explanation the 8 8 collide explode otherexample 3input asteroid 1025output 10explanation the 2 5 collide result 5 the 10 5 collide result 10 constraints2 asteroidslength 1041000 asteroidsi 1000asteroidsi 0
0array
you give string expression represent Lisplike expression return integer value ofthe syntax expression give followsan expression integer let expression add expression mult expression assign variable expression evaluate single integeran integer positive negativeA let expression take form let v1 e1 v2 e2 vn en expr let string let pair alternate variable expression mean variable v1 assign value expression e1 second variable v2 assign value expression e2 sequentially value let expression value expression exprAn add expression take form add e1 e2 add string add expression e1 e2 result addition evaluation e1 evaluation e2a mult expression take form mult e1 e2 mult string mult expression e1 e2 result multiplication evaluation e1 evaluation e2For question use small subset variable name a variable start lowercase letter zero lowercase letter digit additionally convenience name add let mult protect variable namesfinally concept scope when expression variable evaluate context evaluation innermost scope term parenthese check value variable outer scope check sequentially it guarantee expression legal please example detail scope example 1input expression let x 2 mult x let x 3 y 4 add x youtput 14explanation in expression add x y checking value variable xwe check innermost scope outermost context variable try evaluateSince x 3 find value x 3example 2input expression let x 3 x 2 xOutput 2explanation Assignment let statement process sequentiallyExample 3input expression let x 1 y 2 x add x y add x youtput 5explanation the add x y evaluate 3 assign xThe second add x y evaluate 32 5 constraints1 expressionlength 2000there lead trail space expressionAll token separate single space expressionthe answer intermediate calculation answer guarantee fit 32bit integerthe expression guarantee legal evaluate integer
2string
give array integer temperature represent daily temperature return array answer answeri number day wait ith day warm temperature if future day possible answeri 0 instead example 1input temperature 7374757169727673output 11421100example 2input temperature 30405060output 1110example 3input temperature 306090output 110 Constraints1 temperatureslength 10530 temperaturesi 100
0array
you give integer array num you want maximize number point perform follow operation number timespick numsi delete earn numsi point afterwards delete element equal numsi 1 element equal numsi 1return maximum number point earn apply operation number times Example 1input num 342output 6explanation you perform follow operation Delete 4 earn 4 point consequently 3 delete num 2 Delete 2 earn 2 point num you earn total 6 pointsexample 2input num 223334output 9explanation you perform follow operation Delete 3 earn 3 point all 2s 4s delete num 33 Delete 3 earn 3 point num 3 Delete 3 earn 3 point num you earn total 9 point Constraints1 numslength 2 1041 numsi 104
0array
you give n x n grid represent field cherry cell possible integers0 mean cell pass through1 mean cell contain cherry pick pass or1 mean cell contain thorn block wayreturn maximum number cherry collect follow rule belowstarte position 0 0 reach n 1 n 1 move right valid path cell cell value 0 1After reach n 1 n 1 return 0 0 move leave valid path cellswhen pass path cell contain cherry pick cell cell 0if valid path 0 0 n 1 n 1 cherry collect Example 1input grid 011101111output 5explanation the player start 0 0 go right right reach 2 24 cherry pick single trip matrix 011001000then player went leave leave return home pick cherrythe total number cherry pick 5 maximum possibleExample 2input grid 111111111output 0 Constraintsn gridlengthn gridilength1 n 50gridij 1 0 1grid00 1gridn 1n 1 1
0array
you give network n node label 1 n you give time list travel time direct edge timesi ui vi wi ui source node vi target node wi time take signal travel source targetwe send signal give node k Return minimum time take n node receive signal if impossible n node receive signal return 1 Example 1input time 211231341 n 4 k 2output 2example 2Input times 121 n 2 k 1output 1Example 3Input times 121 n 2 k 2output 1 Constraints1 k n 1001 timeslength 6000timesilength 31 ui vi nui vi0 wi 100All pairs ui vi unique ie multiple edge
1graph
you give array character letter sort nondecrease order character target there different character lettersreturn small character letter lexicographically great target if character exist return character letter Example 1input letter cfj target aOutput cExplanation the small character lexicographically great letter cExample 2input letter cfj target cOutput fExplanation the small character lexicographically great c letter fExample 3input letter xxyy target zOutput xExplanation there character letter lexicographically great z return letters0 constraints2 letterslength 104lettersi lowercase english letterletter sort nondecrease orderletter contain different characterstarget lowercase english letter
0array
design special dictionary search word prefix suffiximplement WordFilter classwordfilterstring word Initializes object word dictionaryfstre pref string suff Returns index word dictionary prefix pref suffix suff if valid index return large if word dictionary return 1 example 1inputwordfilter fapple eOutputnull 0explanationwordfilter wordFilter new wordfilterapplewordfilterfa e return 0 word index 0 prefix suffix e Constraints1 wordslength 1041 wordsilength 71 preflength sufflength 7wordsi pref suff consist lowercase english letter onlyAt 104 call function f
2string
you give integer array cost costi cost ith step staircase once pay cost climb stepsYou start step index 0 step index 1return minimum cost reach floor example 1input cost 101520output 15explanation you start index 1 pay 15 climb step reach topthe total cost 15example 2input cost 1100111100111001output 6explanation you start index 0 pay 1 climb step reach index 2 pay 1 climb step reach index 4 pay 1 climb step reach index 6 pay 1 climb step reach index 7 pay 1 climb step reach index 9 pay 1 climb step reach topthe total cost 6 constraints2 costlength 10000 costi 999
0array
you give integer array num large integer uniqueDetermine large element array twice number array if return index large element return 1 example 1input num 3610output 1explanation 6 large integerfor number array x 6 twice big xThe index value 6 1 return 1example 2input num 1234output 1explanation 4 twice value 3 return 1 constraints2 numslength 500 numsi 100the large element num unique
0array
there safe protect password the password sequence n digits digit range 0 k 1the safe peculiar way check password when enter sequence check recent n digit enter time type digitfor example correct password 345 enter 012345after typing 0 recent 3 digit 0 incorrectafter type 1 recent 3 digit 01 incorrectafter type 2 recent 3 digit 012 incorrectafter type 3 recent 3 digits 123 incorrectafter type 4 recent 3 digit 234 incorrectafter type 5 recent 3 digit 345 correct safe unlocksReturn string minimum length unlock safe point enter Example 1input n 1 k 2output 10explanation the password single digit enter digit 01 unlock safeexample 2input n 2 k 2output 01100explanation for possible password 00 type start 4th digit 01 type start 1st digit 10 type start 3rd digit 11 type start 2nd digitthus 01100 unlock safe 01100 10011 11001 unlock safe Constraints1 n 41 k 101 kn 4096
1graph
you stack block form pyramid each block color represent single letter each row block contain block row beneath center topto pyramid aesthetically pleasing specific triangular pattern allow a triangular pattern consist single block stack block the pattern give list threeletter string allow character pattern represent leave right block respectively character blockfor example ABC represent triangular pattern C block stack a left b right block note different BAC B leave a right bottomyou start row block give single string use base pyramidgiven allow return true build pyramid way triangular pattern pyramid allow false Example 1input BCD allow BCCCDECEAFFFOutput trueexplanation the allow triangular pattern show rightstarte level 3 build CE level 2 build a level 1there triangular pattern pyramid BCC CDE CEA all allowedexample 2input AAAA allow AABAACBCDBBEDEFOutput falseexplanation the allow triangular pattern show rightstarte level 4 multiple way build level 3 try possibilite stuck building level 1 constraints2 bottomlength 60 allowedlength 216allowedilength 3the letter input string set a b c d e fall value allow unique
1graph
you give 2D integer array intervals intervalsi starti endi represent integer starti endi inclusivelyA contain set array num interval interval integer numsfor example interval 13 37 89 124789 23489 contain setsreturn minimum possible size contain set Example 1input interval 133789output 5explanation let num 2 3 4 8 9it show contain array size 4example 2input interval 13142535output 3explanation let num 2 3 4it show contain array size 2example 3input interval 12232445output 5explanation let num 1 2 3 4 5it show contain array size 4 Constraints1 intervalslength 3000intervalsilength 20 starti endi 108
0array
special binary string binary string follow propertiesthe number 0s equal number 1severy prefix binary string 1s 0syou give special binary string sa consist choose consecutive nonempty special substring s swap two string consecutive character string exactly index character second stringreturn lexicographically large result string possible apply mention operation string Example 1input s 11011000output 11100100explanation the string 10 occur s1 1100 s3 swappedthis lexicographically large string possible number swapsexample 2input s 10output 10 constraints1 slength 50si 0 1s special binary string
2string
you give string s we want partition string part possible letter appear partnote partition concatenate part order resultant string sReturn list integer represent size part Example 1input s ababcbacadefegdehijhklijOutput 978explanationthe partition ababcbaca defegde hijhklijthis partition letter appear parta partition like ababcbacadefegde hijhklij incorrect split s partsexample 2input s eccbbbbdecoutput 10 Constraints1 slength 500s consist lowercase english letter
2string
you give integer n you n x n binary grid grid value initially 1s index give array mine the ith element array mine define minesi xi yi gridxiyi 0Return order large axisaligned plus sign 1s contain grid if return 0an axisaligned plus sign 1s order k center gridrc 1 arm length k 1 go leave right 1s note 0s 1s arm plus sign relevant area plus sign check 1s Example 1input n 5 mine 42output 2explanation in grid large plus sign order 2 one shownexample 2input n 1 mine 00output 0explanation there plus sign return 0 Constraints1 n 5001 mineslength 50000 xi yi nAll pair xi yi unique
0array
there n couple sit 2n seat arrange row want hold handsthe people seat represent integer array row rowi ID person sit ith seat the couple number order couple 0 1 second couple 2 3 couple 2n 2 2n 1return minimum number swap couple sit a swap consist choose people stand switch seat Example 1input row 0213output 1explanation we need swap second row1 row2 personexample 2input row 3201output 0explanation all couple seat Constraints2n rowlength2 n 30n even0 rowi 2nall element row unique
1graph
give m x n matrix return true matrix Toeplitz Otherwise return falseA matrix Toeplitz diagonal topleft bottomright element example 1input matrix 123451239512output trueexplanationin grid diagonal are9 5 5 1 1 1 2 2 2 3 3 4in diagonal element answer TrueExample 2input matrix 1222output falseExplanationThe diagonal 1 2 different element Constraintsm matrixlengthn matrixilength1 m n 200 matrixij 99 Follow upwhat matrix store disk memory limit load row matrix memory oncewhat matrix large load partial row memory
0array
give string s rearrange character s adjacent character samereturn possible rearrangement s return possible Example 1input s aaboutput abaexample 2input s aaaboutput Constraints1 slength 500s consist lowercase english letter
2string
you give integer array arrWe split arr number chunk ie partition individually sort chunk after concatenate result equal sorted arrayreturn large number chunk sort array Example 1input arr 54321output 1explanationsplitting chunk return require resultfor example split 5 4 3 2 1 result 4 5 1 2 3 is not sortedexample 2input arr 21344output 4explanationwe split chunk 2 1 3 4 4however splitting 2 1 3 4 4 high number chunk possible Constraints1 arrlength 20000 arri 108
0array
you give integer array arr length n represent permutation integer range 0 n 1we split arr number chunk ie partition individually sort chunk after concatenate result equal sorted arrayreturn large number chunk sort array Example 1input arr 43210output 1explanationsplitting chunk return require resultfor example split 4 3 2 1 0 result 3 4 0 1 2 is not sortedexample 2input arr 10234output 4explanationwe split chunk 1 0 2 3 4however splitting 1 0 2 3 4 high number chunk possible Constraintsn arrlength1 n 100 arri nAll element arr unique
0array
give expression expression e 8 5 evaluation map e 1 give term evalvar e evalint 1 return list token represent simplified expression 1a14an expression alternate chunk symbol space separate chunk symbola chunk expression parenthese variable nonnegative integerA variable string lowercase letter include digit Note variable multiple letter note variable lead coefficient unary operator like 2x xExpressions evaluate usual order bracket multiplication addition subtractionfor example expression 1 2 3 answer 7the format output followsFor term free variable nonzero coefficient write free variable term sort order lexicographicallyfor example write term like bac abcTerms degree equal number free variable multiply count multiplicity we write large degree term answer break tie lexicographic order ignore lead coefficient termFor example aabc degree 4the lead coefficient term place directly leave asterisk separate variable exist a lead coefficient 1 printedan example wellformatte answer 2aaa 3aab 3bb 4a 5c 6term include constant term coefficient 0 includedfor example expression 0 output note you assume give expression valid all intermediate result range 231 231 1 Example 1input expression e 8 5 evalvar e evalint 1output 1a14example 2input expression e 8 temperature pressure evalvar e temperature evalint 1 12output 1pressure5example 3input expression e 8 e 8 evalvar evalint Output 1ee64 Constraints1 expressionlength 250expression consists lowercase english letter digits expression contain lead trail spacesAll token expression separate single space0 evalvarslength 1001 evalvarsilength 20evalvarsi consists lowercase english lettersevalintslength evalvarslength100 evalintsi 100
2string
you re give string jewel represent type stone jewel stone represent stone each character stone type stone you want know stone jewelsletter case sensitive consider different type stone A Example 1input jewel aa stone aaabbbboutput 3example 2input jewel z stone zzoutput 0 Constraints1 jewelslength stoneslength 50jewels stone consist English lettersall character jewel unique
2string
you give integer array num length n represent permutation integer range 0 n 1the number global inversion number different pair j where0 j nnumsi numsjThe number local inversion number index where0 n 1numsi numsi 1return true number global inversion equal number local inversion example 1input num 102output trueexplanation there 1 global inversion 1 local inversionExample 2input num 120output falseexplanation there 2 global inversion 1 local inversion Constraintsn numslength1 n 1050 numsi nAll integer num uniquenum permutation number range 0 n 1
0array
in string compose L R x character like RXXLRXRXL consist replace occurrence XL LX replace occurrence RX xr give start string start end string end return true exist sequence move transform string Example 1input start RXXLRXRXL end XRLXXRRLXOutput trueexplanation we transform start end follow stepsRXXLRXRXL XRXLRXRXL XRLXRXRXL XRLXXRRXL XRLXXRRLXExample 2input start x end LOutput false constraints1 startlength 104startlength endlengthBoth start end consist character L R x
2string
there forest unknown number rabbit we ask n rabbit how rabbit color collect answer integer array answer answersi answer ith rabbitgiven array answer return minimum number rabbit forest Example 1input answer 112output 5explanationthe rabbit answer 1 color redthe rabbit answer 2 can not red answer inconsistentsay rabbit answer 2 bluethen 2 blue rabbit forest do not answer arraythe small possible number rabbit forest 5 3 answer plus 2 didntExample 2input answer 101010output 11 Constraints1 answerslength 10000 answersi 1000
0array
you give n x n binary grid board in swap row column otherreturn minimum number move transform board chessboard board if task impossible return 1A chessboard board board 0s 1s 4directionally adjacent Example 1input board 0110011010011001output 2explanation one potential sequence move shownthe swap second columnthe second swap second rowExample 2input board 0110output 0explanation also note board 0 leave corner valid chessboardexample 3input board 1010output 1explanation no matter sequence move end valid chessboard Constraintsn boardlengthn boardilength2 n 30boardij 0 1
0array
give root Binary Search Tree BST return minimum difference value different node tree example 1input root 42613output 1example 2input root 1048nullnull1249output 1 ConstraintsThe number nod tree range 2 1000 Nodeval 105 note this question 530 httpsleetcodecomproblemsminimumabsolutedifferenceinbst
1graph
give string s transform letter individually lowercase uppercase create stringreturn list possible string create return output order Example 1input s a1b2Output a1b2a1b2a1b2a1b2example 2input s 3z4output 3z43z4 constraints1 slength 12 consist lowercase english letter uppercase english letter digit
2string
there undirecte graph n node node number 0 n 1 you give 2D array graph graphu array nod node u adjacent more formally v graphu undirected edge node u node v the graph follow propertiesthere selfedge graphu contain uthere parallel edge graphu contain duplicate valuesIf v graphu u graphv graph undirectedThe graph connected meaning node u v path themA graph bipartite node partition independent set a B edge graph connect node set a node set BReturn true bipartite Example 1input graph 1230201302output falseexplanation there way partition nod independent set edge connect node node otherExample 2input graph 13021302output trueexplanation we partition node set 0 2 1 3 Constraintsgraphlength n1 n 1000 graphulength n0 graphui n 1graphu contain uAll value graphu uniqueif graphu contain v graphv contain u
1graph
you give sorted integer array arr contain 1 prime number integer arr unique you give integer kFor j 0 j arrlength consider fraction arri arrjReturn kth small fraction consider return answer array integer size 2 answer0 arri answer1 arrj Example 1Input arr 1235 k 3output 25explanation the fraction consider sorted order are15 13 25 12 35 23the fraction 25example 2input arr 17 k 1output 17 Constraints2 arrlength 10001 arri 3 104arr0 1arri prime number 0all number arr unique sort strictly increase order1 k arrlength arrlength 1 2 Follow can solve problem well on2 complexity
0array
there n city connect number flight you give array flight flightsi fromi toi pricei indicate flight city fromi city toi cost priceiyou give integer src dst k return cheap price src dst k stop if route return 1 Example 1input n 4 flight 0110012100201001360023200 src 0 dst 3 k 1Output 700explanationthe graph show aboveThe optimal path 1 stop city 0 3 mark red cost 100 600 700note path city 0123 cheap invalid use 2 stopsExample 2input n 3 flight 011001210002500 src 0 dst 2 k 1Output 200explanationthe graph show aboveThe optimal path 1 stop city 0 2 mark red cost 100 100 200example 3input n 3 flight 011001210002500 src 0 dst 2 k 0output 500explanationthe graph show aboveThe optimal path stop city 0 2 mark red cost 500 Constraints1 n 1000 flightslength n n 1 2flightsilength 30 fromi toi nfromi toi1 pricei 104there multiple flight cities0 src dst k nsrc dst
1graph
you play simplify PACMAN game infinite 2D grid you start point 0 0 give destination point target xtarget ytarget try there ghost map start position give 2d array ghost ghostsi xi yi represent start position ith ghost all input integral coordinateseach turn ghost independently choose 1 unit cardinal direction north east south west stay all action happen simultaneouslyyou escape reach target ghost reach if reach square include target time ghost count escapereturn true possible escape regardless ghost return false example 1input ghost 1003 target 01output trueExplanation you reach destination 0 1 1 turn ghost locate 1 0 0 3 catch youexample 2input ghost 10 target 20output falseexplanation you need reach destination 2 0 ghost 1 0 lie destinationexample 3input ghost 20 target 10output falseexplanation the ghost reach target time Constraints1 ghostslength 100ghostsilength 2104 xi yi 104There multiple ghost locationtargetlength 2104 xtarget ytarget 104
0array
you give string order s all character order unique sorted custom order previouslypermute character s match order order sort more specifically character x occur character y order x occur y permute stringreturn permutation s satisfie property Example 1input order cba s abcdOutput cbadExplanation b c appear order order b c c b since d appear order position return string dcba cdba cbda valid outputsexample 2input order cbafg s abcdoutput cbad Constraints1 orderlength 261 slength 200order s consist lowercase English lettersall character order unique
2string
give stre s array string word return number wordsi subsequence sA subsequence stre new string generate original string character delete change relative order remain charactersFor example ace subsequence abcde Example 1input s abcde word abbacdaceOutput 3explanation there string word subsequence s acd aceExample 2Input s dsahjpjauf word ahjpjaujaahbwzgqnuktnmlanowaxoutput 2 constraints1 slength 5 1041 wordslength 50001 wordsilength 50 wordsi consist lowercase english letter
2string
give integer array nums integer leave right return number contiguous nonempty subarray value maximum array element subarray range leave rightthe test case generate answer fit 32bit integer Example 1input num 2143 leave 2 right 3output 3explanation there subarray meet requirement 2 2 1 3example 2input num 29256 leave 2 right 8Output 7 Constraints1 numslength 1050 numsi 1090 leave right 109
0array
give string s goal return true s goal number shift sA shift s consist move leftmost character s rightmost positionFor example s abcde bcdea shift Example 1input s abcde goal cdeaboutput trueexample 2input s abcde goal abcedOutput false constraints1 slength goallength 100s goal consist lowercase english letter
2string
give direct acyclic graph DAG n node label 0 n 1 find possible path node 0 node n 1 return orderthe graph give follow graphi list node visit node ie direct edge node node graphij Example 1input graph 1233output 013023explanation there path 0 1 3 0 2 3example 2input graph 43132434output 04034013401234014 Constraintsn graphlength2 n 150 graphij ngraphij ie selfloopsAll element graphi uniquethe input graph guarantee DAG
1graph
you give array num you rotate nonnegative integer k array numsk numsk 1 numsnumslength 1 nums0 nums1 numsk1 afterward entry equal index worth pointfor example num 24130 rotate k 2 13024 this worth 3 point 1 0 point 3 1 point 0 2 point 2 3 point 4 4 pointreturn rotation index k correspond high score achieve rotate num if multiple answer return small index k Example 1input num 23140output 3explanation Scores k list k 0 num 23140 score 2k 1 num 31402 score 3k 2 num 14023 score 3k 3 num 40231 score 4k 4 num 02314 score 3so choose k 3 high scoreexample 2input num 13024output 0explanation num 3 point matter shiftsSo choose small k 0 constraints1 numslength 1050 numsi numslength
0array
you give integer array length nums1 nums2 in operation allow swap nums1i nums2iFor example nums1 1238 nums2 5674 swap element 3 obtain nums1 1234 nums2 5678return minimum number need operation nums1 nums2 strictly increase the test case generate give input make possiblean array arr strictly increase arr0 arr1 arr2 arrarrlength 1 Example 1input nums1 1354 nums2 1237output 1explanation Swap nums13 nums23 then sequence arenums1 1 3 5 7 nums2 1 2 3 4which strictly increasingExample 2input nums1 03589 nums2 21469output 1 Constraints2 nums1length 105nums2length nums1length0 nums1i nums2i 2 105
0array
there direct graph n node node label 0 n 1 the graph represent 0indexed 2D integer array graph graphi integer array nod adjacent node meaning edge node node graphiA node terminal node outgoing edge a node safe node possible path start node lead terminal node safe nodeReturn array contain safe node graph the answer sort ascending order Example 1input graph 1223505output 2456explanation the give graph show abovenode 5 6 terminal node outgoing edge themevery path start node 2 4 5 6 lead node 5 6example 2input graph 1234123404output 4explanationonly node 4 terminal node path start node 4 lead node 4 Constraintsn graphlength1 n 1040 graphilength n0 graphij n 1graphi sort strictly increase orderthe graph contain selfloopsthe number edge graph range 1 4 104
1graph
you give m x n binary grid 1 represent brick 0 represent space a brick stable ifit directly connect grid orat brick adjacent cell stableyou give array hit sequence erasure want apply each time want erase brick location hitsi rowi coli the brick location exist disappear some brick long stable erasure fall once brick fall immediately erase grid ie land stable bricksreturn array result resulti number brick fall ith erasure appliednote erasure refer location brick brick drop Example 1input grid 10001110 hit 10output 2explanation start grid1000 1110we erase underline brick 10 result grid1000 0110the underlined brick long stable long connect adjacent stable brick fall the result grid is1000 0000hence result 2example 2Input grid 10001100 hit 1110output 00explanation start grid1000 1100we erase underline brick 11 result grid1000 1000all remain brick stable brick fall the grid remain same1000 1000next erase underline brick 10 result grid1000 0000once remain brick stable brick fallhence result 00 Constraintsm gridlengthn gridilength1 m n 200gridij 0 11 hitslength 4 104hitsilength 20 xi m 10 yi n 1all xi yi unique
0array
you give integer array numsyou element num array a B a b nonempty averageA averagebreturn true possible achieve false otherwisenote array arr averagearr sum elements arr length arr Example 1input num 12345678output trueexplanation we split array 1458 2367 average 45example 2input num 31output false Constraints1 numslength 300 numsi 104
0array
there city compose n x n block block contain single building shape like vertical square prism you give 0indexed n x n integer matrix grid gridrc represent height building locate block row r column cA city skyline outer contour form building view city distance the skyline cardinal direction north east south west differentWe allow increase height number building different building the height 0height building increase however increase height building affect citys skyline cardinal directionreturn maximum total sum height building increase change city skyline cardinal direction Example 1input grid 3084245792630310output 35explanation the building height show center imageThe skyline view cardinal direction draw redthe grid increase height building affect skyline isgridNew 8 4 8 7 7 4 7 7 9 4 8 7 3 3 3 3 example 2input grid 000000000output 0explanation increase height building result skyline change Constraintsn gridlengthn gridrlength2 n 500 gridrc 100
0array
you give array integer num represent number write chalkboardalice Bob turn erase exactly number chalkboard Alice start if erase number cause bitwise XOR element chalkboard 0 player lose the bitwise XOR element element bitwise XOR element 0also player start turn bitwise XOR element chalkboard equal 0 player winsReturn true Alice win game assume player play optimally Example 1input num 112output falseexplanation Alice choice erase 1 erase 2 if erase 1 num array 1 2 the bitwise XOR element chalkboard 1 xor 2 3 now Bob remove element want Alice erase element lose if Alice erase 2 num 1 1 the bitwise XOR element chalkboard 1 xor 1 0 Alice loseExample 2input num 01output trueexample 3input num 123output true Constraints1 numslength 10000 numsi 216
0array
give array point XY plane point pointsi xi yi return area large triangle form different point Answers 105 actual answer accept Example 1input point 0001100220output 200000explanation the point show figure the red triangle largestExample 2input point 100001output 050000 constraints3 pointslength 5050 xi yi 50all give point unique
0array
you give integer array num integer k you partition array k nonempty adjacent subarray the score partition sum averages subarrayNote partition use integer num score necessarily integerreturn maximum score achieve possible partition Answers 106 actual answer accept Example 1input num 91239 k 3output 2000000explanation the good choice partition num 9 1 2 3 9 the answer 9 1 2 3 3 9 20we partition num 9 1 2 3 9 examplethat partition lead score 5 2 6 13 worseExample 2input num 1234567 k 4Output 2050000 Constraints1 numslength 1001 numsi 1041 k numslength
0array
give root binary tree return tree subtree given tree contain 1 removedA subtree node node node plus node descendant node Example 1input root 1null001output 1null0null1explanation only red node satisfy property subtree contain 1the diagram right represent answerExample 2input root 1010001output 1null1null1example 3input root 11011010output 11011null1 ConstraintsThe number nod tree range 1 200nodeval 0 1
1graph
we 2dimensional coordinate like 1 3 2 05 then remove commas decimal point space end string sFor example 1 3 s 13 2 05 s 205return list string represent possibility original coordinate beenOur original representation extraneous zero start number like 00 00 000 10 001 0001 number represent few digit also decimal point number occur digit occur start number like 1the final answer list return order all coordinate final answer exactly space occur comma Example 1input s 123output 1 231 2312 312 3example 2input s 0123output 0 1230 1230 12301 2301 23012 3explanation 00 00 0001 0001 allowedexample 3input s 00011output 0 00110001 1 constraints4 slength 12s0 sslength 1 the rest s digit
2string
you give head link list contain unique integer value integer array nums subset link list valuesreturn number connect component num value connect appear consecutively link list example 1input head 0123 num 013output 2explanation 0 1 connect 0 1 3 connect componentsExample 2input head 01234 num 0314output 2explanation 0 1 connect 3 4 connect 0 1 3 4 connect component ConstraintsThe number node link list n1 n 1040 Nodeval nAll value Nodeval unique1 numslength n0 numsi nAll value num unique
0array
give string paragraph string array ban word ban return frequent word ban it guarantee word ban answer uniquethe word paragraph caseinsensitive answer return lowercase Example 1input paragraph Bob hit ball hit BALL fly far hit ban hitoutput ballexplanation hit occur 3 time ban wordball occur twice word frequent nonbanne word paragraph note word paragraph case sensitivethat punctuation ignore adjacent word ball hit is not answer occur bannedexample 2input paragraph ban Output Constraints1 paragraphlength 1000paragraph consist english letter space symbol 0 bannedlength 1001 bannedilength 10bannedi consist lowercase english letter
2string
you give 0indexed integer array front back length n ith card positive integer frontsi print backsi print Initially card place table number face face you flip number card possibly zeroafter flip card integer consider good facing card face cardreturn minimum possible good integer flipping card if good integer return 0 example 1input front 12447 back 13413output 2explanationif flip second card face number 13447 face 124132 minimum good integer appear face face upit show 2 minimum possible good integer obtainable flip cardsexample 2input front 1 back 1output 0ExplanationThere good integer matter flip card return 0 Constraintsn frontslength backslength1 n 10001 frontsi backsi 2000
0array
give array unique integer arr integer arri strictly great 1we binary tree integer number number time each nonleaf nod value equal product value childrenreturn number binary tree the answer large return answer modulo 109 7 Example 1input arr 24output 3explanation we tree 2 4 4 2 2example 2input arr 24510output 7explanation we tree 2 4 5 10 4 2 2 10 2 5 10 5 2 constraints1 arrlength 10002 arri 109All value arr unique
0array
you give string sentence consist word separate space each word consist lowercase uppercase letter onlywe like convert sentence Goat Latin madeup language similar Pig Latin the rule Goat latin followsif word begin vowel e o u append ma end wordfor example word apple applemaif word begin consonant ie vowel remove letter append end add maFor example word goat oatgmaAdd letter end word word index sentence start 1for example word gets add end second word gets aa add end onreturn final sentence represent conversion sentence Goat Latin Example 1input sentence I speak Goat LatinOutput Imaa peaksmaaa oatGmaaaa atinlmaaaaaexample 2input sentence the quick brown fox jump lazy dogoutput heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa Constraints1 sentencelength 150sentence consist english letter spacessentence lead trail spacesAll word sentence separate single space
2string
there n person social medium website you give integer array age agesi age ith personA Person x send friend request person y x y follow condition trueagey 05 agex 7agey agexagey 100 agex 100otherwise x send friend request yNote x send request y y necessarily send request x also person send friend request themselfreturn total number friend request Example 1input age 1616output 2explanation 2 people friend request otherexample 2input age 161718output 2explanation Friend request 17 16 18 17example 3input age 2030100110120output 3explanation Friend request 110 100 120 110 120 100 Constraintsn ageslength1 n 2 1041 agesi 120
0array
you n job m worker you give array difficulty profit worker wheredifficultyi profiti difficulty profit ith job andworkerj ability jth worker ie jth worker complete job difficulty workerjevery worker assign job job complete multiple timesFor example worker attempt job pay 1 total profit 3 if worker complete job profit 0return maximum profit achieve assign worker job example 1input difficulty 246810 profit 1020304050 worker 4567output 100explanation Workers assign job difficulty 4466 profit 20203030 separatelyExample 2input difficulty 854757 profit 246699 worker 402525output 0 Constraintsn difficultylengthn profitlengthm workerlength1 n m 1041 difficultyi profiti workeri 105
0array
let define function countuniquecharss return number unique character sFor example call countuniquecharss s LEETCODE l t c o d unique character appear s countuniquecharss 5given string s return sum countUniqueCharst t substre s the test case generate answer fit 32bit integerNotice substring repeat case count repeat one Example 1input s abcoutput 10explanation all possible substring ABCABBC ABCEvery substre compose unique letterssum length substre 1 1 1 2 2 3 10example 2input s abaoutput 8explanation the example 1 countuniquecharsaba 1example 3input s LEETCODEOutput 92 Constraints1 slength 105s consist uppercase english letter
2string
in string s lowercase letter letter form consecutive group characterfor example string like s abbxxxxzyy group bb xxxx z yyA group identify interval start end start end denote start end index inclusive group in example xxxx interval 36a group consider large 3 charactersreturn interval large group sort increase order start index Example 1input s abbxxxxzzyoutput 36explanation xxxx large group start index 3 end index 6Example 2Input s abcoutput Explanation we group b c large groupsExample 3input s abcdddeeeeaabbbcdoutput 35691214explanation the large group ddd eeee bbb Constraints1 slength 1000 contain lowercase english letter
2string
you give personal information string s represent email address phone number Return mask personal information rulesemail addressan email address isA consist uppercase lowercase english letter follow bythe symbol follow bythe domain consist uppercase lowercase english letter dot middle characterTo mask emailthe uppercase letter domain convert lowercase lettersthe middle letter ie letter replace 5 asterisk Phone numbera phone number format followsThe phone number contain 1013 digitsThe 10 digits local numberthe remain 03 digit begin country codeseparation character set separate digit wayTo mask phone numberremove separation charactersThe mask phone number formxxxx country code 0 digitsxxxx country code 1 digitXXXX country code 2 digitsxxxx country code 3 digitsxxxx 4 digits local number example 1input s leetcodeleetcodecomoutput leleetcodecomexplanation s email addressthe domain convert lowercase middle replace 5 asterisksExample 2input s ABqqcomOutput abqqcomexplanation s email addressthe domain convert lowercase middle replace 5 asterisksNote ab 2 character 5 asterisk middleExample 3input s 1234567890output 7890explanation s phone numberthere 10 digit local number 10 digit country code 0 digitsthu result mask number 7890 Constraintss valid email phone numberIf s email8 slength 40s consist uppercase lowercase english letter exactly symbol symbolIf s phone number10 slength 20s consist digits space symbol
2string
give n x n binary matrix image flip image horizontally invert return result imageto flip image horizontally mean row image reversedFor example flip 110 horizontally result 011to invert image mean 0 replace 1 1 replace 0for example invert 011 result 100 example 1input image 110101000output 100010111explanation first reverse row 011101000then invert image 100010111example 2input image 1100100101111010output 1100011000011010explanation first reverse row 0011100111100101then invert image 1100011000011010 Constraintsn imagelengthn imageilength1 n 20imagesij 0 1
0array
there undirecte connected tree n node label 0 n 1 n 1 edgesYou give integer n array edge edgesi ai bi indicate edge node ai bi treeReturn array answer length n answeri sum distance ith node tree nod Example 1input n 6 edge 0102232425output 8126101010explanation the tree show aboveWe dist01 dist02 dist03 dist04 dist05equal 1 1 2 2 2 8hence answer0 8 onexample 2input n 1 edge output 0example 3input n 2 edge 10output 11 Constraints1 n 3 104edgeslength n 1edgesilength 20 ai bi nai biThe give input represent valid tree
1graph
you give image img1 img2 represent binary square matrices size n x n a binary matrix 0s 1s valuesWe translate image choose slide 1 bit leave right andor number unit we place image we calculate overlap count number position 1 imagesnote translation include kind rotation any 1 bit translate outside matrix border erasedreturn large possible overlap Example 1input img1 110010010 img2 000011001output 3explanation we translate img1 right 1 unit 1 unitthe number position 1 image 3 show redexample 2input img1 1 img2 1output 1Example 3input img1 0 img2 0output 0 Constraintsn img1length img1ilengthn img2length img2ilength1 n 30img1ij 0 1img2ij 0 1
0array
there n domino line place domino vertically upright in beginning simultaneously push domino leave rightAfter second domino fall leave push adjacent domino leave Similarly domino fall right push adjacent domino stand rightWhen vertical domino dominoe fall side stay balance forcesFor purpose question consider fall domino expend additional force fall fallen dominoYou give string domino represent initial state wheredominoesi L ith domino push leftdominoesi R ith domino push right anddominoesi ith domino pushedReturn string represent final state Example 1input domino RRLOutput RRLExplanation the domino expend additional force second dominoexample 2input domino lrlrloutput LLRRLLRRLL Constraintsn dominoeslength1 n 105dominoesi L R
2string
a 3 x 3 magic square 3 x 3 grid fill distinct number 1 9 row column diagonal sumgiven row x col grid integer 3 x 3 magic square subgrid each subgrid contiguous Example 1input grid 438495192762output 1explanation the follow subgrid 3 x 3 magic squarewhile notin total magic square inside give gridexample 2input grid 8output 0 Constraintsrow gridlengthcol gridilength1 row col 100 gridij 15
0array
there n room label 0 n 1 room lock room 0 your goal visit room however enter locked room have keywhen visit room find set distinct key each key number denoting room unlock unlock roomsGiven array room roomsi set key obtain visit room return true visit room false Example 1input room 123output trueexplanation we visit room 0 pick key 1we visit room 1 pick key 2we visit room 2 pick key 3we visit room 3since able visit room return trueExample 2input room 1330120output falseexplanation we enter room number 2 key unlock room Constraintsn roomslength2 n 10000 roomsilength 10001 sumroomsilength 30000 roomsij nAll value roomsi unique
1graph
you give string digit num 123456579 we split fibonaccilike sequence 123 456 579formally fibonaccilike sequence list f nonnegative integer that0 fi 231 integer fit 32bit sign integer typeflength 3 andfi fi 1 fi 2 0 flength 2note splitting string piece piece extra lead zeroes piece number 0 itselfreturn fibonaccilike sequence split num return Example 1input num 1101111output 1101111explanation the output 110 1 111 acceptedExample 2input num 112358130output Explanation the task impossibleExample 3input num 0123output Explanation Leading zero allow 01 2 3 valid Constraints1 numlength 200num contain digit
2string
give string s t return true equal type text editor mean backspace characternote backspace text text continue Example 1input s abc t adcoutput trueexplanation both s t acExample 2Input s ab t cdoutput trueexplanation both s t Example 3input s ac t bOutput falseexplanation s c t b constraints1 slength tlength 200s t contain lowercase letter character follow can solve on time O1 space
2string
you recall array arr mountain array ifarrlength 3There exist index 0indexe 0 arrlength 1 thatarr0 arr1 arri 1 arriarri arri 1 arrarrlength 1given integer array arr return length long subarray mountain Return 0 mountain subarray Example 1input arr 2147325output 5explanation the large mountain 14732 length 5Example 2input arr 222output 0explanation there mountain Constraints1 arrlength 1040 arri 104 Follow upcan solve passcan solve o1 space
0array
alice number card want rearrange card group group size groupsize consist groupsize consecutive cardsGiven integer array hand handi value write ith card integer groupsize return true rearrange card false example 1input hand 123623478 groupsize 3output trueexplanation alice hand rearrange 123234678example 2input hand 12345 groupsize 4output falseexplanation alice hand rearrange group 4 Constraints1 handlength 1040 handi 1091 groupsize handlength note this question 1296 httpsleetcodecomproblemsdividearrayinsetsofkconsecutivenumber
0array
you undirecte connect graph n node label 0 n 1 you give array graph graphi list node connect node edgeReturn length short path visit node you start stop node revisit node multiple time reuse edge Example 1input graph 123000output 4explanation one possible path 10203example 2input graph 1024134212output 4explanation one possible path 01423 Constraintsn graphlength1 n 120 graphilength ngraphi contain iif grapha contain b graphb contain aThe input graph connect
1graph
you give array represent row seat seatsi 1 represent person sit ith seat seatsi 0 represent ith seat 0indexedthere seat person sittingAlex want sit seat distance close person maximize return maximum distance close person Example 1input seat 1000101output 2explanation if Alex sit second open seat ie seats2 close person distance 2if Alex sit open seat close person distance 1thus maximum distance close person 2example 2input seat 1000output 3explanation if Alex sit seat ie seats3 close person 3 seat awaythis maximum distance possible answer 3example 3input seat 01output 1 constraints2 seatslength 2 104seatsi 0 1at seat emptyAt seat occupy
0array
you give 2D array axisaligne rectangle each rectanglei xi1 yi1 xi2 yi2 denote ith rectangle xi1 yi1 coordinate bottomleft corner xi2 yi2 coordinate topright cornercalculate total area cover rectangle plane any area cover rectangle count oncereturn total area since answer large return modulo 109 7 Example 1input rectangle 002210231031output 6explanation a total area 6 cover rectangle illustrate pictureFrom 11 22 green red rectangle overlapfrom 10 23 rectangle overlapexample 2input rectangle 0010000000001000000000output 49explanation the answer 1018 modulo 109 7 49 Constraints1 rectangleslength 200rectangesilength 40 xi1 yi1 xi2 yi2 109
0array
an array arr mountain follow property holdarrlength 3There exist 0 arrlength 1 thatarr0 arr1 arri 1 arriarri arri 1 arrarrlength 1given mountain array arr return index arr0 arr1 arri 1 arri arri 1 arrarrlength 1you solve Ologarrlength time complexity Example 1input arr 010Output 1example 2input arr 0210output 1example 3input arr 01052output 1 constraints3 arrlength 1050 arri 106arr guarantee mountain array
0array
there n car go destination onelane road the destination target mile awayyou give integer array position speed length n positioni position ith car speedi speed ith car mile houra car pass car ahead catch drive bumper bumper speed the fast car slow match slow car speed the distance car ignore ie assume positiona car fleet nonempty set car drive position speed note single car car fleetIf car catch car fleet right destination point consider car fleetreturn number car fleet arrive destination Example 1input target 12 position 108053 speed 24113output 3explanationthe car start 10 speed 2 8 speed 4 fleet meet 12the car start 0 catch car fleet itselfthe car start 5 speed 1 3 speed 3 fleet meeting 6 the fleet move speed 1 reach targetnote car meet fleet destination answer 3example 2input target 10 position 3 speed 3output 1explanation there car fleetExample 3input target 100 position 024 speed 421output 1explanationthe car start 0 speed 4 2 speed 2 fleet meeting 4 the fleet move speed 2then fleet speed 2 car start 4 speed 1 fleet meeting 6 the fleet move speed 1 reach target Constraintsn positionlength speedlength1 n 1050 target 1060 positioni targetall value position unique0 speedi 106
0array
give balanced parenthese string s return score stringthe score balanced parenthese string base follow rule score 1ab score A B A b balance parenthese stringsA score 2 a a balanced parenthese stre Example 1input s output 1example 2input s output 2example 3input s output 2 constraints2 slength 50 consist s balanced parenthese string
2string
there n worker you give integer array quality wage qualityi quality ith worker wagei minimum wage expectation ith workerWe want hire exactly k worker form pay group to hire group k worker pay accord follow rulesevery worker pay group pay ratio quality compare worker pay groupevery worker pay group pay minimum wage expectationGiven integer k return money need form pay group satisfy condition Answers 105 actual answer accept Example 1input quality 10205 wage 705030 k 2output 10500000explanation we pay 70 0th worker 35 2nd workerExample 2input quality 3110101 wage 48227 k 3output 3066667explanation we pay 4 0th worker 1333333 2nd 3rd worker separately constraintsn qualitylength wagelength1 k n 1041 qualityi wagei 104
0array
give string s goal return true swap letter s result equal goal return falseswappe letter define take index j 0indexed j swap character si sjFor example swap index 0 2 abcd result cbad Example 1input s ab goal baOutput trueexplanation you swap s0 s1 b ba equal goalexample 2Input s ab goal abOutput falseexplanation the letter swap s0 s1 b result ba goalExample 3input s aa goal aaoutput trueexplanation you swap s0 s1 aa equal goal Constraints1 slength goallength 2 104s goal consist lowercase letter
2string
at lemonade stand lemonade cost 5 customer stand queue buy order time order specify bill each customer buy lemonade pay 5 10 20 bill you provide correct change customer net transaction customer pay 5note change hand firstgiven integer array bill billsi bill ith customer pay return true provide customer correct change false Example 1input bill 5551020output trueexplanation from 3 customer collect 5 bill orderfrom fourth customer collect 10 bill 5from fifth customer 10 bill 5 billsince customer get correct change output trueExample 2input bill 55101020output falseexplanation from customer order collect 5 billsFor customer order collect 10 bill 5 billfor customer change 15 10 billssince customer receive correct change answer false Constraints1 billslength 105billsi 5 10 20
0array
you give m x n binary matrix gridA consist choose row column toggle value row column ie change 0s 1s 1s 0sEvery row matrix interpret binary number score matrix sum numbersReturn high possible score make number move include zero move Example 1input grid 001110101100output 39explanation 0b1111 0b1001 0b1111 15 9 15 39example 2input grid 0output 1 Constraintsm gridlengthn gridilength1 m n 20gridij 0 1
0array
give integer array num integer k return length shortest nonempty subarray num sum k if subarray return 1A subarray contiguous array Example 1input num 1 k 1Output 1Example 2input num 12 k 4Output 1Example 3input num 212 k 3output 3 Constraints1 numslength 105105 numsi 1051 k 109
0array
give root binary tree value target node target integer k return array value nodes distance k target nodeyou return answer order Example 1input root 3516208nullnull74 target 5 k 2output 741explanation the node distance 2 target node value 5 value 7 4 1example 2input root 1 target 1 k 3output ConstraintsThe number nod tree range 1 5000 Nodeval 500All value Nodeval uniquetarget value nod tree0 k 1000
1graph
give root binary tree depth node short distance rootReturn small subtree contain deep node original treeA node call deep large depth possible node entire treethe subtree node tree consist node plus set descendant node Example 1input root 3516208nullnull74output 274explanation we return node value 2 colored yellow diagramThe node colour blue deep node treenotice nod 5 3 2 contain deep node tree node 2 small subtree return itexample 2input root 1output 1explanation the root deep node treeExample 3input root 013null2output 2explanation the deep node tree 2 valid subtree subtree nod 2 1 0 subtree node 2 small ConstraintsThe number nod tree range 1 5000 Nodeval 500The value nod tree unique Note this question 1123 httpsleetcodecomproblemslowestcommonancestorofdeepestleave
1graph
give 2D integer array matrix return transpose matrixThe transpose matrix matrix flip main diagonal switching matrixs row column index example 1input matrix 123456789output 147258369example 2input matrix 123456output 142536 Constraintsm matrixlengthn matrixilength1 m n 10001 m n 105109 matrixij 109
0array
you give integer array nums1 nums2 length the advantage nums1 respect nums2 number index nums1i nums2iReturn permutation nums1 maximize advantage respect nums2 example 1input nums1 271115 nums2 110411output 211715example 2input nums1 1224832 nums2 13253211Output 2432812 Constraints1 nums1length 105nums2length nums1length0 nums1i nums2i 109
0array
a car travel start position destination target mile east start positionthere gas station way the gas station represent array station stationsi positioni fueli indicate ith gas station positioni mile east start position fueli liter gasThe car start infinite tank gas initially startfuel liter fuel it use liter gas mile drive when car reach gas station stop refuel transfer gas station carreturn minimum number refueling stop car order reach destination if reach destination return 1note car reach gas station 0 fuel leave car refuel if car reach destination 0 fuel leave consider arrive Example 1input target 1 startFuel 1 station output 0explanation we reach target refuelingexample 2input target 100 startFuel 1 station 10100output 1explanation we reach target gas stationExample 3input target 100 startFuel 10 station 1060203030306040output 2explanation we start 10 liter fuelWe drive position 10 expend 10 liter fuel we refuel 0 liter 60 liter gasthen drive position 10 position 60 expend 50 liter fueland refuel 10 liter 50 liter gas we drive reach targetWe 2 refueling stop way return 2 Constraints1 target startFuel 1090 stationslength 5001 positioni positioni1 target1 fueli 109
0array
consider leave binary tree leave right order value leave form leaf value sequenceFor example give tree leaf value sequence 6 7 4 9 8two binary tree consider leafsimilar leaf value sequence samereturn true give tree head node root1 root2 leafsimilar Example 1input root1 3516298nullnull74 root2 3516742nullnullnullnullnullnull98output trueExample 2input root1 123 root2 132output false ConstraintsThe number nod tree range 1 200both give tree value range 0 200
1graph
a sequence x1 x2 xn fibonaccilike ifn 3xi xi1 xi2 2 nGiven strictly increase array arr positive integer form sequence return length long fibonaccilike subsequence arr if exist return 0A subsequence derive sequence arr delete number element include arr change order remain element for example 3 5 8 subsequence 3 4 5 6 7 8 Example 1input arr 12345678output 5explanation the long subsequence fibonaccilike 12358example 2input arr 13711121418output 3explanation the long subsequence fibonaccilike 11112 31114 71118 Constraints3 arrlength 10001 arri arri 1 109
0array
a robot infinite XYplane start point 0 0 face north the robot receive sequence possible type commands2 turn leave 90 degrees1 turn right 90 degrees1 k 9 move forward k unit unit timeSome grid square obstacle the ith obstacle grid point obstaclesi xi yi if robot run obstacle instead stay current location commandreturn maximum euclidean distance robot get origin square ie distance 5 return 25notenorth mean Y directioneast mean X directionsouth mean Y directionwest mean x direction Example 1input command 413 obstacle output 25explanation the robot start 0 01 move north 4 unit 0 42 turn right3 move east 3 unit 3 4the furthest point robot get origin 3 4 square 32 42 25 unit awayexample 2input command 41424 obstacle 24output 65explanation the robot start 0 01 move north 4 unit 0 42 turn right3 move east 1 unit block obstacle 2 4 robot 1 44 Turn left5 move north 4 unit 1 8the furthest point robot get origin 1 8 square 12 82 65 unit awayexample 3input command 6116 obstacle output 36explanation the robot start 0 01 move north 6 unit 0 62 turn right3 turn right4 move south 6 unit 0 0the furth point robot get origin 0 6 square 62 36 unit away Constraints1 commandslength 104commandsi 2 1 integer range 1 90 obstacleslength 1043 104 xi yi 3 104the answer guarantee 231
0array
Koko love eat banana there n pile banana ith pile pilesi banana the guard gone come h hourskoko decide bananasperhour eat speed k each hour choose pile banana eat k banana pile if pile k banana eat instead eat banana hourkoko like eat slowly want finish eat banana guard returnreturn minimum integer k eat banana h hour Example 1input pile 36711 h 8output 4Example 2input pile 301123420 h 5output 30Example 3input pile 301123420 h 6output 23 Constraints1 pileslength 104pileslength h 1091 pilesi 109
0array
Alice Bob play game pile stone there number pile arrange row pile positive integer number stone pilesithe objective game end stone the total number stone pile odd tiesalice Bob turn Alice start each turn player take entire pile stone begin end row this continue pile leave point person stone winsassume Alice Bob play optimally return true Alice win game false Bob win Example 1input pile 5345output trueexplanation Alice start 5 5say take 5 row 3 4 5if Bob take 3 board 4 5 Alice take 5 win 10 pointsif Bob take 5 board 3 4 Alice take 4 win 9 pointsthis demonstrate take 5 win Alice return trueexample 2input pile 3723output true constraints2 pileslength 500pileslength even1 pilesi 500sumpilesi odd
0array
there group n member list crime commit the ith crime generate profiti require groupi member participate if member participate crime member can not participate crimelet profitable scheme subset crime generate minprofit profit total number member participate subset crime nreturn number scheme choose since answer large return modulo 109 7 Example 1input n 5 minprofit 3 group 22 profit 23output 2explanation to profit 3 group commit crime 0 1 crime 1in total 2 schemesExample 2input n 10 minprofit 5 group 235 profit 678output 7explanation to profit 5 group commit crime long commit onethere 7 possible scheme 0 1 2 01 02 12 012 constraints1 n 1000 minProfit 1001 grouplength 1001 groupi 100profitlength grouplength0 profiti 100
0array