question
stringlengths
58
4.29k
label
class label
3 classes
give root binary tree return leftmost value row tree Example 1input root 213output 1example 2input root 1234null56nullnull7output 7 ConstraintsThe number nod tree range 1 104231 Nodeval 231 1
1graph
give root binary tree return array large value row tree 0indexed example 1input root 13253null9output 139example 2input root 123output 13 ConstraintsThe number nod tree range 0 104231 Nodeval 231 1
1graph
give string s find long palindromic subsequence length sa subsequence sequence derive sequence delete element change order remain element Example 1input s bbbaboutput 4explanation one possible long palindromic subsequence bbbbexample 2input s cbbdOutput 2explanation one possible long palindromic subsequence bb Constraints1 slength 1000 consists lowercase english letter
2string
you n super washing machine line initially wash machine dress emptyfor choose m 1 m n washing machine pass dress washing machine adjacent washing machine timeGiven integer array machine represent number dress washing machine leave right line return minimum number move washing machine number dress if possible return 1 example 1input machine 105output 3Explanation1st 1 0 5 1 1 42nd 1 1 4 2 1 33rd 2 1 3 2 2 2example 2input machine 030output 2explanation1st 0 3 0 1 2 02nd 1 2 0 1 1 1example 3input machine 020output 1explanationits impossible washing machine number dress Constraintsn machineslength1 n 1040 machinesi 105
0array
you give integer array coin represent coin different denomination integer represent total moneyreturn number combination if money combination coin return 0you assume infinite number kind coinThe answer guarantee fit sign 32bit integer Example 1Input 5 coin 125output 4explanation way amount55522152111511111example 2input 3 coin 2output 0explanation 3 coin 2example 3input 10 coin 10output 1 Constraints1 coinslength 3001 coinsi 5000all value coin unique0 5000
0array
we define usage capital word right follow case holdsall letter word capital like USAAll letter word capital like leetcodeonly letter word capital like GoogleGiven string word return true usage capital right example 1input word USAOutput trueExample 2input word flagoutput false constraints1 wordlength 100word consist lowercase uppercase english letter
2string
give string b return length long uncommon subsequence b if long uncommon subsequence exist return 1an uncommon subsequence string string subsequence othera subsequence stre s string obtain delete number character sFor example abc subsequence aebdc delete underlined character aebdc abc other subsequence aebdc include aebdc aeb string Example 1input aba b cdcOutput 3explanation one long uncommon subsequence aba aba subsequence aba cdcNote cdc long uncommon subsequenceExample 2input aaa b bbbOutput 3explanation the long uncommon subsequence aaa bbbexample 3input aaa b aaaoutput 1explanation every subsequence stre subsequence string b similarly subsequence stre b subsequence stre Constraints1 alength blength 100a b consist lowercase english letter
2string
give integer array num integer k return true num good subarray false otherwisea good subarray subarray whereit length andthe sum element subarray multiple kNote thatA subarray contiguous arrayAn integer x multiple k exist integer n x n k 0 multiple k Example 1input num 232467 k 6output trueExplanation 2 4 continuous subarray size 2 element sum 6Example 2input num 232647 k 6output trueexplanation 23 2 6 4 7 continuous subarray size 5 element sum 4242 multiple 6 42 7 6 7 integerExample 3input num 232647 k 13output false Constraints1 numslength 1050 numsi 1090 sumnumsi 231 11 k 231 1
0array
give binary array num return maximum length contiguous subarray equal number 0 1 Example 1input num 01output 2explanation 0 1 long contiguous subarray equal number 0 1example 2input num 010output 2explanation 0 1 1 0 long contiguous subarray equal number 0 1 constraints1 numslength 105numsi 0 1
0array
suppose n integer label 1 n a permutation n integer perm 1indexed consider beautiful arrangement 1 n follow truepermi divisible ii divisible permiGiven integer n return number beautiful arrangement construct Example 1input n 2output 2explanation the beautiful arrangement 12 perm1 1 divisible 1 perm2 2 divisible 2the second beautiful arrangement 21 perm1 2 divisible 1 2 divisible perm2 1example 2Input n 1output 1 Constraints1 n 15
0array
give root Binary Search Tree BST return minimum absolute difference value different node tree example 1input root 42613output 1example 2input root 1048nullnull1249output 1 ConstraintsThe number nod tree range 2 1040 Nodeval 105 note this question 783 httpsleetcodecomproblemsminimumdistancebetweenbstnode
1graph
give array integer num integer k return number unique kdiff pair arrayA kdiff pair integer pair numsi numsj follow true0 j numslengthi jnumsi numsj kNotice val denote absolute value val Example 1input num 31415 k 2output 2explanation there 2diff pair array 1 3 3 5although 1s input return number unique pairsExample 2input num 12345 k 1Output 4explanation there 1diff pair array 1 2 2 3 3 4 4 5example 3input num 13154 k 0output 1explanation there 0diff pair array 1 1 constraints1 numslength 104107 numsi 1070 k 107
0array
note this companion problem System design problem Design tinyurltinyurl url shortening service enter url httpsleetcodecomproblemsdesigntinyurl return short URL httptinyurlcom4e9iAk Design class encode URL decode tiny URLThere restriction encodedecode algorithm work you need ensure url encode tiny url tiny url decode original URLImplement Solution classsolution initialize object systemstring encodestre longUrl return tiny url give longurlstre decodestre shorturl return original long url give shortUrl it guarantee give shortUrl encode object Example 1input url httpsleetcodecomproblemsdesigntinyurloutput httpsleetcodecomproblemsdesigntinyurlexplanationsolution obj new Solutionstring tiny objencodeurl return encode tiny urlstring an objdecodetiny return original url deconde Constraints1 urllength 104url gurantee valid url
2string
a complex number represent string form realimaginaryi wherereal real integer range 100 100imaginary imaginary integer range 100 100i2 1given complex number num1 num2 string return stre complex number represent multiplication example 1input num1 11i num2 11ioutput 02iexplanation 1 1 1 i2 2 2i need convert form 02iexample 2input num1 11i num2 11ioutput 02iexplanation 1 1 1 i2 2 2i need convert form 02i Constraintsnum1 num2 valid complex number
2string
give root Binary Search Tree BST convert Greater Tree key original BST change original key plus sum key great original key bsta reminder binary search tree tree satisfie constraintsthe 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 4160257nullnullnull3nullnullnull8Output 30362136352615nullnullnull33nullnullnull8example 2input root 0null1output 1null1 constraintsthe number nod tree range 0 104104 Nodeval 104All value tree uniqueroot guarantee valid binary search tree note this question 1038 httpsleetcodecomproblemsbinarysearchtreetogreatersumtree
1graph
you give sorted array consist integer element appear exactly twice element appear exactly oncereturn single element appear onceyour solution run Olog n time o1 space Example 1input num 112334488output 2Example 2input num 3377101111output 10 Constraints1 numslength 1050 numsi 105
0array
give string s integer k reverse k character 2k character count start stringif few k character leave reverse if 2k greater equal k character reverse k character leave original Example 1input s abcdefg k 2output bacdfegExample 2input s abcd k 2output bacd Constraints1 slength 104s consist lowercase english letters1 k 104
2string
give root binary tree return length diameter treethe diameter binary tree length long path node tree this path pass rootthe length path node represent number edge Example 1input root 12345output 3explanation 3 length path 4213 5213example 2input root 12Output 1 ConstraintsThe number nod tree range 1 104100 Nodeval 100
1graph
you give box different color represent different positive numbersYou experience round remove box box leave each time choose continuous box color ie compose k box k 1 remove k k pointsreturn maximum point example 1input box 132223431output 23explanation1 3 2 2 2 3 4 3 1 1 3 3 4 3 1 339 point 1 3 3 3 1 111 point 1 1 339 point 224 pointsExample 2input box 111output 9example 3input box 1output 1 Constraints1 boxeslength 1001 boxesi 100
0array
there n city some connect if city connect directly city b city b connect directly city c city connect indirectly city cA province group directly indirectly connect city city outside groupyou give n x n matrix isconnecte isConnectedij 1 ith city jth city directly connect isConnectedij 0 otherwisereturn total number province Example 1input isconnecte 110110001output 2example 2input isconnecte 100010001output 3 Constraints1 n 200n isConnectedlengthn isconnectedilengthisconnectedij 1 0isconnectedii 1isconnectedij isconnectedji
1graph
you give string s represent attendance record student character signify student absent late present day the record contain follow charactersA AbsentL LateP PresentThe student eligible attendance award meet follow criteriathe student absent a strictly few 2 day totalthe student late L 3 consecutive daysreturn true student eligible attendance award false Example 1input s PPALLPOutput trueexplanation the student few 2 absence late 3 consecutive daysExample 2input s PPALLLOutput falseexplanation the student late 3 consecutive day 3 day eligible award Constraints1 slength 1000si A L p
2string
you give integer array num the adjacent integer num perform float divisionfor example num 234 evaluate expression 234however add number parenthesis position change priority operation you want add parenthesis value expression evaluation maximumreturn corresponding expression maximum value string formatnote expression contain redundant parenthesis Example 1input num 1000100102output 1000100102explanation 1000100102 1000100102 200however bold parenthesis 1000100102 redundant influence operation prioritySo return 1000100102other cases1000100102 501000100102 501000100102 051000100102 2example 2input num 234output 234explanation 234 83 2667it show try possibility expression evaluation great 2667 Constraints1 numslength 102 numsi 1000there optimal division give input
0array
there rectangular brick wall n row brick the ith row number brick height ie unit different width the total width row samedraw vertical line cross brick if line go edge brick brick consider cross you draw line vertical edge wall case line obviously cross bricksGiven 2D array wall contain information wall return minimum number cross brick draw vertical line Example 1input wall 1221312132243121311output 2example 2input wall 111output 3 Constraintsn walllength1 n 1041 wallilength 1041 sumwallilength 2 104sumwalli row i1 wallij 231 1
0array
give positive integer n find small integer exactly digit exist integer n great value n if positive integer exist return 1note return integer fit 32bit integer valid answer fit 32bit integer return 1 Example 1input n 12output 21example 2input n 21output 1 Constraints1 n 231 1
2string
give string s reverse order character word sentence preserve whitespace initial word order Example 1input s Lets LeetCode contestoutput stel ekat edoCteeL tsetnocExample 2input s God DingOutput doG gniD constraints1 slength 5 104s contain printable ASCII characterss contain lead trail spacesthere word sall word s separate single space
2string
give nary tree find maximum depththe maximum depth number nod long path root node farth leaf nodenarytree input serialization represent level order traversal group child separate null value see example example 1input root 1null324null56output 3example 2input root 1null2345nullnull67null8null910nullnull11null12null13nullnull14output 5 ConstraintsThe total number node range 0 104the depth nary tree equal 1000
1graph
give array integer num integer k return total number subarray sum equal kA subarray contiguous nonempty sequence element array Example 1input num 111 k 2output 2example 2input num 123 k 3output 2 Constraints1 numslength 2 1041000 numsi 1000107 k 107
0array
give integer array num 2n integer group integer n pair a1 b1 a2 b2 bn sum minai bi maximize Return maximized sum Example 1input num 1432output 4explanation all possible pairing ignore order element are1 1 4 2 3 min1 4 min2 3 1 2 32 1 3 2 4 min1 3 min2 4 1 2 33 1 2 3 4 min1 2 min3 4 1 3 4so maximum possible sum 4example 2input num 626512output 9explanation the optimal pair 2 1 2 5 6 6 min2 1 min2 5 min6 6 1 2 6 9 Constraints1 n 104numslength 2 n104 numsi 104
0array
give root binary tree return sum tree node tiltthe tilt tree node absolute difference sum leave subtree node value right subtree node value if node leave child sum leave subtree node value treat 0 the rule similar node right child Example 1input root 123output 1explanation Tilt node 2 00 0 childrenTilt node 3 00 0 childrenTilt node 1 23 1 leave subtree leave child sum 2 right subtree right child sum 3sum tilt 0 0 1 1example 2input root 42935null7output 15explanation Tilt node 3 00 0 childrenTilt node 5 00 0 childrenTilt node 7 00 0 childrenTilt node 2 35 2 leave subtree leave child sum 3 right subtree right child sum 5Tilt node 9 07 7 leave child sum 0 right subtree right child sum 7Tilt node 4 35297 1016 6 leave subtree value 3 5 2 sum 10 right subtree value 9 7 sum 16sum tilt 0 0 0 2 7 6 15example 3input root 21714112233output 9 ConstraintsThe number nod tree range 0 1041000 Nodeval 1000
1graph
give string n represent integer return close integer include palindrome if tie return small onethe close define absolute difference minimized integer Example 1input n 123output 121Example 2input n 1output 0explanation 0 2 close palindrome return small 0 Constraints1 nlength 18n consist digitsn lead zerosn represent integer range 1 1018 1
2string
in MATLAB handy function call reshape reshape m x n matrix new different size r x c keep original datayou give m x n matrix mat integer r c represent number row number column want reshape matrixthe reshaped matrix fill element original matrix rowtraverse order wereif reshape operation give parameter possible legal output new reshaped matrix Otherwise output original matrix Example 1input mat 1234 r 1 c 4output 1234example 2input mat 1234 r 2 c 4output 1234 Constraintsm matlengthn matilength1 m n 1001000 matij 10001 r c 300
0array
give string s1 s2 return true s2 contain permutation s1 false otherwisein word return true s1s permutation substre s2 Example 1input s1 ab s2 eidbaoooOutput trueExplanation s2 contain permutation s1 baexample 2input s1 ab s2 eidboaoooutput false Constraints1 s1length s2length 104s1 s2 consist lowercase english letter
2string
Alice n candy ith candy type candyTypei Alice notice start gain weight visit doctorthe doctor advise Alice eat n 2 candy n Alice like candy want eat maximum number different type candy follow doctor advicegiven integer array candytype length n return maximum number different type candy eat eat n 2 Example 1input candyType 112233output 3explanation Alice eat 6 2 3 candy since 3 type eat typeexample 2input candytype 1123output 2explanation Alice eat 4 2 2 candy whether eat type 12 13 23 eat 2 different typesExample 3input candyType 6666output 1explanation Alice eat 4 2 2 candy even eat 2 candy 1 type Constraintsn candytypelength2 n 104n even105 candyTypei 105
0array
give integer array num need find continuous subarray sort subarray ascend order array sort ascend orderreturn short subarray output length Example 1input num 264810915output 5explanation you need sort 6 4 8 10 9 ascending order array sort ascend orderexample 2input num 1234output 0example 3input num 1output 0 Constraints1 numslength 104105 numsi 105 Follow can solve on time complexity
0array
give string word1 word2 return minimum number step require word1 word2 sameIn step delete exactly character string Example 1input word1 sea word2 eatoutput 2explanation you need step sea ea step eat eaexample 2input word1 leetcode word2 etcooutput 4 constraints1 word1length word2length 500word1 word2 consist lowercase english letter
2string
you give array tree treesi xi yi represent location tree gardenyou ask fence entire garden minimum length rope expensive the garden fence tree enclosedreturn coordinate tree exactly locate fence perimeter Example 1input point 112220243342output 1120332442example 2input point 122242output 422212 Constraints1 pointslength 3000pointsilength 20 xi yi 100all give point unique
0array
give root nary tree return preorder traversal node valuesNaryTree input serialization represent level order traversal each group child separate null value see example example 1input root 1null324null56output 135624example 2input root 1null2345nullnull67null8null910nullnull11null12null13nullnull14output 1236711144812591310 ConstraintsThe number nod tree range 0 1040 Nodeval 104the height nary tree equal 1000 Follow Recursive solution trivial iteratively
1graph
give root nary tree return postorder traversal node valuesNaryTree input serialization represent level order traversal each group child separate null value see example example 1input root 1null324null56output 563241example 2input root 1null2345nullnull67null8null910nullnull11null12null13nullnull14output 2614117312841391051 ConstraintsThe number nod tree range 0 1040 Nodeval 104the height nary tree equal 1000 Follow Recursive solution trivial iteratively
1graph
give string represent code snippet implement tag validator parse code return validA code snippet valid follow rule holdthe code wrap valid closed tag otherwise code invalida close tag necessarily valid exactly follow format TAG_NAMETAG_CONTENTTAG_NAME among tag_name start tag tag_name end tag the tag_name start end tag a closed tag valid tag_name tag_content valida valid tag_name contain uppercase letter length range 19 otherwise tag_name invalida valid tag_content contain valid close tag cdata character note1 EXCEPT unmatched unmatched start end tag unmatched close tag invalid TAG_NAME otherwise tag_content invalida start tag unmatched end tag exist tag_name vice versa however need consider issue unbalanced tag nestedA unmatched find subsequent and find subsequent character parse tag_name necessarily validthe cdata follow format cdatacdata_content the range CDATA_CONTENT define character cdata subsequent cdata_content contain character the function cdata forbid validator parse cdata_content character parse tag matter valid invalid treat regular character example 1input code divthis line cdatadivdivoutput trueexplanation the code wrap closed tag DIV DIV the tag_name valid tag_content consist character cdata although CDATA_CONTENT unmatched start tag invalid TAG_NAME consider plain text parse tagso tag_content valid code valid thus return trueExample 2input code DIV cdata cdatadivdivoutput trueExplanationWe separate code start_tagtag_contentend_tagstart_tag divend_tag DIVtag_content separate text1cdatatext2text1 cdata cdata CDATAdiv cdata_content divtext2 the reason start_tag not DIV rule 6the reason cdata not CDATAdiv rule 7Example 3input code A B a boutput falseexplanation unbalance if a closed b unmatched vice versa Constraints1 codelength 500code consist english letter digit
2string
give string expression represent expression fraction addition subtraction return calculation result string formatthe final result irreducible fraction if final result integer change format fraction denominator 1 so case 2 convert 21 Example 1input expression 1212output 01example 2input expression 121213output 13example 3input expression 1312output 16 ConstraintsThe input string contain 0 9 so outputeach fraction input output format numeratordenominator if input fraction output positive omittedThe input contain valid irreducible fraction numerator denominator fraction range 1 10 if denominator 1 mean fraction actually integer fraction format define abovethe number give fraction range 1 10the numerator denominator final result guarantee valid range 32bit int
2string
we define harmonious array array difference maximum value minimum value exactly 1given integer array num return length long harmonious subsequence possible subsequencesA subsequence array sequence derive array delete element change order remain element Example 1input num 13225237output 5explanation the long harmonious subsequence 32223example 2input num 1234output 2example 3input num 1111output 0 constraints1 numslength 2 104109 numsi 109
0array
you give m x n matrix M initialize 0s array operation op opsi ai bi mean Mxy incremente 0 x ai 0 y bicount return number maximum integer matrix perform operation Example 1input m 3 n 3 op 2233output 4explanation the maximum integer M 2 M so return 4example 2input m 3 n 3 op 223333332233333322333333output 4example 3input m 3 n 3 op Output 9 Constraints1 m n 4 1040 opslength 104opsilength 21 ai m1 bi n
0array
you long flowerbe plot plant however flower plant adjacent plotsGiven integer array flowerbe contain 0s 1s 0 mean 1 mean integer n return n new flower plant flowerbe violating noadjacentflower rule Example 1input flowerbe 10001 n 1output trueExample 2input flowerbe 10001 n 2output false Constraints1 flowerbedlength 2 104flowerbedi 0 1there adjacent flower flowerbed0 n flowerbedlength
0array
give integer array num return number triplet choose array triangle length triangle Example 1input num 2234output 3explanation Valid combination 234 2234 second 2223example 2input num 4234output 4 constraints1 numslength 10000 numsi 1000
0array
you give binary tree root1 root2Imagine cover nod tree overlap you need merge tree new binary tree the merge rule node overlap sum node value new value merge node Otherwise not null node node new treeReturn merge treeNote the merging process start root node tree Example 1input root1 1325 root2 213null4null7output 34554null7example 2input root1 1 root2 12Output 22 ConstraintsThe number nod tree range 0 2000104 Nodeval 104
1graph
give character array task represent task CPU need letter represent different task Tasks order each task unit time for unit time CPU complete task idleHowever nonnegative integer n represent cooldown period task letter array n unit time tasksreturn number unit time CPU finish give task Example 1input task AAABBB n 2output 8explanation A B idle A b idle a BThere 2 unit time tasksexample 2input task AAABBB n 0output 6explanation on case permutation size 6 work n 0aaabbbabababbbbaaaand onexample 3input task AAAAAABCDEFG n 2output 16Explanation one possible solution isA b C a d e a F G a idle idle a idle idle A Constraints1 tasklength 104tasksi uppercase English letterThe integer n range 0 100
0array
design implementation circular queue the circular queue linear data structure operation perform base FIFO First in first Out principle position connect position circle it call Ring BufferOne benefit circular queue use space queue in normal queue queue insert element space queue but circular queue use space store new valuesimplement mycircularqueue classMyCircularQueuek Initializes object size queue kint Front get item queue if queue return 1int Rear get item queue if queue return 1boolean enqueueint value Inserts element circular queue return true operation successfulboolean deQueue Deletes element circular queue return true operation successfulboolean isempty Checks circular queue notboolean isfull Checks circular queue notyou solve problem builtin queue datum structure programming language Example 1inputmycircularqueue enQueue enQueue enQueue enQueue Rear isfull deQueue enQueue rear3 1 2 3 4 4 outputnull true true true false 3 true true true 4explanationmycircularqueue mycircularqueue new MyCircularQueue3myCircularQueueenQueue1 return TruemyCircularQueueenQueue2 return TruemyCircularQueueenQueue3 return TruemyCircularQueueenQueue4 return FalsemyCircularQueueRear return 3mycircularqueueisfull return TruemyCircularQueuedeQueue return TruemyCircularQueueenQueue4 return truemycircularqueuerear return 4 Constraints1 k 10000 value 1000at 3000 call enQueue deQueue Front Rear isEmpty isfull
0array
give root binary tree integer val depth add row node value val give depth depthnote root node depth 1the add rule isgiven integer depth null tree node cur depth depth 1 create tree node value val cur leave subtree root right subtree rootcur original left subtree leave subtree new left subtree rootcur original right subtree right subtree new right subtree rootIf depth 1 mean depth depth 1 create tree node value val new root original tree original tree new root leave subtree Example 1input root 426315 val 1 depth 2output 4112nullnull6315example 2input root 42null31 val 1 depth 3output 42null113nullnull1 ConstraintsThe number nod tree range 1 104the depth tree range 1 104100 Nodeval 100105 val 1051 depth depth tree 1
1graph
give integer array num find number product maximum return maximum product Example 1input num 123output 6Example 2input num 1234output 24example 3input num 123output 6 Constraints3 numslength 1041000 numsi 1000
0array
there n different online course number 1 n you give array course coursesi durationi lastdayi indicate ith course take continuously durationi day finish lastDayiYou start 1st day course simultaneouslyreturn maximum number course Example 1input course 10020020013001000125020003200output 3explanation there totally 4 course 3 course mostFirst 1st course cost 100 day finish 100th day ready course 101st daysecond 3rd course cost 1000 day finish 1100th day ready course 1101st day Third 2nd course cost 200 day finish 1300th day the 4th course take finish 3300th day exceed close dateexample 2input course 12output 1example 3input course 3243output 0 Constraints1 courseslength 1041 durationi lastdayi 104
0array
you k list sort integer nondecrease order find small range include number k listsWe define range b small range c d b d c c b d c example 1input num 4101524260912205182230output 2024explanation List 1 4 10 15 2426 24 range 2024list 2 0 9 12 20 20 range 2024list 3 5 18 22 30 22 range 2024example 2input num 123123123output 11 Constraintsnumslength k1 k 35001 numsilength 50105 numsij 105numsi sort nondecrease order
0array
on singlethreaded cpu execute program contain n function each function unique ID 0 n1function call store stack function start ID push stack function end ID pop stack the function ID stack current function execute each time function start end write log ID start end timestampyou give list log logsi represent ith log message format string function_idstart endtimestamp for example 0start3 mean function function ID 0 start begin timestamp 3 1end2 mean function function ID 1 end end timestamp 2 note function call multiple time possibly recursivelya function exclusive time sum execution time function call program for example function call twice execute 2 time unit execute 1 time unit exclusive time 2 1 3return exclusive time function array value ith index represent exclusive time function ID Example 1input n 2 log 0start01start21end50end6output 34ExplanationFunction 0 start begin time 0 execute 2 unit time reach end time 1Function 1 start begin time 2 execute 4 unit time end end time 5function 0 resume execution begin time 6 execute 1 unit timeSo function 0 spend 2 1 3 unit total time execute function 1 spend 4 unit total time executingExample 2input n 1 log 0start00start20end50start60end60end7output 8explanationfunction 0 start begin time 0 execute 2 unit time recursively call itselffunction 0 recursive start begin time 2 execute 4 unit timefunction 0 initial resume execution immediately call againfunction 0 2nd recursive start begin time 6 execute 1 unit timefunction 0 initial resume execution begin time 7 execute 1 unit timeSo function 0 spend 2 4 1 1 8 unit total time executingExample 3input n 2 log 0start00start20end51start61end60end7output 71explanationfunction 0 start begin time 0 execute 2 unit time recursively call itselffunction 0 recursive start begin time 2 execute 4 unit timefunction 0 initial resume execution immediately call function 1Function 1 start begin time 6 execute 1 unit time end end time 6function 0 resume execution begin time 6 execute 2 unit timeSo function 0 spend 2 4 1 7 unit total time execute function 1 spend 1 unit total time execute Constraints1 n 1001 logslength 5000 function_id n0 timestamp 109no start event happen timestampno end event happen timestampeach function end log start log
0array
give root binary tree return average value node level form array Answers 105 actual answer accept Example 1input root 3920nullnull157output 30000014500001100000explanation the average value node level 0 3 level 1 145 level 2 11hence return 3 145 11example 2input root 3920157output 30000014500001100000 ConstraintsThe number nod tree range 1 104231 Nodeval 231 1
1graph
in LeetCode Store n item sell each item price however special offer special offer consist different kind item sale priceyou give integer array price pricei price ith item integer array need needsi number piece ith item want buyyou give array special speciali size n 1 specialij number piece jth item ith offer specialin ie integer array price ith offerReturn low price pay exactly certain item give optimal use special offer you allow buy item want low overall price you use special offer time want example 1input price 25 special 3051210 need 32output 14explanation there kind item a b their price 2 5 respectively in special offer 1 pay 5 3A 0bin special offer 2 pay 10 1a 2b you need buy 3A 2B pay 10 1A 2B special offer 2 4 2aexample 2input price 234 special 11042219 need 121output 11explanation the price a 2 3 b 4 c you pay 4 1A 1B 9 2a 2b 1C you need buy 1A 2B 1C pay 4 1A 1B special offer 1 3 1b 4 1c you add item 9 2a 2b 1C Constraintsn pricelength needslength1 n 60 pricei needsi 101 speciallength 100specialilength n 10 specialij 50
0array
a message contain letter AZ encode number follow mappingA 1B 2Z 26To decode encode message digit group map letter reverse mapping multiple way for example 11106 map intoAAJF group 1 1 10 6kjf group 11 10 6note group 1 11 06 invalid 06 map F 6 different 06in addition mapping encode message contain character represent digit 1 9 0 exclude for example encode message 1 represent encode message 11 12 13 14 15 16 17 18 19 Decoding 1 equivalent decode encode message representgiven string s consist digit character return number way decode itsince answer large return modulo 109 7 Example 1input s output 9explanation the encode message represent encode message 1 2 3 4 5 6 7 8 9each decode string a b c d e F g h I respectivelyhence total 9 way decode Example 2Input s 1output 18explanation the encode message represent encode message 11 12 13 14 15 16 17 18 19each encode message 2 way decode eg 11 decode AA KHence total 9 2 18 way decode 1Example 3input s 2output 15explanation the encode message represent encode message 21 22 23 24 25 26 27 28 2921 22 23 24 25 26 2 way decode 27 28 29 1 wayhence total 6 2 3 1 12 3 15 way decode 2 Constraints1 slength 105si digit
2string
solve give equation return value x form string xvalue the equation contain operation variable x coefficient you return no solution solution equation Infinite solution infinite solution equationif exactly solution equation ensure value x integer Example 1input equation x53x6x2Output x2Example 2input equation xxOutput Infinite solutionsExample 3input equation 2xxoutput x0 Constraints3 equationlength 1000equation exactly equation consist integer absolute value range 0 100 lead zero variable x
2string
design implementation circular doubleende queue dequeimplement MyCircularDeque classmycirculardequeint k Initializes deque maximum size kboolean insertfront add item Deque return true operation successful false otherwiseboolean insertLast add item rear Deque return true operation successful false otherwiseboolean deletefront Deletes item Deque return true operation successful false otherwiseboolean deleteLast Deletes item rear Deque return true operation successful false otherwiseint getfront Returns item Deque return 1 deque emptyint getRear return item Deque return 1 deque emptyboolean isempty return true deque false otherwiseboolean isfull return true deque false example 1inputmycirculardeque insertLast insertLast insertfront insertFront getrear isfull deleteLast insertfront getfront3 1 2 3 4 4 outputnull true true true false 2 true true true 4explanationmycirculardeque myCircularDeque new MyCircularDeque3myCircularDequeinsertLast1 return TruemyCircularDequeinsertLast2 return TruemyCircularDequeinsertFront3 return truemycirculardequeinsertfront4 return false queue fullmycirculardequegetrear return 2mycirculardequeisfull return TruemyCircularDequedeleteLast return truemycirculardequeinsertfront4 return truemycirculardequegetfront return 4 Constraints1 k 10000 value 1000at 2000 call insertfront insertlast deletefront deleteLast getfront getrear isempty isfull
0array
you give integer array num consist n element integer kFind contiguous subarray length equal k maximum average value return value any answer calculation error 105 accept Example 1input num 11256503 k 4Output 1275000explanation maximum average 12 5 6 50 4 51 4 1275example 2input num 5 k 1output 500000 Constraintsn numslength1 k n 105104 numsi 104
0array
you set integer s originally contain number 1 n unfortunately error number s got duplicate number set result repetition number loss numberyou give integer array num represent datum status set errorfind number occur twice number miss return form array Example 1input num 1224output 23example 2input num 11output 12 constraints2 numslength 1041 numsi 104
0array
you give array n pair pair pairsi lefti righti lefti rightiA pair p2 c d follow pair p1 b b c a chain pair form fashionreturn length long chain formedYou need use give interval you select pair order example 1input pair 122334output 2explanation the long chain 12 34example 2input pair 127845output 3explanation the long chain 12 45 78 Constraintsn pairslength1 n 10001000 lefti righti 1000
0array
give string s return number palindromic substring itA stre palindrome read backward forwardA substre contiguous sequence character string Example 1input s abcoutput 3explanation three palindromic string b cExample 2input s aaaoutput 6explanation six palindromic string aa aa aaa Constraints1 slength 1000 consists lowercase english letter
2string
in world dota2 party Radiant DireThe dota2 senate consist senator come party now Senate wants decide change dota2 game the voting change roundbased procedure in round senator exercise rightsBan senator right a senator senator lose right follow roundsAnnounce victory if senator find senator right vote party announce victory decide change gamegiven string senate represent senator party belong the character r D represent Radiant party dire party then n senator size give stre nthe roundbased procedure start senator senator give order this procedure end vote all senator lose right skip proceduresuppose senator smart play good strategy party Predict party finally announce victory change dota2 game the output Radiant Dire Example 1input senate RDOutput RadiantExplanation the senator come Radiant ban senator right round 1 and second senator can not exercise right anymore right ban and round 2 senator announce victory guy senate voteExample 2Input senate RDDOutput DireExplanation the senator come Radiant ban senator right round 1 and second senator can not exercise right anymore right ban and senator come dire ban senator right round 1 and round 2 senator announce victory guy senate vote Constraintsn senatelength1 n 104senatei R d
2string
give root binary tree return duplicate subtreesfor kind duplicate subtree need return root node themtwo tree duplicate structure node value Example 1input root 1234null24nullnull4Output 244example 2input root 211Output 1Example 3input root 2223null3nulloutput 233 ConstraintsThe number nod tree range 1 5000200 Nodeval 200
1graph
give root Binary Search Tree target number k return true exist element BST sum equal give target Example 1input root 53624null7 k 9Output trueExample 2input root 53624null7 k 28Output false ConstraintsThe number nod tree range 1 104104 Nodeval 104root guarantee valid binary search tree105 k 105
1graph
you give integer array num duplicate a maximum binary tree build recursively num follow algorithmCreate root node value maximum value numsrecursively build left subtree subarray prefix leave maximum valuerecursively build right subtree subarray suffix right maximum valuereturn maximum binary tree build num Example 1input num 321605output 635null20nullnull1explanation the recursive call follow the large value 321605 6 Left prefix 321 right suffix 05 the large value 321 3 Left prefix right suffix 21 empty array child the large value 21 2 Left prefix right suffix 1 empty array child only element child node value 1 the large value 05 5 Left prefix 0 right suffix only element child node value 0 empty array childexample 2input num 321output 3null2null1 Constraints1 numslength 10000 numsi 1000All integer num unique
0array
give root binary tree construct 0indexe m x n string matrix re represent format layout tree the format layout matrix construct follow rulesThe height tree height number row m equal height 1the number column n equal 2height1 1Place root node middle row formally location res0n12for node place matrix position resrc place leave child resr1c2heightr1 right child resr1c2heightr1continue process nod tree placedany cell contain stre Return construct matrix re Example 1input root 12Output 1 2example 2input root 123null4output 1 23 4 ConstraintsThe number nod tree range 1 21099 Nodeval 99The depth tree range 1 10
1graph
there robot start position 0 0 origin 2D plane give sequence move judge robot end 0 0 complete movesyou give string move represent sequence robot movesi represent ith Valid move r right L leave U D downreturn true robot return origin finish move false otherwisenote the way robot face irrelevant r robot right L leave etc also assume magnitude robot movement Example 1input move udoutput trueexplanation the robot move all move magnitude end origin started therefore return trueexample 2input move lloutput falseexplanation the robot move leave twice it end move leave origin we return false origin end move Constraints1 moveslength 2 104moves contain character U D L r
2string
give sort integer array arr integers k x return k close integer x array the result sort ascend orderan integer close x integer b ifa x b x ora x b x b Example 1input arr 12345 k 4 x 3output 1234example 2input arr 12345 k 4 x 1Output 1234 Constraints1 k arrlength1 arrlength 104arr sort ascend order104 arri x 104
0array
you give integer array num sort nondecrease orderDetermine possible split num subsequence follow condition trueeach subsequence consecutive increase sequence ie integer exactly previous integerall subsequence length 3 moreReturn true split num accord condition false otherwisea subsequence array new array form original array delete element disturb relative position remain element ie 135 subsequence 12345 132 Example 1input num 123345output trueexplanation num split follow subsequences123345 1 2 3123345 3 4 5example 2input num 12334455output trueexplanation num split follow subsequences12334455 1 2 3 4 512334455 3 4 5example 3input num 123445output falseexplanation it impossible split num consecutive increase subsequence length 3 constraints1 numslength 1041000 numsi 1000num sort nondecrease order
0array
an image smooth filter size 3 x 3 apply cell image round average cell surround cell ie average cell blue smooth if surround cell cell present consider average ie average cell red smootherGiven m x n integer matrix img represent grayscale image return image apply smooth cell Example 1input img 111101111output 000000000explanationfor point 00 02 20 22 floor34 floor075 0for point 01 10 12 21 floor56 floor083333333 0for point 11 floor89 floor088888889 0example 2input img 10020010020050200100200100output 137141137141138141137141137explanationfor point 00 02 20 22 floor100200200504 floor1375 137For point 01 10 12 21 floor200200502001001006 floor141666667 141for point 11 floor502002002002001001001001009 floor138888889 138 Constraintsm imglengthn imgilength1 m n 2000 imgij 255
0array
give root binary tree return maximum width give treethe maximum width tree maximum width levelsthe width level define length endnode leftmost rightmost nonnull node null node endnode present complete binary tree extend level count length calculationIt guarantee answer range 32bit sign integer Example 1input root 13253null9output 4explanation the maximum width exist level length 4 53null9example 2input root 1325nullnull96null7output 7explanation the maximum width exist fourth level length 7 6nullnullnullnullnull7example 3input root 1325output 2explanation the maximum width exist second level length 2 32 ConstraintsThe number nod tree range 1 3000100 Nodeval 100
1graph
there strange printer follow special propertiesthe printer print sequence character timeAt turn printer print new character start end place cover original exist charactersgiven string s return minimum number turn printer need print Example 1input s aaabbboutput 2explanation print aaa print bbbexample 2input s abaoutput 2explanation Print aaa print b second place string cover exist character Constraints1 slength 100s consist lowercase english letter
2string
give array num n integer task check nondecrease modifying elementwe define array nondecrease numsi numsi 1 hold 0base 0 n 2 Example 1input num 423output trueexplanation you modify 4 1 nondecrease arrayExample 2input num 421output falseexplanation you nondecrease array modify element Constraintsn numslength1 n 104105 numsi 105
0array
give integer n k construct list answer contain n different positive integer range 1 n obey follow requirementsuppose list answer a1 a2 a3 list a1 a2 a2 a3 a3 a4 an1 exactly k distinct integersreturn list answer if multiple valid answer return Example 1input n 3 k 1output 123explanation the 123 different positive integer range 1 3 11 exactly 1 distinct integer 1Example 2Input n 3 k 2output 132explanation the 132 different positive integer range 1 3 21 exactly 2 distinct integer 1 2 Constraints1 k n 104
0array
give root binary search tree low high boundary low high trim tree element lie low high trimming tree change relative structure element remain tree ie node descendant remain descendant it prove unique answerreturn root trim binary search tree note root change depend give bound Example 1input root 102 low 1 high 2output 1null2example 2input root 304null2nullnull1 low 1 high 3output 32null1 ConstraintsThe number nod tree range 1 1040 Nodeval 104The value node tree uniqueroot guarantee valid binary search tree0 low high 104
1graph
give nonempty special binary tree consist node nonnegative value node tree exactly zero subnode if node subnode node value small value subnode More formally property rootval minrootleftval rootrightval holdsgiven binary tree need output second minimum value set node value treeIf second minimum value exist output 1 instead example 1input root 225nullnull57output 5explanation the small value 2 second small value 5Example 2input root 222output 1explanation the small value 2 is not second small value ConstraintsThe number nod tree range 1 251 Nodeval 231 1rootval minrootleftval rootrightval internal node tree
1graph
there room n bulb label 1 n turn initially button wall each button different functionality wherebutton 1 Flips status bulbsButton 2 Flips status bulb label ie 2 4 Button 3 Flips status bulb odd label ie 1 3 Button 4 Flips status bulb label j 3k 1 k 0 1 2 ie 1 4 7 10 you exactly press button press total for press pick button pressGiven integer n press return number different possible status perform press button press Example 1input n 1 press 1output 2explanation Status press button 1 press button 2example 2Input n 2 press 1output 3explanation Status press button 1 press button 2 press button 3example 3Input n 3 press 1output 4explanation Status press button 1 press button 2 press button 3 press button 4 Constraints1 n 10000 press 1000
1graph
give integer array num return number longest increase subsequencesnotice sequence strictly increase Example 1input num 13547output 2explanation the long increase subsequence 1 3 4 7 1 3 5 7example 2input num 22222output 5explanation the length long increase subsequence 1 5 increase subsequence length 1 output 5 constraints1 numslength 2000106 numsi 106
0array
give unsorted array integer num return length long continuous increase subsequence ie subarray the subsequence strictly increasinga continuous increase subsequence define index l r l r numsl numsl 1 numsr 1 numsr l r numsi numsi 1 Example 1input num 13547output 3explanation the long continuous increase subsequence 135 length 3even 1357 increase subsequence continuous element 5 7 separate element4example 2input num 22222output 1explanation the long continuous increase subsequence 2 length 1 note strictlyincrease constraints1 numslength 104109 numsi 109
0array
design datum structure initialize list different word provide string determine change exactly character string match word datum structureimplement MagicDictionary classmagicdictionary Initializes objectvoid builddictstre dictionary Sets data structure array distinct string dictionarybool searchstre searchword return true change exactly character searchword match string datum structure return false Example 1inputmagicdictionary builddict search search search search hello leetcode hello hhllo hell leetcodedOutputnull null false true false falseexplanationmagicdictionary magicdictionary new MagicDictionarymagicDictionarybuildDicthello leetcodemagicDictionarysearchhello return FalsemagicDictionarysearchhhllo we change second h e match hello return TruemagicDictionarysearchhell return FalsemagicDictionarysearchleetcoded return false Constraints1 dictionarylength 1001 dictionaryilength 100dictionaryi consist lowercase english lettersall string dictionary distinct1 searchwordlength 100searchWord consist lowercase English lettersbuilddict call searchat 100 call search
2string
design map allow followingmap stre key give valuereturn sum value key prefix equal give stringimplement MapSum classmapsum Initializes MapSum objectvoid insertstre key int val Inserts keyval pair map if key existed original keyvalue pair overridden new oneint sumstre prefix return sum pair value key start prefix Example 1inputmapsum insert sum insert sum apple 3 ap app 2 apoutputnull null 3 null 5explanationmapsum mapsum new mapsummapsuminsertapple 3 mapsumsumap return 3 apple 3mapsuminsertapp 2 mapsumsumap return 5 apple app 3 2 5 constraints1 keylength prefixlength 50key prefix consist lowercase English letters1 val 1000At 50 call insert sum
2string
give string s contain type character return true s validthe following rule define valid stringany left parenthesis correspond right parenthesis any right parenthesis corresponding leave parenthesis left parenthesis correspond right parenthesis treat single right parenthesis single left parenthesis string Example 1input s output trueexample 2input s output trueExample 3input s output true constraints1 slength 100si
2string
you give integer array card length 4 you card contain number range 1 9 you arrange number card mathematical expression operator parenthese value 24you restrict follow rulesThe division operator represent real division integer divisionfor example 4 1 2 3 4 1 3 12every operation number in particular use unary operatorFor example card 1 1 1 1 expression 1 1 1 1 allowedyou concatenate number togetherfor example card 1 2 1 2 expression 12 12 validreturn true expression evaluate 24 false Example 1input card 4187output trueexplanation 84 71 24example 2input card 1212output false Constraintscardslength 41 cardsi 9
0array
give string s return true s palindrome delete character Example 1input s abaoutput trueExample 2input s abcaoutput trueExplanation you delete character cExample 3input s abcoutput false Constraints1 slength 105s consist lowercase english letter
2string
you keep score baseball game strange rule at begin game start recordyou give list string operations operationsi ith operation apply record followingan integer xRecord new score xRecord new score sum previous scoresdrecord new score double previous scorecinvalidate previous score remove recordreturn sum score record apply operationsThe test case generate answer intermediate calculation fit 32bit integer operation valid Example 1input op 52cdoutput 30explanation5 add 5 record record 52 add 2 record record 5 2C Invalidate remove previous score record 5D add 2 5 10 record record 5 10 Add 5 10 15 record record 5 10 15the total sum 5 10 15 30example 2input op 524cd9output 27explanation5 add 5 record record 52 add 2 record record 5 24 add 4 record record 5 2 4c Invalidate remove previous score record 5 2D Add 2 2 4 record record 5 2 49 Add 9 record record 5 2 4 9 add 4 9 5 record record 5 2 4 9 5 Add 9 5 14 record record 5 2 4 9 5 14the total sum 5 2 4 9 5 14 27example 3input op 1coutput 0Explanation1 add 1 record record 1C Invalidate remove previous score record since record total sum 0 Constraints1 operationslength 1000operationsi c D string represent integer range 3 104 3 104for operation previous score recordFor operation C d previous score record
0array
in problem tree undirecte graph connect cyclesyou give graph start tree n node label 1 n additional edge add the add edge different vertex choose 1 n edge exist the graph represent array edge length n edgesi ai bi indicate edge node ai bi graphReturn edge remove result graph tree n node if multiple answer return answer occur input Example 1input edge 121323output 23example 2input edge 1223341415output 14 Constraintsn edgeslength3 n 1000edgesilength 21 ai bi edgeslengthai biThere repeat edgesthe give graph connect
1graph
in problem root tree direct graph exactly node root node descendant node plus node exactly parent root node parentsThe give input direct graph start root tree n node distinct value 1 n additional direct edge add the add edge different vertex choose 1 n edge existedthe result graph give 2darray edge each element edge pair ui vi represent direct edge connect node ui vi ui parent child viReturn edge remove result graph root tree n node if multiple answer return answer occur give 2darray Example 1input edge 121323output 23example 2input edge 1223344115output 41 Constraintsn edgeslength3 n 1000edgesilength 21 ui vi nui vi
1graph
give string b return minimum number time repeat string string b substring if impossible b substre repeat return 1notice string abc repeat 0 time repeat 1 time abc repeat 2 time abcabc Example 1input abcd b cdabcdabOutput 3explanation we return 3 repeat time abcdabcdabcd b substre itExample 2input b aaoutput 2 Constraints1 alength blength 104a b consist lowercase english letter
2string
give root binary tree return length long path node path value this path pass rootthe length path node represent number edge Example 1input root 54511null5output 2explanation the show image show long path value ie 5Example 2input root 14544null5output 2explanation the show image show long path value ie 4 ConstraintsThe number nod tree range 0 1041000 Nodeval 1000The depth tree exceed 1000
1graph
give integer array num integer k find nonoverlapping subarray length k maximum sum return themreturn result list index represent start position interval 0indexed if multiple answer return lexicographically smallest Example 1input num 12126751 k 2output 035Explanation Subarrays 1 2 2 6 7 5 correspond start index 0 3 5we take 2 1 answer 1 3 5 lexicographically largerexample 2input num 121212121 k 2output 024 Constraints1 numslength 2 1041 numsi 2161 k floornumslength 3
0array
you data structure employee information include employee unique ID importance value direct subordinate idsyou give array employee employee whereemployeesiid ID ith employeeemployeesiimportance importance value ith employeeemployeesisubordinates list id direct subordinate ith employeeGiven integer i d represent employee ID return total importance value employee direct indirect subordinate Example 1input employee 15232333 i d 1output 11explanation employee 1 importance value 5 direct subordinate employee 2 employee 3they importance value 3thus total importance value employee 1 5 3 3 11example 2input employee 12553 i d 5output 3explanation employee 5 importance value 3 direct subordinatesthus total importance value employee 5 3 Constraints1 employeeslength 20001 employeesiid 2000All employeesiid unique100 employeesiimportance 100one employee direct leader subordinatesthe id employeesisubordinate valid id
1graph
give array string word integer k return k frequent stringsReturn answer sort frequency highest low Sort word frequency lexicographical order example 1input word iloveleetcodeilovecode k 2output iloveexplanation love frequent wordsnote come love low alphabetical orderexample 2input word thedayissunnythethethesunnyisis k 4Output theissunnydayExplanation sunny day frequent word number occurrence 4 3 2 1 respectively Constraints1 wordslength 5001 wordsilength 10wordsi consist lowercase english lettersk range 1 the number unique wordsi Followup could solve on logk time on extra space
2string
give binary string s return number nonempty substring number 0s 1s 0s 1s substring group consecutivelysubstring occur multiple time count number time occur Example 1input s 00110011output 6explanation there 6 substring equal number consecutive 1s 0s 0011 01 1100 10 0011 01notice substring repeat count number times occuralso 00110011 valid substring 0s 1s group togetherExample 2input s 10101output 4explanation there 4 substring 10 01 10 01 equal number consecutive 1s 0s Constraints1 slength 105si 0 1
2string
give nonempty array nonnegative integer num degree array define maximum frequency elementsyour task find small possible length contiguous subarray nums degree num Example 1input num 12231output 2explanation the input array degree 2 element 1 2 appear twiceOf subarray degree1 2 2 3 1 1 2 2 3 2 2 3 1 1 2 2 2 2 3 2 2the short length 2 so return 2example 2input num 1223142output 6explanation the degree 3 element 2 repeat 3 timesSo 223142 short subarray return 6 Constraintsnumslength 1 50000numsi integer 0 49999
0array
give integer array num integer k return true possible divide array k nonempty subset sum equal Example 1input num 4323521 k 4Output trueexplanation it possible divide 4 subset 5 1 4 23 23 equal sumsExample 2input num 1234 k 3Output false Constraints1 k numslength 161 numsi 104the frequency element range 1 4
0array
there square drop Xaxis 2d planeyou give 2D integer array position positionsi lefti sideLengthi represent ith square length sidelengthi drop left edge align Xcoordinate leftiEach square drop time height land square it fall downward negative Y direction land square Xaxis a square brushing leftright square count landing once land freeze place movedAfter square drop record height current tall stack squaresreturn integer array ans ansi represent height describe drop ith square Example 1input position 122361output 255explanationafter drop tall stack square 1 height 2after second drop tall stack square 1 2 height 5after drop tall stack square 1 2 height 5thus return answer 2 5 5example 2input position 100100200100output 100100ExplanationAfter drop tall stack square 1 height 100after second drop tall stack square 1 square 2 height 100thus return answer 100 100note square 2 brush right square 1 count land Constraints1 positionslength 10001 lefti 1081 sidelengthi 106
0array
give array integer num sort ascending order integer target write function search target num if target exist return index otherwise return 1you write algorithm Olog n runtime complexity Example 1input num 1035912 target 9output 4explanation 9 exist num index 4Example 2Input num 1035912 target 2output 1explanation 2 exist num return 1 Constraints1 numslength 104104 numsi target 104All integer num uniquenum sort ascending order
0array
Design HashSet builtin hash table librariesImplement MyHashSet classvoid addkey Inserts value key HashSetbool containskey Returns value key exist HashSet notvoid removekey Removes value key HashSet if key exist HashSet Example 1InputMyHashSet add add contain contain add contain remove contain 1 2 1 3 2 2 2 2outputnull null null true false null true null falseexplanationmyhashset myHashSet new MyHashSetmyHashSetadd1 set 1myhashsetadd2 set 1 2myhashsetcontains1 return truemyhashsetcontains3 return False foundmyhashsetadd2 set 1 2myhashsetcontains2 return truemyhashsetremove2 set 1myhashsetcontains2 return False remove constraints0 key 106at 104 call add remove contain
0array
Design HashMap builtin hash table librariesimplement MyHashMap classMyHashMap initialize object mapvoid putint key int value insert key value pair HashMap if key exist map update corresponding valueint getint key return value specify key map 1 map contain mapping keyvoid removekey remove key corresponding value map contain mapping key Example 1inputmyhashmap remove 1 1 2 2 1 3 2 1 2 2 2outputnull null null 1 1 null 1 null 1explanationmyhashmap myHashMap new MyHashMapmyHashMapput1 1 the map 11myhashmapput2 2 the map 11 22myhashmapget1 return 1 the map 11 22myhashmapget3 return 1 ie find the map 11 22myhashmapput2 1 the map 11 21 ie update exist valuemyhashmapget2 return 1 the map 11 21myhashmapremove2 remove mapping 2 the map 11myhashmapget2 return 1 ie find the map 11 constraints0 key value 106at 104 call remove
0array
give string s return string replace uppercase letter lowercase letter Example 1input s HelloOutput helloexample 2input s hereoutput hereexample 3Input s LOVELYOutput lovely Constraints1 slength 100s consist printable ascii character
2string