question
stringlengths
58
4.29k
label
class label
3 classes
you give array price pricesi price give stock ith dayfind maximum profit achieve you complete transaction like ie buy sell share stock multiple time follow restrictionsafter sell stock buy stock day ie cooldown dayNote you engage multiple transaction simultaneously ie sell stock buy Example 1input price 12302output 3explanation transaction buy sell cooldown buy sellExample 2input price 1output 0 Constraints1 priceslength 50000 pricesi 1000
0array
a tree undirecte graph vertex connect exactly path in word connect graph simple cycle treeGiven tree n node label 0 n 1 array n 1 edge edgesi ai bi indicate undirected edge node ai bi tree choose node tree root when select node x root result tree height h among possible rooted tree minimum height ie minh call minimum height tree mhtsreturn list MHTs root label you return answer orderThe height root tree number edge long downward path root leaf Example 1input n 4 edge 101213output 1explanation as show height tree 1 root node label 1 MHTExample 2input n 6 edge 3031323454output 34 Constraints1 n 2 104edgeslength n 10 ai bi nai biAll pair ai bi distinctThe give input guarantee tree repeat edge
1graph
you give n balloon index 0 n 1 each balloon paint number represent array num you ask burst balloonsIf burst ith balloon numsi 1 numsi numsi 1 coin if 1 1 go bound array treat balloon 1 paint itreturn maximum coin collect burst balloon wisely Example 1input num 3158output 167explanationnums 3158 358 38 8 coin 315 358 138 181 167example 2input num 15output 10 Constraintsn numslength1 n 3000 numsi 100
0array
a super ugly number positive integer prime factor array primesGiven integ n array integer prime return nth super ugly numberThe nth super ugly number guarantee fit 32bit sign integer Example 1input n 12 prime 271319output 32explanation 1247813141619262832 sequence 12 super ugly number give prime 271319example 2input n 1 prime 235output 1explanation 1 prime factor prime factor array prime 235 Constraints1 n 1051 primeslength 1002 primesi 1000primesi guarantee prime numberAll value prime unique sorted ascending order
0array
give integer array num return integer array count countsi number small element right numsi Example 1input num 5261output 2110explanationto right 5 2 small element 2 1to right 2 1 small element 1to right 6 1 small element 1to right 1 0 small elementExample 2input num 1output 0Example 3input num 11output 00 Constraints1 numslength 105104 numsi 104
0array
give string s remove duplicate letter letter appear you sure result smallest lexicographical order possible result Example 1input s bcabcoutput abcexample 2Input s cbacdcbcoutput acdb Constraints1 slength 104s consist lowercase english letter note this question 1081 httpsleetcodecomproblemssmallestsubsequenceofdistinctcharacter
2string
give integer array num reorder nums0 nums1 nums2 nums3You assume input array valid answer Example 1input num 151164output 161514explanation 141516 acceptedExample 2input num 132231output 231312 Constraints1 numslength 5 1040 numsi 5000it guarantee answer give input num follow up can on time andor inplace O1 extra space
0array
give integer array nums integer lower upper return number range sum lie low upper inclusiverange sum Si j define sum element num indice j inclusive j Example 1input num 251 low 2 upper 2output 3explanation the range 00 22 02 respective sum 2 1 2example 2input num 0 low 0 upper 0output 1 Constraints1 numslength 105231 numsi 231 1105 low upper 105the answer guarantee fit 32bit integer
0array
give sort integer array nums integer n addpatch element array number range 1 n inclusive form sum element arrayreturn minimum number patch require Example 1input num 13 n 6output 1explanationcombinations num 1 3 13 form possible sum 1 3 4now addpatch 2 num combination 1 2 3 13 23 123Possible sum 1 2 3 4 5 6 cover range 1 6so need 1 patchExample 2input num 1510 n 20output 2explanation the patch 2 4example 3input num 122 n 5output 0 Constraints1 numslength 10001 numsi 104nums sort ascend order1 n 231 1
0array
one way serialize binary tree use preorder traversal when encounter nonnull node record node value if null node record sentinel value for example binary tree serialize string 934126 represent null nodeGiven stre commaseparated value preorder return true correct preorder traversal serialization binary treeIt guarantee commaseparated value string integer character represent null pointeryou assume input format validFor example contain consecutive commas 13note you allow reconstruct tree Example 1input preorder 934126output trueExample 2input preorder 1output falseExample 3input preorder 91output false Constraints1 preorderlength 104preorder consist integer range 0 100 separate commas
2string
you give list airline ticket ticketsi fromi toi represent departure arrival airport flight Reconstruct itinerary order return itall ticket belong man depart JFK itinerary begin JFK if multiple valid itinerary return itinerary small lexical order read single stringfor example itinerary JFK LGA small lexical order JFK LGBYou assume ticket form valid itinerary you use ticket example 1input ticket MUCLHRJFKMUCSFOSJCLHRSFOOutput JFKMUCLHRSFOSJCExample 2input ticket JFKSFOJFKATLSFOATLATLJFKATLSFOOutput JFKATLJFKSFOATLSFOExplanation another possible reconstruction JFKSFOATLJFKATLSFO large lexical order Constraints1 ticketslength 300ticketsilength 2fromilength 3toilength 3fromi toi consist uppercase English lettersfromi toi
1graph
give integer array num return true exist triple index j k j k numsi numsj numsk if index exist return false example 1input num 12345output trueexplanation any triplet j k validExample 2input num 54321output falseexplanation no triplet existsexample 3input num 215046output trueexplanation the triplet 3 4 5 valid nums3 0 nums4 4 nums5 6 constraints1 numslength 5 105231 numsi 231 1 Follow could implement solution run on time complexity o1 space complexity
0array
you give array integer distanceyou start point 00 xy plane distance0 meter north distance1 meter west distance2 meter south distance3 meter east in word direction change counterclockwisereturn true path cross false Example 1input distance 2112output trueExample 2input distance 1234output falseexample 3input distance 1111output true Constraints1 distancelength 1051 distancei 105
0array
the thief find new place thievery there entrance area call rootBesides root house parent house after tour smart thief realize house place form binary tree it automatically contact police directlylinke house break nightgiven root binary tree return maximum money thief rob alert police Example 1input root 323null3null1output 7explanation Maximum money thief rob 3 3 1 7example 2input root 34513null1output 9explanation Maximum money thief rob 4 5 9 ConstraintsThe number nod tree range 1 1040 Nodeval 104
1graph
you give nested list integer nestedlist each element integer list element integer list Implement iterator flatten itImplement NestedIterator classnestediteratorlistnestedinteger nestedlist Initializes iterator nest list nestedListint Returns integer nest listboolean hasnext return true integer nest list false otherwiseYour code test follow pseudocodeinitialize iterator nestedlistre iteratorhasnext append iteratornext end resreturn resIf re match expect flatten list code judge correct Example 1input nestedlist 11211output 11211explanation by call repeatedly hasnext return false order element return 11211example 2input nestedlist 146output 146explanation by call repeatedly hasnext return false order element return 146 Constraints1 nestedlistlength 500the value integer nest list range 106 106
1graph
write function reverse stre the input string give array character syou modifying input array inplace O1 extra memory Example 1input s hellooutput ollehExample 2input s HannahOutput hannaH Constraints1 slength 105si printable ascii character
2string
give string s reverse vowel string return itthe vowel e o u appear low upper case Example 1input s hellooutput holleExample 2input s leetcodeoutput leotcede Constraints1 slength 3 105s consist printable ascii character
2string
give integer array num integer k return k frequent element you return answer order Example 1input num 111223 k 2output 12Example 2input num 1 k 1Output 1 Constraints1 numslength 105104 numsi 104k range 1 number unique element arrayit guarantee answer unique Follow your algorithms time complexity well on log n n array size
0array
give integer array nums1 nums2 return array intersection each element result unique return result order Example 1input nums1 1221 nums2 22output 2example 2input nums1 495 nums2 94984output 94explanation 49 accept Constraints1 nums1length nums2length 10000 nums1i nums2i 1000
0array
give integer array nums1 nums2 return array intersection each element result appear time show array return result order Example 1input nums1 1221 nums2 22output 22example 2input nums1 495 nums2 94984output 49explanation 94 accept Constraints1 nums1length nums2length 10000 nums1i nums2i 1000 Follow upwhat give array sort how optimize algorithmwhat nums1s size small compare nums2s size which algorithm betterwhat element nums2 store disk memory limit load element memory
0array
you give 2D array integer envelope envelopesi wi hi represents width height envelopeone envelope fit width height envelope great envelope width heightReturn maximum number envelope russian doll ie inside othernote you rotate envelope Example 1input envelope 54646723output 3explanation the maximum number envelope russian doll 3 23 54 67example 2input envelope 111111output 1 Constraints1 envelopeslength 105envelopesilength 21 wi hi 105
0array
give m x n matrix matrix integer k return max sum rectangle matrix sum large kit guarantee rectangle sum large k example 1input matrix 101023 k 2output 2explanation because sum blue rectangle 0 1 2 3 2 2 max number large k k 2Example 2Input matrix 221 k 3output 3 Constraintsm matrixlengthn matrixilength1 m n 100100 matrixij 100105 k 105 Follow what number row large number column
0array
you give jug capacity jug1Capacity jug2Capacity liter there infinite water supply available Determine possible measure exactly targetcapacity liter jugsif targetcapacity liter water measurable targetcapacity liter water contain bucket endoperations allowedfill jug waterempty jugspour water jug till jug completely jug example 1input jug1capacity 3 jug2capacity 5 targetcapacity 4output trueexplanation the famous die hard example Example 2input jug1capacity 2 jug2capacity 6 targetcapacity 5output falseexample 3input jug1capacity 1 jug2capacity 2 targetcapacity 3output true Constraints1 jug1capacity jug2Capacity targetcapacity 106
1graph
give set distinct positive integer num return large subset answer pair answeri answerj element subset satisfiesansweri answerj 0 oranswerj answeri 0if multiple solution return Example 1input num 123output 12Explanation 13 acceptedExample 2input num 1248output 1248 Constraints1 numslength 10001 numsi 2 109all integer num unique
0array
you give integer array nums1 nums2 sort ascending order integer kDefine pair u v consist element array element second arrayReturn k pair u1 v1 u2 v2 uk vk small sum example 1input nums1 1711 nums2 246 k 3output 121416explanation the 3 pair return sequence 121416727411276114116example 2input nums1 112 nums2 123 k 2output 1111explanation the 2 pair return sequence 111112211222131323example 3input nums1 12 nums2 3 k 3output 1323explanation all possible pair return sequence 1323 Constraints1 nums1length nums2length 105109 nums1i nums2i 109nums1 nums2 sort ascending order1 k 104
0array
a wiggle sequence sequence difference successive number strictly alternate positive negative the difference exist positive negative a sequence element sequence nonequal element trivially wiggle sequencesfor example 1 7 4 9 2 5 wiggle sequence difference 6 3 5 7 3 alternate positive negativeIn contrast 1 4 7 2 5 1 7 4 5 5 wiggle sequence the difference positive second difference zeroA subsequence obtain delete element possibly zero original sequence leave remain element original orderGiven integer array num return length long wiggle subsequence num Example 1input num 174925output 6explanation the entire sequence wiggle sequence difference 6 3 5 7 3example 2input num 1175101315105168output 7explanation there subsequence achieve lengthOne 1 17 10 13 10 16 8 difference 16 7 3 3 6 8example 3input num 123456789output 2 Constraints1 numslength 10000 numsi 1000 Follow could solve on time
0array
give array distinct integer num target integer target return number possible combination add targetthe test case generate answer fit 32bit integer Example 1input num 123 target 4Output 7explanationthe possible combination way are1 1 1 11 1 21 2 11 32 1 12 23 1note different sequence count different combinationsExample 2input num 9 target 3output 0 Constraints1 numslength 2001 numsi 1000All element nums unique1 target 1000 follow what negative number allow give array how change problem what limitation need add question allow negative number
0array
give n x n matrix row column sort ascending order return kth small element matrixnote kth small element sorted order kth distinct elementyou find solution memory complexity well on2 example 1input matrix 159101113121315 k 8Output 13Explanation the element matrix 159101112131315 8th small number 13example 2input matrix 5 k 1output 5 Constraintsn matrixlength matrixilength1 n 300109 matrixij 109all row column matrix guarantee sort nondecrease order1 k n2 Follow upcould solve problem constant memory ie O1 memory complexitycould solve problem on time complexity the solution advanced interview find read paper fun
0array
Implement RandomizedSet classrandomizedset Initializes RandomizedSet objectbool insertint val Inserts item val set present return true item present false otherwisebool removeint val Removes item val set present return true item present false otherwiseint getrandom return random element current set element guarantee element exist method call each element probability returnedyou implement function class function work average o1 time complexity Example 1inputrandomizedset insert remove insert getrandom remove insert getrandom 1 2 2 1 2 outputnull true false true 2 true false 2explanationrandomizedset randomizedSet new RandomizedSetrandomizedSetinsert1 Inserts 1 set return true 1 insert successfullyrandomizedsetremove2 return false 2 exist setrandomizedSetinsert2 insert 2 set return true Set contain 12randomizedsetgetrandom getrandom return 1 2 randomlyrandomizedsetremove1 Removes 1 set return true Set contain 2randomizedsetinsert2 2 set return falserandomizedsetgetrandom since 2 number set getrandom return 2 constraints231 val 231 1at 2 105 call insert remove getrandomthere element datum structure getrandom call
0array
RandomizedCollection data structure contain collection number possibly duplicate ie multiset it support insert remove specific element remove random elementImplement RandomizedCollection classrandomizedcollection Initializes RandomizedCollection objectbool insertint val Inserts item val multiset item present return true item present false otherwisebool removeint val Removes item val multiset present return true item present false note val multiple occurrence multiset remove themint getrandom return random element current multiset element the probability element return linearly relate number value multiset containsYou implement function class function work average O1 time complexityNote the test case generate getrandom call item RandomizedCollection Example 1inputrandomizedcollection insert insert insert getRandom remove getrandom 1 1 2 1 outputnull true false true 2 true 1explanationrandomizedcollection randomizedcollection new RandomizedCollectionrandomizedCollectioninsert1 return true collection contain 1 Inserts 1 collectionrandomizedcollectioninsert1 return false collection contain 1 Inserts 1 collection Collection contain 11randomizedcollectioninsert2 return true collection contain 2 Inserts 2 collection Collection contain 112randomizedcollectiongetrandom getrandom return 1 probability 23 return 2 probability 13randomizedcollectionremove1 return true collection contain 1 Removes 1 collection Collection contain 12randomizedcollectiongetrandom getrandom return 1 2 equally likely constraints231 val 231 1at 2 105 call total insert remove getrandomthere element datum structure getrandom call
0array
give string ransomnote magazine return true ransomnote construct letter magazine false otherwiseEach letter magazine ransomnote Example 1input ransomNote magazine bOutput falseexample 2input ransomNote aa magazine abOutput falseexample 3input ransomnote aa magazine aabOutput true constraints1 ransomnotelength magazinelength 105ransomNote magazine consist lowercase english letter
2string
give integer array num design algorithm randomly shuffle array all permutation array equally likely result shufflingimplement solution classsolutionint num Initializes object integer array numsint reset Resets array original configuration return itint shuffle return random shuffle array Example 1inputsolution shuffle reset shuffle1 2 3 outputnull 3 1 2 1 2 3 1 3 2explanationsolution solution new Solution1 2 3solutionshuffle Shuffle array 123 return result any permutation 123 equally likely return Example return 3 1 2solutionreset Resets array original configuration 123 return 1 2 3solutionshuffle return random shuffle array 123 Example return 1 3 2 constraints1 numslength 50106 numsi 106all element num uniqueAt 104 call total reset shuffle
0array
give integer n return number range 1 n sorted lexicographical orderYou write algorithm run on time use O1 extra space example 1input n 13Output 11011121323456789example 2input n 2output 12 Constraints1 n 5 104
1graph
give string s find nonrepeate character return index if exist return 1 example 1input s leetcodeoutput 0example 2input s loveleetcodeoutput 2example 3input s aabboutput 1 Constraints1 slength 105s consist lowercase english letter
2string
you give string s tString t generate random shuffle string s add letter random positionreturn letter add t Example 1input s abcd t abcdeoutput eExplanation e letter addedexample 2input s t yOutput y constraints0 slength 1000tlength slength 1s t consist lowercase english letter
2string
give array rectangle rectanglesi xi yi ai bi represent axisaligned rectangle the bottomleft point rectangle xi yi topright point ai biReturn true rectangle form exact cover rectangular region Example 1input rectangle 11333142324413242334output trueExplanation all 5 rectangle form exact cover rectangular regionExample 2input rectangle 1123132431423244output falseexplanation because gap rectangular regionsExample 3input rectangle 1133314213242244output falseexplanation because rectangle overlap Constraints1 rectangleslength 2 104rectanglesilength 4105 xi yi ai bi 105
0array
give string s t return true s subsequence t false otherwisea subsequence stre new string form original string delete character disturb relative position remain character ie ace subsequence abcde aec Example 1input s abc t ahbgdcOutput trueexample 2input s axc t ahbgdcOutput false constraints0 slength 1000 tlength 104s t consist lowercase English letter Follow suppose lot income s s1 s2 sk k 109 want check t subsequence in scenario change code
2string
give integer array datum represent datum return valid UTF8 encoding ie translates sequence valid UTF8 encode charactersA character UTF8 1 4 byte long subject follow rulesfor 1byte character bit 0 follow Unicode codeFor nbyte character n bit one n 1 bit 0 follow n 1 byte significant 2 bit 10this UTF8 encode work number byte UTF8 Octet Sequence binary 1 0xxxxxxx 2 110xxxxx 10xxxxxx 3 1110xxxx 10xxxxxx 10xxxxxx 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxxx denote bite binary form byte 0 1note the input array integer only significant 8 bit integer store datum this mean integer represent 1 byte datum Example 1input datum 1971301output trueExplanation datum represent octet sequence 11000101 10000010 00000001it valid utf8 encode 2bytes character follow 1byte characterexample 2input datum 2351404output falseexplanation datum represent octet sequence 11101011 10001100 00000100the 3 bit one 4th bit 0 mean 3bytes characterthe byte continuation byte start 10 that s correctBut second continuation byte start 10 invalid Constraints1 datalength 2 1040 datai 255
0array
give encode string return decode stringThe encoding rule kencoded_stre encoded_stre inside square bracket repeat exactly k time note k guarantee positive integeryou assume input string valid extra white space square bracket wellforme etc furthermore assume original datum contain digit digit repeat number k for example input like 3a 24the test case generate length output exceed 105 Example 1input s 3a2bcoutput aaabcbcExample 2input s 3a2coutput accaccaccExample 3input s 2abc3cdefoutput abcabccdcdcdef Constraints1 slength 30s consist lowercase english letter digit square brackets s guarantee valid inputall integer s range 1 300
2string
give string s integ k return length long substre s frequency character substre greater equal k Example 1input s aaabb k 3output 3explanation the long substring aaa repeat 3 timesExample 2input s ababbc k 2output 5explanation the long substre ababb repeat 2 time b repeat 3 time Constraints1 slength 104s consist lowercase english letters1 k 105
2string
you give integer array num length nAssume arrk array obtain rotate num k position clockwise we define rotation function F num followFk 0 arrk0 1 arrk1 n 1 arrkn 1return maximum value F0 F1 fn1the test case generate answer fit 32bit integer Example 1input num 4326output 26explanationf0 0 4 1 3 2 2 3 6 0 3 4 18 25f1 0 6 1 4 2 3 3 2 0 4 6 6 16f2 0 2 1 6 2 4 3 3 0 6 8 9 23f3 0 3 1 2 2 6 3 4 0 2 12 12 26so maximum value F0 F1 F2 F3 F3 26example 2input num 100output 0 Constraintsn numslength1 n 105100 numsi 100
0array
give stre num represent nonnegative integer num integer k return small possible integer remove k digits num Example 1input num 1432219 k 3output 1219explanation Remove digit 4 3 2 form new number 1219 smallestexample 2input num 10200 k 1output 200Explanation Remove lead 1 number 200 note output contain lead zeroesexample 3input num 10 k 2output 0explanation Remove digit number leave 0 Constraints1 k numlength 105num consist digitsnum lead zero zero
2string
a frog crossing river the river divide number unit unit exist stone the frog jump stone jump waterGiven list stone position unit sort ascending order determine frog cross river landing stone initially frog stone assume jump 1 unitIf frog jump k unit jump k 1 k k 1 unit the frog jump forward direction example 1input stone 0135681217output trueexplanation the frog jump stone jump 1 unit 2nd stone 2 unit 3rd stone 2 unit 4th stone 3 unit 6th stone 4 unit 7th stone 5 unit 8th stoneexample 2input stone 012348911output falseexplanation there way jump stone gap 5th 6th stone large constraints2 stoneslength 20000 stonesi 231 1stones0 0stone sort strictly increase order
0array
give root binary tree return sum leave leavesA leaf node child a left leaf leaf leave child node Example 1input root 3920nullnull157output 24explanation there leave leave binary tree value 9 15 respectivelyexample 2input root 1output 0 ConstraintsThe number nod tree range 1 10001000 Nodeval 1000
1graph
you give array people people attribute people queue necessarily order each peoplei hi ki represent ith person height hi exactly ki people height greater equal hireconstruct return queue represent input array people the return queue format array queue queuej hj kj attribute jth person queue queue0 person queue Example 1input people 704471506152output 507052614471ExplanationPerson 0 height 5 people tall height frontperson 1 height 7 people tall height frontperson 2 height 5 person tall height person 0 1Person 3 height 6 person tall height person 1person 4 height 4 people tall height people 0 1 2 3person 5 height 7 person tall height person 1hence 507052614471 reconstruct queueexample 2input people 605040322214output 405022321460 Constraints1 peoplelength 20000 hi 1060 ki peoplelengthit guarantee queue reconstruct
0array
give string s consist lowercase uppercase letter return length long palindrome build lettersletter case sensitive example Aa consider palindrome Example 1input s abccccddoutput 7explanation one long palindrome build dccaccd length 7example 2input s aoutput 1explanation the long palindrome build length 1 constraints1 slength 2000s consist lowercase andor uppercase english letter
2string
give integer array num integer k split nums k nonempty subarray large sum subarray minimizedreturn minimize large sum splitA subarray contiguous array Example 1input num 725108 k 2output 18explanation there way split num subarraysthe good way split 725 108 large sum subarray 18example 2input num 12345 k 2output 9explanation there way split num subarraysthe good way split 123 45 large sum subarray 9 Constraints1 numslength 10000 numsi 1061 k min50 numslength
0array
give integer n return string array answer 1indexed whereansweri FizzBuzz divisible 3 5answeri fizz divisible 3answeri Buzz divisible 5answeri string condition true Example 1input n 3output 12fizzexample 2input n 5output 12fizz4buzzexample 3input n 15output 12fizz4buzzfizz78fizzbuzz11fizz1314fizzbuzz Constraints1 n 104
2string
an integer array call arithmetic consist element difference consecutive element samefor example 13579 7777 3159 arithmetic sequencesGiven integer array num return number arithmetic subarray numsA subarray contiguous subsequence array Example 1input num 1234output 3explanation we 3 arithmetic slice num 1 2 3 2 3 4 1234 itselfexample 2input num 1output 0 Constraints1 numslength 50001000 numsi 1000
0array
give integer array num return distinct maximum number array if maximum exist return maximum number example 1input num 321Output 1explanationthe distinct maximum 3the second distinct maximum 2the distinct maximum 1example 2input num 12Output 2explanationthe distinct maximum 2the second distinct maximum 1the distinct maximum exist maximum 2 return insteadExample 3input num 2231output 1explanationthe distinct maximum 3the second distinct maximum 2 2s count valueThe distinct maximum 1 constraints1 numslength 104231 numsi 231 1 Follow can find on solution
0array
give nonnegative integer num1 num2 represent string return sum num1 num2 stringYou solve problem builtin library handle large integer BigInteger you convert input integer directly example 1input num1 11 num2 123output 134example 2input num1 456 num2 77Output 533example 3input num1 0 num2 0output 0 Constraints1 num1length num2length 104num1 num2 consist digitsnum1 num2 do not lead zero zero
2string
give nonempty array num contain positive integer find array partition subset sum element subset equal Example 1input num 15115output trueexplanation the array partition 1 5 5 11example 2input num 1235output falseexplanation the array partition equal sum subset Constraints1 numslength 2001 numsi 100
0array
a password consider strong condition metit 6 character 20 charactersIt contain lowercase letter uppercase letter digitIt contain repeat character row ie aaa weak aaa strong assume condition metgiven string password return minimum number step require password strong password strong return 0in step caninsert character passworddelete character password orReplace character password character Example 1input password aOutput 5example 2input password aA1Output 3example 3input password 1337c0d3output 0 Constraints1 passwordlength 50password consist letter digit dot exclamation mark
2string
give integer array num return maximum result numsi XOR numsj 0 j n Example 1input num 31052528output 28explanation the maximum result 5 xor 25 28example 2input num 147053834991368092516670output 127 constraints1 numslength 2 1050 numsi 231 1
0array
give string s contain outoforder english representation digit 09 return digit ascend order Example 1input s owoztneoeroutput 012example 2input s fviefurooutput 45 Constraints1 slength 105si character egfihonsrutwvxzs guarantee valid
2string
you give string s integer k you choose character string change uppercase english character you perform operation k timesreturn length long substre contain letter perform operation Example 1input s ABAB k 2output 4explanation Replace as Bs vice versaexample 2input s AABABBA k 1output 4explanation replace a middle b form AABBBBAThe substre BBBB long repeat letter 4 Constraints1 slength 105s consist uppercase English letters0 k slength
2string
give n n matrix grid 0s 1s we want represent grid quadtreereturn root QuadTree represent gridNotice assign value node true False isLeaf False accept answerA QuadTree tree data structure internal node exactly child besides node attributesval true node represents grid 1s false node represents grid 0sisLeaf true node leaf node tree false node childrenclass Node public boolean val public boolean isLeaf public Node topLeft public Node topright public Node bottomleft public Node bottomrightwe construct QuadTree twodimensional area follow stepsIf current grid value ie 1s 0s set isLeaf true set val value grid set child Null stopIf current grid different value set isLeaf False set val value divide current grid subgrid show photorecurse child proper subgridIf want know QuadTree refer wikiquadtree formatthe output represent serialized format QuadTree level order traversal null signify path terminator node exist belowIt similar serialization binary tree the difference node represent list isLeaf valif value isLeaf val true represent 1 list isLeaf val value isLeaf val False represent 0 example 1input grid 0110output 0110111110explanation the explanation example show belownotice 0 represnt false 1 represent true photo represent QuadTreeExample 2input grid 1111000011110000111111111111111111110000111100001111000011110000output 0111011110nullnullnullnull10101111explanation all value grid we divide grid subgridsthe topleft bottomleft bottomright valuethe topright different value divide 4 subgrid valueExplanation show photo Constraintsn gridlength gridilengthn 2x 0 x 6
0array
give nary tree return level order traversal node valuesNaryTree input serialization represent level order traversal group child separate null value see example example 1input root 1null324null56output 132456example 2input root 1null2345nullnull67null8null910nullnull11null12null13nullnull14output 1234567891011121314 ConstraintsThe height nary tree equal 1000the total number node 0 104
1graph
you give doubly link list contain node pointer previous pointer additional child pointer this child pointer point separate doubly link list contain special node these child list child produce multilevel datum structure show example belowGiven head level list flatten list node appear singlelevel doubly link list let curr node child list the node child list appear curr currnext flatten listReturn head flatten list the node list child pointer set null Example 1input head 123456nullnullnull78910nullnull1112output 123781112910456explanation the multilevel link list input shownAfter flatten multilevel link list becomesExample 2input head 12null3output 132explanation the multilevel link list input shownAfter flatten multilevel link list becomesExample 3input head Output Explanation there list input ConstraintsThe number Nodes exceed 10001 Nodeval 105 how multilevel link list represent test casesWe use multilevel link list Example 1 123456null 78910null 1112nullthe serialization level follows123456null78910null1112nullto serialize level add null level signify node connect upper node previous level the serialization becomes1 2 3 4 5 6 null null null 7 8 9 10 null null 11 12 nullmerge serialization level remove trailing null obtain123456nullnullnull78910nullnull1112
1graph
give string s return number segment stringa segment define contiguous sequence nonspace character example 1input s Hello JohnOutput 5explanation the segment Hello JohnExample 2input s HelloOutput 1 constraints0 slength 300s consist lowercase uppercase English letter digit follow character _ the space character s
2string
give array intervals intervals intervalsi starti endi return minimum number interval need remove rest interval nonoverlapping Example 1input interval 12233413output 1explanation 13 remove rest interval nonoverlappingExample 2input interval 121212output 2explanation you need remove 12 rest interval nonoverlappingExample 3input interval 1223output 0explanation you do not need remove interval they re nonoverlappe Constraints1 intervalslength 105intervalsilength 25 104 starti endi 5 104
0array
you give array intervals intervalsi starti endi starti uniquethe right interval interval interval j startj endi startj minimize Note equal jReturn array right interval index interval if right interval exist interval 1 index Example 1input interval 12output 1explanation there interval collection output 1example 2input interval 342312output 101explanation there right interval 34the right interval 23 34 start0 3 small start end1 3the right interval 12 23 start1 2 small start end2 2example 3input interval 142334output 121explanation there right interval 14 34the right interval 23 34 start2 3 small start end1 3 Constraints1 intervalslength 2 104intervalsilength 2106 starti endi 106the start point interval unique
0array
give root binary tree integer targetsum return number path sum value path equal targetsumthe path need start end root leaf downward ie travel parent node child nod Example 1input root 105332null1132null1 targetsum 8output 3explanation the path sum 8 shownExample 2input root 54811null13472nullnull51 targetsum 22output 3 ConstraintsThe number nod tree range 0 1000109 Nodeval 1091000 targetsum 1000
1graph
give string s p return array start index ps anagram s you return answer orderAn Anagram word phrase form rearrange letter different word phrase typically original letter exactly Example 1input s cbaebabacd p abcoutput 06explanationthe substre start index 0 cba anagram abcthe substre start index 6 bac anagram abcExample 2Input s abab p abOutput 012explanationthe substre start index 0 ab anagram abThe substre start index 1 ba anagram abthe substre start index 2 ab anagram ab Constraints1 slength plength 3 104s p consist lowercase english letter
2string
give integer array num length n integer num range 1 n integer appear twice return array integer appear twiceyou write algorithm run on time use constant extra space Example 1input num 43278231output 23example 2input num 112output 1example 3input num 1Output Constraintsn numslength1 n 1051 numsi nEach element num appear twice
0array
give array character chars compress follow algorithmbegin string s for group consecutive repeat character charsIf group length 1 append character sOtherwise append character follow group lengththe compress string s return separately instead store input character array char note group length 10 long split multiple character charsafter modify input array return new length arrayyou write algorithm use constant extra space Example 1input char aabbcccOutput Return 6 6 character input array a2b2c3explanation the group aa bb ccc this compress a2b2c3example 2input char aOutput return 1 character input array aExplanation the group remain uncompressed single characterexample 3input char abbbbbbbbbbbboutput return 4 4 character input array ab12explanation the group bbbbbbbbbbbb this compress ab12 Constraints1 charslength 2000charsi lowercase english letter uppercase english letter digit symbol
2string
give integer array num return number arithmetic subsequence numsA sequence number call arithmetic consist element difference consecutive element sameFor example 1 3 5 7 9 7 7 7 7 3 1 5 9 arithmetic sequencesfor example 1 1 2 5 7 arithmetic sequenceA subsequence array sequence form remove element possibly arrayfor example 2510 subsequence 121241510the test case generate answer fit 32bit integer Example 1input num 246810output 7explanation all arithmetic subsequence slice are24646868102468468102468102610Example 2input num 77777output 16explanation any subsequence array arithmetic Constraints1 numslength 1000231 numsi 231 1
0array
you give n point plane distinct pointsi xi yi a boomerang tuple point j k distance j equal distance k order tuple mattersreturn number boomerang example 1input point 001020output 2explanation the boomerang 100020 102000example 2input point 112233output 2example 3input point 11output 0 Constraintsn pointslength1 n 500pointsilength 2104 xi yi 104All point unique
0array
give array num n integer numsi range 1 n return array integer range 1 n appear num Example 1input num 43278231output 56example 2input num 11output 2 Constraintsn numslength1 n 1051 numsi n Follow could extra space on runtime you assume return list count extra space
0array
give string s sort decrease order base frequency character the frequency character number time appear stringreturn sort string if multiple answer return Example 1input s treeoutput eertexplanation e appear twice r t appear onceSo e appear r t therefore eetr valid answerexample 2input s cccaaaoutput aaacccexplanation both c appear time cccaaa aaaccc valid answersnote cacaca incorrect character togetherexample 3input s AabbOutput bbaaexplanation bbaa valid answer Aabb incorrectNote a treat different character Constraints1 slength 5 105s consist uppercase lowercase english letter digit
2string
there spherical balloon tape flat wall represent XYplane the balloon represent 2D integer array point pointsi xstart xend denote balloon horizontal diameter stretch xstart xend you know exact ycoordinate balloonsarrow shoot directly vertically positive ydirection different point xaxis a balloon xstart xend burst arrow shoot x xstart x xend there limit number arrow shoot a shot arrow keep travel infinitely burst balloon pathgiven array point return minimum number arrow shoot burst balloon Example 1input point 10162816712output 2explanation the balloon burst 2 arrow Shoot arrow x 6 burst balloon 28 16 Shoot arrow x 11 bursting balloon 1016 712example 2input point 12345678output 4explanation one arrow need shoot balloon total 4 arrowsexample 3input point 12233445output 2explanation the balloon burst 2 arrow Shoot arrow x 2 burst balloon 12 23 Shoot arrow x 4 burst balloon 34 45 Constraints1 pointslength 105pointsilength 2231 xstart xend 231 1
0array
give integer array num size n return minimum number move require array element equalIn increment n 1 element array 1 example 1input num 123output 3explanation only move need remember increment elements123 233 343 444example 2input num 111output 0 Constraintsn numslength1 numslength 105109 numsi 109The answer guarantee fit 32bit integer
0array
give integer array nums1 nums2 nums3 nums4 length n return number tuple j k l that0 j k l nnums1i nums2j nums3k nums4l 0 example 1input nums1 12 nums2 21 nums3 12 nums4 02output 2explanationthe tuple are1 0 0 0 1 nums10 nums20 nums30 nums41 1 2 1 2 02 1 1 0 0 nums11 nums21 nums30 nums40 2 1 1 0 0example 2input nums1 0 nums2 0 nums3 0 nums4 0output 1 Constraintsn nums1lengthn nums2lengthn nums3lengthn nums4length1 n 200228 nums1i nums2i nums3i nums4i 228
0array
assume awesome parent want child cookie but child cookieeach child greed factor gi minimum size cookie child content cookie j size sj if sj gi assign cookie j child child content your goal maximize number content child output maximum number Example 1input g 123 s 11output 1explanation you 3 child 2 cookie the greed factor 3 child 1 2 3 and 2 cookie size 1 child greed factor 1 contentyou need output 1example 2input g 12 s 123output 2explanation you 2 child 3 cookie the greed factor 2 child 1 2 you 3 cookie size big gratify child you need output 2 Constraints1 glength 3 1040 slength 3 1041 gi sj 231 1
0array
give array n integer num 132 pattern subsequence integer numsi numsj numsk j k numsi numsk numsjReturn true 132 pattern num return false Example 1input num 1234output falseexplanation there 132 pattern sequenceexample 2input num 3142output trueexplanation there 132 pattern sequence 1 4 2example 3input num 1320output trueexplanation there 132 pattern sequence 1 3 2 1 3 0 1 2 0 Constraintsn numslength1 n 2 105109 numsi 109
0array
you play game involve circular array nonzero integer num each numsi denote number indice forwardbackward locate index iif numsi positive numsi step forward andif numsi negative numsi step backwardsince array circular assume move forward element put element move backwards element put elementA cycle array consist sequence index seq length k wherefollowing movement rule result repeat index sequence seq0 seq1 seqk 1 seq0 every numsseqj positive negativek 1return true cycle num false Example 1input num 21122output trueexplanation the graph show index connect White node jump forward red jumping backwardWe cycle 0 2 3 0 node white jump directionexample 2input num 123456output falseexplanation the graph show index connect White node jump forward red jumping backwardThe cycle size 1 return falseexample 3input num 11514output trueexplanation the graph show index connect White node jump forward red jumping backwardWe cycle 0 1 0 size 1 node jump forward node jump backward cycleWe cycle 3 4 3 node white jumping direction Constraints1 numslength 50001000 numsi 1000numsi 0 follow could solve on time complexity o1 extra space complexity
0array
give string s check construct take substring append multiple copy substre Example 1input s ababoutput trueexplanation it substre ab twiceExample 2Input s abaoutput falseexample 3input s abcabcabcabcoutput trueexplanation it substre abc times substre abcabc twice Constraints1 slength 104s consist lowercase english letter
2string
give integer array num size n return minimum number move require array element equalIn increment decrement element array 1test case design answer fit 32bit integer Example 1input num 123output 2explanationonly move need remember increment decrement element123 223 222example 2input num 11029output 16 Constraintsn numslength1 numslength 105109 numsi 109
0array
we define str s n string str consist string s concatenate n timesFor example str abc 3 abcabcabcWe define string s1 obtain string s2 remove character s2 s1For example s1 abc obtain s2 abdbec base definition remove bolde underlined charactersYou give string s1 s2 integer n1 n2 you string str1 s1 n1 str2 s2 n2Return maximum integer m str str2 m obtain str1 Example 1input s1 acb n1 4 s2 ab n2 2Output 2example 2input s1 acb n1 1 s2 acb n2 1output 1 Constraints1 s1length s2length 100s1 s2 consist lowercase english letters1 n1 n2 106
2string
we define string s infinite wraparound string abcdefghijklmnopqrstuvwxyz s look like thiszabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdGiven stre p return number unique nonempty substring p present s example 1input p aoutput 1explanation only substre p sExample 2input p cacoutput 2explanation there substring c p sExample 3input p zaboutput 6explanation there substring z b za ab zab p s Constraints1 plength 105p consist lowercase english letter
2string
give stre queryip return ipv4 IP valid ipv4 address ipv6 IP valid ipv6 address neither IP correct IP typea valid ipv4 address IP form x1x2x3x4 0 xi 255 xi contain lead zero for example 19216811 19216810 valid ipv4 address 192168011 192168100 19216811 invalid ipv4 addressesa valid IPv6 address IP form x1x2x3x4x5x6x7x8 where1 xilength 4xi hexadecimal string contain digit lowercase english letter f uppercase english letter a FLeading zero allow xiFor example 20010db885a3000000008a2e03707334 2001db885a3008a2e03707334 valid ipv6 address 20010db885a38a2e037j7334 020010db885a3000000008a2e03707334 invalid ipv6 address Example 1Input queryip 172162541output ipv4explanation this valid ipv4 address return ipv4example 2input queryIP 20010db885a3008a2e03707334output ipv6explanation this valid ipv6 address return ipv6example 3input queryip 256256256256output NeitherExplanation this ipv4 address ipv6 address constraintsqueryip consist english letter digit character
2string
you give integer array matchstick matchsticksi length ith matchstick you want use matchstick square you break stick link matchstick exactly timereturn true square false Example 1input matchstick 11222output trueexplanation you form square length 2 square come stick length 1example 2input matchstick 33334output falseexplanation you find way form square matchstick Constraints1 matchstickslength 151 matchsticksi 108
0array
winter come during contest job design standard heater fix warm radius warm housesEvery house warm long house heater warm radius range give position house heater horizontal line return minimum radius standard heater heater cover housesNotice heater follow radius standard warm radius Example 1input house 123 heater 2output 1explanation the heater place position 2 use radius 1 standard house warmedexample 2input house 1234 heater 14output 1explanation the heater place position 1 4 we need use radius 1 standard house warmedexample 3input house 15 heater 2output 3 Constraints1 houseslength heaterslength 3 1041 housesi heatersi 109
0array
the Hamming distance integer number position correspond bit differentGiven integer array num return sum Hamming distance pair integer num Example 1input num 4142output 6explanation in binary representation 4 0100 14 1110 2 0010 justshowe bit relevant casethe answer beHammingDistance4 14 HammingDistance4 2 hammingdistance14 2 2 2 2 6example 2input num 4144output 4 constraints1 numslength 1040 numsi 109the answer give input fit 32bit integer
0array
the median middle value order integer list if size list middle value so median mean middle valuesfor example arr 234 median 3for example arr 1234 median 2 3 2 25You give integer array num integer k there slide window size k move left array right you k number window each time slide window move right positionreturn median array window original array Answers 105 actual value accept Example 1input num 13135367 k 3Output 100000100000100000300000500000600000explanation Window position Median 1 3 1 3 5 3 6 7 1 1 3 1 3 5 3 6 7 1 1 3 1 3 5 3 6 7 1 1 3 1 3 5 3 6 7 3 1 3 1 3 5 3 6 7 5 1 3 1 3 5 3 6 7 6example 2input num 123423142 k 3Output 200000300000300000300000200000300000200000 Constraints1 k numslength 105231 numsi 231 1
0array
a magical string s consist 1 2 obey follow rulesThe string s magical concatenate number contiguous occurrence character 1 2 generate string s itselfthe element s s 1221121221221121122 if group consecutive 1s 2s s 1 22 11 2 1 22 1 22 11 2 11 22 occurrence 1 2s group 1 2 2 1 1 2 1 2 2 1 2 2 you occurrence sequence s itselfgiven integer n return number 1s n number magical string s example 1input n 6output 3explanation the 6 element magical string s 122112 contain 1s return 3example 2input n 1output 1 Constraints1 n 105
2string
you give license key represent string s consist alphanumeric character dash the string separate n 1 group n dash you give integer kWe want reformat string s group contain exactly k character group short k contain character furthermore dash insert group convert lowercase letter uppercasereturn reformatte license key Example 1input s 5f3z2e9w k 4output 5f3z2e9wexplanation the string s split part 4 charactersnote extra dash need removedExample 2input s 25g3j k 2output 25g3jexplanation the string s split part 2 character shorter mention Constraints1 slength 105s consist english letter digits dash 1 k 104
2string
give binary array num return maximum number consecutive 1s array Example 1input num 110111output 3explanation the digit digit consecutive 1s the maximum number consecutive 1s 3example 2input num 101101output 2 Constraints1 numslength 105numsi 0 1
0array
you give integer array num two player play game array player 1 player 2player 1 player 2 turn player 1 start both player start game score 0 at turn player take number end array ie nums0 numsnumslength 1 reduce size array 1 the player add choose number score the game end element arrayreturn true Player 1 win game if score player equal player 1 winner return true you assume player play optimally Example 1input num 152output falseexplanation Initially player 1 choose 1 2 if choose 2 1 player 2 choose 1 2 5 if player 2 choose 5 player 1 leave 1 2 so final score player 1 1 2 3 player 2 5 hence player 1 winner need return falseexample 2input num 152337output trueExplanation Player 1 choose 1 then player 2 choose 5 7 no matter number player 2 choose player 1 choose 233finally player 1 score 234 player 2 12 need return true represent player1 win Constraints1 numslength 200 numsi 107
0array
give integer array num return different possible increase subsequence give array element you return answer orderthe give array contain duplicate equal integer consider special case increase sequence Example 1input num 4677output 464674677474776767777example 2input num 44321output 44 Constraints1 numslength 15100 numsi 100
0array
give integer array num return number reverse pair arraya reverse pair pair j where0 j numslength andnumsi 2 numsj Example 1input num 13231output 2explanation the reverse pair are1 4 nums1 3 nums4 1 3 2 13 4 nums3 3 nums4 1 3 2 1example 2input num 24351output 3explanation the reverse pair are1 4 nums1 4 nums4 1 4 2 12 4 nums2 3 nums4 1 3 2 13 4 nums3 5 nums4 1 5 2 1 constraints1 numslength 5 104231 numsi 231 1
0array
you give integer array num integer targetyou want build expression num add symbol integer num concatenate integersfor example num 2 1 add 2 1 concatenate build expression 21return number different expression build evaluate target Example 1input num 11111 target 3output 5explanation there 5 way assign symbol sum num target 31 1 1 1 1 31 1 1 1 1 31 1 1 1 1 31 1 1 1 1 31 1 1 1 1 3example 2input num 1 target 1output 1 Constraints1 numslength 200 numsi 10000 sumnumsi 10001000 target 1000
0array
our hero Teemo attack enemy Ashe poison attack when Teemo attack Ashe Ashe gets poison exactly duration second more formally attack second t mean Ashe poison inclusive time interval t t duration 1 if Teemo attack poison effect end timer reset poison effect end duration second new attackyou give nondecrease integer array timeserie timeseriesi denote Teemo attack Ashe second timeseriesi integer durationreturn total number second Ashe poison Example 1input timeserie 14 duration 2output 4explanation Teemos attack ashe follow at second 1 teemo attack Ashe poison second 1 2 at second 4 teemo attack Ashe poison second 4 5ashe poison second 1 2 4 5 4 second totalexample 2input timeserie 12 duration 2output 3explanation Teemos attack ashe follow at second 1 teemo attack Ashe poison second 1 2 at second 2 teemo attack reset poison timer Ashe poison second 2 3ashe poison second 1 2 3 3 second total Constraints1 timeSerieslength 1040 timeSeriesi duration 107timeseries sort nondecrease order
0array
the great element element x array great element right x arrayyou give distinct 0indexed integer array nums1 nums2 nums1 subset nums2For 0 nums1length find index j nums1i nums2j determine great element nums2j nums2 if great element answer query 1return array ans length nums1length ansi great element describe Example 1input nums1 412 nums2 1342output 131explanation the great element value nums1 follow 4 underlined nums2 1342 there great element answer 1 1 underline nums2 1342 the great element 3 2 underline nums2 1342 there great element answer 1example 2input nums1 24 nums2 1234output 31explanation the great element value nums1 follow 2 underlined nums2 1234 the great element 3 4 underline nums2 1234 there great element answer 1 Constraints1 nums1length nums2length 10000 nums1i nums2i 104All integer nums1 nums2 uniqueall integer nums1 appear nums2 Follow could find Onums1length nums2length solution
0array
give m x n matrix mat return array element array diagonal order Example 1input mat 123456789output 124753689example 2input mat 1234output 1234 Constraintsm matlengthn matilength1 m n 1041 m n 104105 matij 105
0array
give root binary search tree BST duplicate return mode ie frequently occur element itIf tree mode return orderAssume BST define followsthe leave subtree node contain nod key equal node keythe right subtree node contain nod key greater equal node keyBoth leave right subtree binary search tree Example 1input root 1null22output 2example 2input root 0output 0 constraintsthe number nod tree range 1 104105 Nodeval 105 Follow could extra space Assume implicit stack space incur recursion count
1graph
suppose LeetCode start ipo soon in order sell good price share Venture Capital LeetCode like work project increase capital IPO since limited resource finish k distinct project IPO help LeetCode design good way maximize total capital finish k distinct projectsyou give n project ith project pure profit profitsi minimum capital capitali need start itinitially w capital when finish project obtain pure profit profit add total capitalpick list k distinct project give project maximize final capital return final maximized capitalthe answer guarantee fit 32bit sign integer Example 1Input k 2 w 0 profit 123 capital 011output 4explanation since initial capital 0 start project index 0after finishing obtain profit 1 capital 1with capital 1 start project index 1 project index 2since choose 2 project need finish project index 2 maximum capitaltherefore output final maximized capital 0 1 3 4example 2input k 3 w 0 profit 123 capital 012output 6 Constraints1 k 1050 w 109n profitslengthn capitallength1 n 1050 profitsi 1040 capitali 109
0array
give circular integer array nums ie element numsnumslength 1 nums0 return great number element numsthe great number number x great number traversingorder array mean search circularly find great number if do not exist return 1 number Example 1input num 121output 212explanation the 1s great number 2 the number 2 can not find great number the second 1s great number need search circularly 2example 2input num 12343output 23414 Constraints1 numslength 104109 numsi 109
0array
you give integer array score size n scorei score ith athlete competition all score guarantee uniquethe athlete place base score 1st place athlete high score 2nd place athlete 2nd high score the placement athlete determine rankThe 1st place athlete rank Gold MedalThe 2nd place athlete rank Silver MedalThe 3rd place athlete rank Bronze MedalFor 4th place nth place athlete rank placement number ie xth place athlete rank xReturn array answer size n answeri rank ith athlete Example 1input score 54321output Gold MedalSilver MedalBronze medal45explanation the placement 1st 2nd 3rd 4th 5thexample 2input score 103894output Gold medal5bronze MedalSilver medal4explanation the placement 1st 5th 3rd 2nd 4th Constraintsn scorelength1 n 1040 scorei 106all value score unique
0array
give root binary tree return frequent subtree sum if tie return value high frequency orderthe subtree sum node define sum node value form subtree root node include node Example 1input root 523output 234example 2input root 525output 2 ConstraintsThe number nod tree range 1 104105 Nodeval 105
1graph