question
stringlengths
58
4.29k
label
class label
3 classes
give integer array inorder postorder inorder inorder traversal binary tree postorder postorder traversal tree construct return binary tree Example 1input inorder 9315207 postorder 9157203output 3920nullnull157example 2input inorder 1 postorder 1output 1 Constraints1 inorderlength 3000postorderlength inorderlength3000 inorderi postorderi 3000inorder postorder consist unique valuesEach value postorder appear inorderinorder guarantee inorder traversal treepostorder guarantee postorder traversal tree
0array
give root binary tree return bottomup level order traversal nodes value ie leave right level level leaf root Example 1input root 3920nullnull157Output 1579203example 2input root 1Output 1Example 3input root Output ConstraintsThe number nod tree range 0 20001000 Nodeval 1000
1graph
give integer array num element sort ascending order convert heightbalanced binary search tree Example 1input num 103059output 03910null5explanation 0105null3null9 acceptedExample 2input num 13output 31explanation 1null3 31 heightbalanced bst Constraints1 numslength 104104 numsi 104nums sort strictly increase order
0array
give binary tree determine heightbalanced Example 1input root 3920nullnull157Output trueExample 2input root 12233nullnull44output falseexample 3input root Output true ConstraintsThe number nod tree range 0 5000104 Nodeval 104
1graph
give binary tree find minimum depththe minimum depth number nod short path root node near leaf nodenote a leaf node child Example 1input root 3920nullnull157output 2example 2input root 2null3null4null5null6output 5 ConstraintsThe number nod tree range 0 1051000 Nodeval 1000
1graph
give root binary tree integer targetsum return true tree roottoleaf path add value path equal targetSumA leaf node child Example 1input root 54811null13472nullnullnull1 targetsum 22output trueexplanation the roottoleaf path target sum shownExample 2input root 123 targetsum 5output falseexplanation there roottoleaf path tree1 2 the sum 31 3 the sum 4there roottoleaf path sum 5Example 3input root targetsum 0output falseexplanation since tree roottoleaf path constraintsthe number nod tree range 0 50001000 Nodeval 10001000 targetsum 1000
1graph
give root binary tree integer targetsum return roottoleaf path sum node value path equal targetsum each path return list node value node referencesA roottoleaf path path start root end leaf node a leaf node child Example 1input root 54811null13472nullnull51 targetsum 22output 541125845explanation there path sum equal targetSum5 4 11 2 225 8 4 5 22example 2input root 123 targetsum 5output Example 3input root 12 targetsum 0output ConstraintsThe number nod tree range 0 50001000 Nodeval 10001000 targetsum 1000
1graph
give root binary tree flatten tree link listThe link list use TreeNode class right child pointer point node list leave child pointer nullthe link list order preorder traversal binary tree Example 1input root 12534null6output 1null2null3null4null5null6example 2input root Output Example 3input root 0output 0 constraintsthe number nod tree range 0 2000100 Nodeval 100 Follow can flatten tree inplace o1 extra space
1graph
give string s t return number distinct subsequence s equal tThe test case generate answer fit 32bit sign integer Example 1input s rabbbit t rabbitoutput 3explanationas show 3 way generate rabbit srabbbitrabbbitrabbbitExample 2input s babgbag t bagoutput 5explanationas show 5 way generate bag sbabgbagbabgbagbabgbagbabgbagbabgbag Constraints1 slength tlength 1000 t consist english letter
2string
you give perfect binary tree leave level parent child the binary tree follow definitionstruct Node int val Node leave Node right Node nextPopulate pointer point right node if right node pointer set nullinitially pointer set NULL Example 1input root 1234567output 1234567explanation give perfect binary tree Figure a function populate pointer point right node like Figure B the serialized output level order connect pointer signify end levelexample 2input root Output ConstraintsThe number nod tree range 0 212 11000 Nodeval 1000 FollowupYou use constant extra spacethe recursive approach fine you assume implicit stack space count extra space problem
1graph
give binary treestruct Node int val Node leave Node right Node nextPopulate pointer point right node if right node pointer set nullinitially pointer set NULL Example 1input root 12345null7output 123457explanation give binary tree Figure a function populate pointer point right node like Figure B the serialized output level order connect pointer signify end levelexample 2input root Output ConstraintsThe number nod tree range 0 6000100 Nodeval 100 FollowupYou use constant extra spacethe recursive approach fine you assume implicit stack space count extra space problem
1graph
give integer numrow return numrow Pascals trianglein Pascals triangle number sum number directly show Example 1input numrow 5output 111121133114641example 2input numrow 1output 1 Constraints1 numrow 30
0array
give integer rowindex return rowIndexth 0indexed row Pascals triangleIn Pascals triangle number sum number directly show Example 1input rowindex 3output 1331example 2input rowindex 0output 1Example 3input rowIndex 1output 11 Constraints0 rowindex 33 Follow could optimize algorithm use OrowIndex extra space
0array
give triangle array return minimum path sum bottomFor step adjacent number row more formally index current row index index 1 row Example 1input triangle 2346574183output 11explanation the triangle look like 2 3 4 6 5 74 1 8 3the minimum path sum 2 3 5 1 11 underline aboveexample 2input triangle 10output 10 constraints1 trianglelength 200triangle0length 1triangleilength trianglei 1length 1104 triangleij 104 Follow could on extra space n total number row triangle
0array
you give array price pricesi price give stock ith dayYou want maximize profit choose single day buy stock choose different day future sell stockreturn maximum profit achieve transaction if achieve profit return 0 example 1input price 715364output 5explanation Buy day 2 price 1 sell day 5 price 6 profit 61 5note buying day 2 selling day 1 allow buy sellExample 2input price 76431output 0explanation in case transaction max profit 0 Constraints1 priceslength 1050 pricesi 104
0array
you give integer array price pricesi price give stock ith dayOn day decide buy andor sell stock you hold share stock time however buy immediately sell dayfind return maximum profit achieve Example 1input price 715364output 7explanation Buy day 2 price 1 sell day 3 price 5 profit 51 4Then buy day 4 price 3 sell day 5 price 6 profit 63 3total profit 4 3 7example 2input price 12345output 4explanation Buy day 1 price 1 sell day 5 price 5 profit 51 4total profit 4example 3input price 76431output 0explanation there way positive profit buy stock achieve maximum profit 0 Constraints1 priceslength 3 1040 pricesi 104
0array
you give array price pricesi price give stock ith dayfind maximum profit achieve you complete transactionsnote you engage multiple transaction simultaneously ie sell stock buy Example 1input price 33500314output 6explanation Buy day 4 price 0 sell day 6 price 3 profit 30 3then buy day 7 price 1 sell day 8 price 4 profit 41 3example 2input price 12345output 4explanation Buy day 1 price 1 sell day 5 price 5 profit 51 4note buy day 1 buy day 2 sell later engage multiple transaction time you sell buy againexample 3input price 76431output 0explanation in case transaction ie max profit 0 Constraints1 priceslength 1050 pricesi 105
0array
a path binary tree sequence node pair adjacent node sequence edge connect a node appear sequence note path need pass rootThe path sum path sum node value pathgiven root binary tree return maximum path sum nonempty path Example 1input root 123output 6explanation the optimal path 2 1 3 path sum 2 1 3 6example 2input root 10920nullnull157output 42explanation the optimal path 15 20 7 path sum 15 20 7 42 ConstraintsThe number nod tree range 1 3 1041000 Nodeval 1000
1graph
a phrase palindrome convert uppercase letter lowercase letter remove nonalphanumeric character read forward backward Alphanumeric character include letter numbersgiven stre s return true palindrome false example 1input s a man plan canal PanamaOutput trueExplanation amanaplanacanalpanama palindromeExample 2input s race caroutput falseexplanation raceacar palindromeExample 3input s output trueexplanation s string remove nonalphanumeric characterssince string read forward backward palindrome Constraints1 slength 2 105s consist printable ascii character
2string
give unsorted array integer num return length long consecutive element sequenceyou write algorithm run on time Example 1input num 1004200132output 4explanation the long consecutive element sequence 1 2 3 4 therefore length 4example 2input num 0372584601output 9 constraints0 numslength 105109 numsi 109
0array
you give root binary tree contain digit 0 9 onlyEach roottoleaf path tree represent numberFor example roottoleaf path 1 2 3 represent number 123return total sum roottoleaf number test case generate answer fit 32bit integerA leaf node node child Example 1input root 123Output 25explanationthe roottoleaf path 12 represent number 12The roottoleaf path 13 represent number 13therefore sum 12 13 25example 2input root 49051output 1026explanationthe roottoleaf path 495 represent number 495the roottoleaf path 491 represent number 491the roottoleaf path 40 represent number 40therefore sum 495 491 40 1026 ConstraintsThe number nod tree range 1 10000 Nodeval 9The depth tree exceed 10
1graph
give string s partition s substre partition palindrome return possible palindrome partition s Example 1input s aaboutput aabaabexample 2input s aOutput constraints1 slength 16s contain lowercase english letter
2string
give string s partition s substre partition palindromereturn minimum cut need palindrome partition s Example 1input s aaboutput 1explanation the palindrome partition aab produce 1 cutexample 2input s aoutput 0example 3input s abOutput 1 Constraints1 slength 2000s consists lowercase english letter
2string
give reference node connect undirected graphReturn deep copy clone graphEach node graph contain value int list ListNode neighborsclass Node public int val public ListNode neighbor test case formatfor simplicity node value nod index 1indexed for example node val 1 second node val 2 the graph represent test case adjacency listan adjacency list collection unordered list represent finite graph each list describe set neighbor node graphthe give node node val 1 you return copy give node reference cloned graph Example 1input adjlist 24132413output 24132413explanation there 4 node graph1st node val 1s neighbor 2nd node val 2 4th node val 42nd node val 2s neighbor 1st node val 1 3rd node val 33rd node val 3s neighbor 2nd node val 2 4th node val 44th node val 4s neighbor 1st node val 1 3rd node val 3example 2input adjlist Output Explanation Note input contain list the graph consist node val 1 neighborsExample 3input adjlist Output Explanation this graph node ConstraintsThe number node graph range 0 1001 Nodeval 100nodeval unique nodeThere repeat edge selfloop graphThe Graph connect node visit start give node
1graph
there n gas station circular route gas ith station gasiYou car unlimited gas tank cost costi gas travel ith station 1th station you begin journey tank gas stationsgiven integer arrays gas cost return start gas station index travel circuit clockwise direction return 1 if exist solution guarantee unique Example 1input gas 12345 cost 34512output 3explanationstart station 3 index 3 fill 4 unit gas your tank 0 4 4travel station 4 your tank 4 1 5 8travel station 0 your tank 8 2 1 7travel station 1 your tank 7 3 2 6travel station 2 your tank 6 4 3 5travel station 3 the cost 5 your gas travel station 3therefore return 3 start indexExample 2input gas 234 cost 343output 1explanationyou can not start station 0 1 gas travel stationlet start station 2 fill 4 unit gas your tank 0 4 4travel station 0 your tank 4 3 2 3travel station 1 your tank 3 3 3 3you travel station 2 require 4 unit gas 3therefore can not travel circuit matter start Constraintsn gaslength costlength1 n 1050 gasi costi 104
0array
there n child stand line each child assign rating value give integer array ratingsyou give candy child subject follow requirementsEach child candychildren high rating candy neighborsreturn minimum number candy need distribute candy child example 1input rating 102output 5explanation you allocate second child 2 1 2 candy respectivelyexample 2input rating 122output 4explanation you allocate second child 1 2 1 candy respectivelythe child get 1 candy satisfie condition Constraintsn ratingslength1 n 2 1040 ratingsi 2 104
0array
give nonempty array integer nums element appear twice find single oneyou implement solution linear runtime complexity use constant extra space Example 1input num 221output 1Example 2input num 41212output 4example 3input num 1output 1 Constraints1 numslength 3 1043 104 numsi 3 104Each element array appear twice element appear
0array
give integer array nums element appear time appear exactly find single element return itYou implement solution linear runtime complexity use constant extra space Example 1input num 2232output 3example 2input num 01010199output 99 constraints1 numslength 3 104231 numsi 231 1Each element num appear exactly time element appear
0array
give string s dictionary string worddict return true s segment spaceseparate sequence dictionary wordsnote word dictionary reuse multiple time segmentation Example 1input s leetcode worddict leetcodeoutput trueexplanation return true leetcode segment leet codeExample 2input s applepenapple worddict applepenoutput trueexplanation return true applepenapple segment apple pen applenote allow reuse dictionary wordexample 3input s catsandog worddict catsdogsandandcatoutput false constraints1 slength 3001 worddictlength 10001 worddictilength 20 worddicti consist lowercase english lettersall string worddict unique
2string
give string s dictionary string worddict add space s construct sentence word valid dictionary word return possible sentence orderNote word dictionary reuse multiple time segmentation Example 1input s catsanddog worddict catcatsandsanddogoutput cat dogcat sand dogexample 2input s pineapplepenapple worddict applepenapplepenpinepineappleoutput pine apple pen applepineapple pen applepine applepen appleexplanation note allow reuse dictionary wordexample 3input s catsandog worddict catsdogsandandcatoutput constraints1 slength 201 worddictlength 10001 worddictilength 10 worddicti consist lowercase english lettersall string worddict unique
2string
give root binary tree return preorder traversal nodes value example 1input root 1null23output 123example 2input root Output Example 3input root 1output 1 ConstraintsThe number nod tree range 0 100100 Nodeval 100 Follow Recursive solution trivial iteratively
1graph
give root binary tree return postorder traversal node value example 1input root 1null23output 321example 2input root Output Example 3input root 1output 1 ConstraintsThe number nod tree range 0 100100 Nodeval 100 Follow Recursive solution trivial iteratively
1graph
give array point pointsi xi yi represent point XY plane return maximum number point lie straight line example 1input point 112233output 3example 2input point 113253412314output 4 Constraints1 pointslength 300pointsilength 2104 xi yi 104All point unique
0array
evaluate value arithmetic expression Reverse Polish NotationValid operator each operand integer expressionnote division integer truncate zeroIt guarantee give RPN expression valid that mean expression evaluate result division zero operation Example 1input token 213output 9explanation 2 1 3 9example 2input token 4135output 6explanation 4 13 5 6example 3input tokens 1069311175output 22explanation 10 6 9 3 11 17 5 10 6 12 11 17 5 10 6 132 17 5 10 0 17 5 0 17 5 17 5 22 Constraints1 tokenslength 104tokensi operator integer range 200 200
0array
give input string s reverse order wordsA word define sequence nonspace character the word s separate spacereturn string word reverse order concatenate single spaceNote s contain lead trail space multiple space word the return string single space separate word do include extra space Example 1input s sky blueoutput blue sky theExample 2Input s hello world output world helloexplanation your reversed string contain lead trail spacesexample 3input s good exampleoutput example good aExplanation you need reduce multiple space word single space reverse string Constraints1 slength 104s contain english letter uppercase lowercase digits space there word s Followup if stre datum type mutable language solve inplace O1 extra space
2string
give integer array num find subarray large product return productthe test case generate answer fit 32bit integer Example 1input num 2324output 6explanation 23 large product 6example 2input num 201output 0explanation the result 2 21 subarray Constraints1 numslength 2 10410 numsi 10the product prefix suffix num guarantee fit 32bit integer
0array
suppose array length n sort ascending order rotate 1 n time for example array num 0124567 become4567012 rotate 4 times0124567 rotate 7 timesnotice rotate array a0 a1 a2 an1 1 time result array an1 a0 a1 a2 an2given sort rotate array num unique element return minimum element arrayyou write algorithm run Olog n time Example 1input num 34512output 1explanation the original array 12345 rotate 3 timesexample 2input num 4567012output 0explanation the original array 0124567 rotate 4 timesExample 3input num 11131517output 11explanation the original array 11131517 rotate 4 time Constraintsn numslength1 n 50005000 numsi 5000all integer num uniquenum sort rotate 1 n time
0array
suppose array length n sort ascending order rotate 1 n time for example array num 0144567 become4567014 rotate 4 times0144567 rotate 7 timesnotice rotate array a0 a1 a2 an1 1 time result array an1 a0 a1 a2 an2given sort rotate array num contain duplicate return minimum element arrayyou decrease overall operation step possible example 1input num 135output 1example 2input num 22201output 0 Constraintsn numslength1 n 50005000 numsi 5000nums sort rotate 1 n time follow this problem similar Find Minimum Rotated Sorted Array num contain duplicate would affect runtime complexity how
0array
a peak element element strictly great neighborsgiven 0indexed integer array num find peak element return index if array contain multiple peak return index peaksyou imagine nums1 numsn in word element consider strictly great neighbor outside arrayyou write algorithm run Olog n time Example 1input num 1231output 2explanation 3 peak element function return index number 2example 2input num 1213564output 5explanation your function return index number 1 peak element 2 index number 5 peak element 6 Constraints1 numslength 1000231 numsi 231 1numsi numsi 1 valid
0array
give integer array num return maximum difference successive element sort form if array contain element return 0you write algorithm run linear time use linear extra space Example 1input num 3691output 3explanation the sorted form array 1369 36 69 maximum difference 3example 2input num 10output 0explanation the array contain 2 element return 0 Constraints1 numslength 1050 numsi 109
0array
give version number version1 version2 compare themversion number consist revision join dot each revision consist digit contain lead zero every revision contain character Revisions 0indexed leave right leftmost revision revision 0 revision revision 1 for example 2533 01 valid version numbersto compare version number compare revision lefttoright order revision compare integer value ignore lead zero this mean revision 1 001 consider equal if version number specify revision index treat revision 0 for example version 10 version 11 revision 0s revision 1s 0 1 respectively 0 1return followingIf version1 version2 return 1if version1 version2 return 1Otherwise return 0 example 1input version1 101 version2 1001output 0explanation ignore lead zero 01 001 represent integer 1Example 2input version1 10 version2 100output 0explanation version1 specify revision 2 mean treat 0example 3input version1 01 version2 11output 1explanation version1s revision 0 0 version2s revision 0 1 0 1 version1 version2 constraints1 version1length version2length 500version1 version2 contain digit version1 version2 valid version numbersAll give revision version1 version2 store 32bit integer
2string
give integer represent numerator denominator fraction return fraction string formatIf fractional repeat enclose repeat parenthesesif multiple answer possible return themIt guarantee length answer string 104 give input Example 1input numerator 1 denominator 2output 05Example 2input numerator 2 denominator 1output 2Example 3Input numerator 4 denominator 333output 0012 Constraints231 numerator denominator 231 1denominator 0
2string
give 1indexed array integer number sort nondecrease order find number add specific target number let number numbersindex1 numbersindex2 1 index1 index2 numberslengthreturn index number index1 index2 add integer array index1 index2 length 2the test generate exactly solution you use element twiceyour solution use constant extra space Example 1input number 271115 target 9Output 12Explanation the sum 2 7 9 therefore index1 1 index2 2 we return 1 2example 2input number 234 target 6output 13explanation the sum 2 4 6 therefore index1 1 index2 3 we return 1 3example 3input number 10 target 1output 12Explanation the sum 1 0 1 therefore index1 1 index2 2 we return 1 2 constraints2 numberslength 3 1041000 numbersi 1000number sort nondecrease order1000 target 1000the test generate exactly solution
0array
give integer columnnumber return correspond column title appear Excel sheetfor examplea 1b 2C 3Z 26aa 27ab 28 Example 1input columnnumber 1output AExample 2input columnnumber 28output abexample 3input columnnumber 701output ZY Constraints1 columnnumber 231 1
2string
give array num size n return majority elementthe majority element element appear n 2 time you assume majority element exist array Example 1input num 323Output 3example 2input num 2211122output 2 Constraintsn numslength1 n 5 104109 numsi 109 Followup could solve problem linear time O1 space
0array
give stre columntitle represent column title appear Excel sheet return correspond column numberFor examplea 1b 2C 3Z 26aa 27ab 28 Example 1input columntitle aoutput 1example 2input columntitle ABOutput 28example 3input columntitle ZYOutput 701 Constraints1 columntitlelength 7columntitle consist uppercase english letterscolumnTitle range a FXSHRXW
2string
the demon capture princess imprison bottomright corner dungeon the dungeon consist m x n room lay 2D grid our valiant knight initially position topleft room fight way dungeon rescue princessthe knight initial health point represent positive integer if point health point drop 0 die immediatelysome room guard demon represent negative integer knight lose health enter room room represent 0 contain magic orb increase knight health represent positive integersTo reach princess quickly possible knight decides rightward downward stepreturn knight minimum initial health rescue princessnote room contain threat powerup room knight enter bottomright room princess imprison Example 1input dungeon 233510110305output 7explanation the initial health knight 7 follow optimal path right right DOWN DOWNExample 2Input dungeon 0output 1 Constraintsm dungeonlengthn dungeonilength1 m n 2001000 dungeonij 1000
0array
give list nonnegative integer num arrange form large number return itsince result large need return string instead integer Example 1input num 102output 210example 2input num 3303459output 9534330 Constraints1 numslength 1000 numsi 109
2string
the dna sequence compose series nucleotide abbreviate a C G TFor example ACGAATTCCG DNA sequencewhen study dna useful identify repeat sequence DNAGiven string s represent dna sequence return 10letterlong sequence substring occur dna molecule you return answer order Example 1input s AAAAACCCCCAAAAACCCCCCAAAAAGGGTTTOutput AAAAACCCCCCCCCCAAAAAExample 2input s AAAAAAAAAAAAAOutput AAAAAAAAAA Constraints1 slength 105si a c g t
2string
you give integer array price pricesi price give stock ith day integer kFind maximum profit achieve you complete k transactionsnote you engage multiple transaction simultaneously ie sell stock buy Example 1input k 2 price 241output 2explanation Buy day 1 price 2 sell day 2 price 4 profit 42 2example 2input k 2 price 326503output 7explanation Buy day 2 price 2 sell day 3 price 6 profit 62 4 then buy day 5 price 0 sell day 6 price 3 profit 30 3 Constraints1 k 1001 priceslength 10000 pricesi 1000
0array
give array rotate array right k step k nonnegative Example 1input num 1234567 k 3output 5671234explanationrotate 1 step right 7123456rotate 2 step right 6712345rotate 3 step right 5671234example 2input num 1100399 k 2output 3991100explanation rotate 1 step right 9911003rotate 2 step right 3991100 Constraints1 numslength 105231 numsi 231 10 k 105 Follow uptry come solution there different way solve problemcould inplace o1 extra space
0array
you professional robber planning rob house street each house certain money stash constraint stop robbing adjacent house security system connect automatically contact police adjacent house break nightgiven integer array num represent money house return maximum money rob tonight alert police Example 1input num 1231output 4explanation Rob house 1 money 1 rob house 3 money 3total rob 1 3 4example 2input num 27931output 12explanation Rob house 1 money 2 rob house 3 money 9 rob house 5 money 1total rob 2 9 1 12 constraints1 numslength 1000 numsi 400
0array
give root binary tree imagine stand right return value node order Example 1input root 123null5null4Output 134example 2input root 1null3output 13example 3input root Output ConstraintsThe number nod tree range 0 100100 Nodeval 100
1graph
give integer n return number prime number strictly n Example 1input n 10output 4explanation there 4 prime number 10 2 3 5 7example 2input n 0output 0Example 3Input n 1Output 0 Constraints0 n 5 106
0array
give string s t determine isomorphictwo string s t isomorphic character s replace tAll occurrence character replace character preserve order character no character map character character map Example 1input s egg t addoutput trueexample 2Input s foo t baroutput falseexample 3Input s paper t titleoutput true Constraints1 slength 5 104tlength slength t consist valid ascii character
2string
there total numcourse course label 0 numcourses 1 you give array prerequisite prerequisitesi ai bi indicate course bi want course aifor example pair 0 1 indicate course 0 course 1return true finish course otherwise return false Example 1input numcourses 2 prerequisite 10output trueexplanation there total 2 course to course 1 finish course 0 so possibleExample 2input numcourses 2 prerequisite 1001output falseexplanation there total 2 course to course 1 finish course 0 course 0 finish course 1 so impossible Constraints1 numcourses 20000 prerequisiteslength 5000prerequisitesilength 20 ai bi numCoursesAll pair prerequisitesi unique
1graph
a trie pronounce try prefix tree tree data structure efficiently store retrieve key dataset string there application datum structure autocomplete spellcheckerimplement Trie classtrie Initializes trie objectvoid insertstre word Inserts string word trieboolean searchString word Returns true string word trie ie insert false otherwiseboolean startswithstre prefix return true previously insert string word prefix prefix false Example 1inputtrie insert search search startswith insert search apple apple app app app appoutputnull null true false true null trueExplanationTrie trie new Trietrieinsertappletriesearchapple return Truetriesearchapp return FalsetriestartsWithapp return Truetrieinsertapptriesearchapp return true constraints1 wordlength prefixlength 2000word prefix consist lowercase English lettersat 3 104 call total insert search startswith
2string
give array positive integer num positive integer target return minimal length subarray sum great equal target if subarray return 0 instead example 1input target 7 num 231243output 2explanation the subarray 43 minimal length problem constraintexample 2input target 4 num 144output 1Example 3input target 11 num 11111111output 0 Constraints1 target 1091 numslength 1051 numsi 104 Follow if figure on solution try code solution time complexity on logn
0array
there total numcourse course label 0 numcourses 1 you give array prerequisite prerequisitesi ai bi indicate course bi want course aifor example pair 0 1 indicate course 0 course 1return order course finish course if valid answer return if impossible finish course return array Example 1input numcourses 2 prerequisite 10output 01Explanation there total 2 course to course 1 finish course 0 so correct course order 01Example 2input numcourses 4 prerequisite 10203132output 0213explanation there total 4 course to course 3 finish course 1 2 both course 1 2 take finished course 0So correct course order 0123 another correct order 0213example 3input numcourses 1 prerequisite output 0 Constraints1 numcourses 20000 prerequisiteslength numcourses numcourses 1prerequisitesilength 20 ai bi numCoursesai biAll pair ai bi distinct
1graph
you professional robber planning rob house street each house certain money stash all house place arrange circle that mean house neighbor meanwhile adjacent house security system connect automatically contact police adjacent house break nightgiven integer array num represent money house return maximum money rob tonight alert police Example 1input num 232output 3explanation you rob house 1 money 2 rob house 3 money 2 adjacent housesexample 2input num 1231output 4explanation Rob house 1 money 1 rob house 3 money 3total rob 1 3 4example 3input num 123output 3 Constraints1 numslength 1000 numsi 1000
0array
you give stre s you convert s palindrome add character itreturn short palindrome find perform transformation Example 1input s aacecaaaoutput aaacecaaaExample 2input s abcdoutput dcbabcd constraints0 slength 5 104s consist lowercase english letter
2string
give integer array num integer k return kth large element arrayNote kth large element sorted order kth distinct elementyou solve on time complexity Example 1input num 321564 k 2Output 5Example 2input num 323124556 k 4Output 4 Constraints1 k numslength 105104 numsi 104
0array
find valid combination k number sum n follow condition trueonly number 1 9 usedeach number oncereturn list possible valid combination the list contain combination twice combination return order Example 1input k 3 n 7output 124explanation1 2 4 7there valid combinationsexample 2input k 3 n 9output 126135234explanation1 2 6 91 3 5 92 3 4 9there valid combinationsExample 3input k 4 n 1output Explanation there valid combinationsuse 4 different number range 19 small sum 1234 10 10 1 valid combination Constraints2 k 91 n 60
0array
give integer array num return true value appear twice array return false element distinct Example 1input num 1231output trueExample 2input num 1234output falseexample 3input num 1113343242output true Constraints1 numslength 105109 numsi 109
0array
a citys skyline outer contour silhouette form building city view distance give location height building return skyline form building collectivelyThe geometric information building give array building buildingsi lefti righti heightilefti x coordinate leave edge ith buildingrighti x coordinate right edge ith buildingheighti height ith buildingyou assume building perfect rectangle ground absolutely flat surface height 0the skyline represent list key point sort xcoordinate form x1y1x2y2 each key point leave endpoint horizontal segment skyline point list ycoordinate 0 mark skylines termination rightmost building end any ground leftmost rightmost building skyline contournote there consecutive horizontal line equal height output skyline for instance 2 34 57 511 512 7 acceptable line height 5 merge final output 2 34 512 7 Example 1input building 291037155121215201019248output 2103157121201510208240explanationfigure a show building inputfigure b show skyline form building the red point figure B represent key point output listExample 2input building 023253output 0350 constraints1 buildingslength 1040 lefti righti 231 11 heighti 231 1buildings sorted lefti nondecrease order
0array
give integer array num integer k return true distinct index j array numsi numsj absi j k Example 1input num 1231 k 3Output trueExample 2input num 1011 k 1Output trueExample 3input num 123123 k 2output false constraints1 numslength 105109 numsi 1090 k 105
0array
you give integer array nums integer indexdiff valuedifffind pair indice j thati jabsi j indexDiffabsnumsi numsj valueDiff andreturn true pair exist false Example 1input num 1231 indexdiff 3 valuediff 0output trueexplanation we choose j 0 3We satisfy conditionsi j 0 3absi j indexDiff abs0 3 3absnumsi numsj valueDiff abs1 1 0example 2input num 159159 indexdiff 2 valuediff 3output falseexplanation after try possible pair j satisfy condition return false constraints2 numslength 105109 numsi 1091 indexdiff numslength0 valueDiff 109
0array
give m x n binary matrix fill 0s 1s find large square contain 1 return area Example 1input matrix 10100101111111110010output 4example 2input matrix 0110output 1example 3input matrix 0output 0 Constraintsm matrixlengthn matrixilength1 m n 300matrixij 0 1
0array
give root complete binary tree return number node treeaccorde Wikipedia level possibly completely fill complete binary tree node level far leave possible it 1 2h node inclusive level hDesign algorithm run on time complexity Example 1input root 123456output 6Example 2input root Output 0example 3input root 1output 1 ConstraintsThe number nod tree range 0 5 1040 Nodeval 5 104the tree guarantee complete
1graph
give string s represent valid expression implement basic calculator evaluate return result evaluationnote you allow use builtin function evaluate string mathematical expression eval Example 1Input s 1 1output 2example 2Input s 21 2 output 3example 3input s 1452368output 23 constraints1 slength 3 105s consist digit s represent valid expression unary operation ie 1 2 3 invalid unary operation ie 1 2 3 validthere consecutive operator inputEvery number run calculation fit sign 32bit integer
2string
give root binary tree invert tree return root Example 1input root 4271369output 4729631example 2input root 213output 231example 3input root Output ConstraintsThe number nod tree range 0 100100 Nodeval 100
1graph
give string s represents expression evaluate expression return value the integer division truncate zeroyou assume give expression valid all intermediate result range 231 231 1note you allow use builtin function evaluate string mathematical expression eval Example 1input s 322output 7example 2input s 32 output 1example 3input s 35 2 output 5 constraints1 slength 3 105s consist integer operator separate number spacess represent valid expressionall integer expression nonnegative integer range 0 231 1the answer guarantee fit 32bit integer
2string
you give sort unique integer array numsA range ab set integer b inclusivereturn small sorted list range cover number array exactly that element num cover exactly range integer x x range numseach range ab list output asab ba b Example 1input num 012457output 02457explanation the range are02 0245 4577 7Example 2input num 0234689output 024689explanation the range are00 024 2466 689 89 constraints0 numslength 20231 numsi 231 1all value num uniquenum sort ascending order
0array
give integer array size n find element appear n3 times Example 1input num 323Output 3example 2input num 1Output 1example 3input num 12Output 12 Constraints1 numslength 5 104109 numsi 109 Follow could solve problem linear time O1 space
0array
give root binary search tree integer k return kth small value 1indexed value nod tree example 1input root 314null2 k 1Output 1Example 2input root 53624nullnull1 k 3output 3 ConstraintsThe number nod tree n1 k n 1040 Nodeval 104 Follow if BST modify ie insert delete operation need find kth smallest frequently optimize
1graph
give binary search tree BST find low common ancestor LCA node give node bstaccorde definition LCA Wikipedia the low common ancestor define node p q low node T p q descendant allow node descendant Example 1input root 6280479nullnull35 p 2 q 8output 6explanation the LCA nod 2 8 6example 2input root 6280479nullnull35 p 2 q 4output 2explanation the LCA nod 2 4 2 node descendant accord LCA definitionexample 3input root 21 p 2 q 1output 2 ConstraintsThe number nod tree range 2 105109 Nodeval 109All Nodeval uniquep qp q exist BST
1graph
give binary tree find low common ancestor LCA give node treeaccorde definition LCA Wikipedia the low common ancestor define node p q low node T p q descendant allow node descendant Example 1input root 3516208nullnull74 p 5 q 1output 3explanation the LCA nod 5 1 3example 2input root 3516208nullnull74 p 5 q 4output 5explanation the LCA nod 5 4 5 node descendant accord LCA definitionexample 3input root 12 p 1 q 2output 1 ConstraintsThe number nod tree range 2 105109 Nodeval 109All Nodeval uniquep qp q exist tree
1graph
give integer array num return array answer answeri equal product element num numsithe product prefix suffix num guarantee fit 32bit integeryou write algorithm run on time division operation Example 1input num 1234output 241286example 2input num 11033output 00900 constraints2 numslength 10530 numsi 30the product prefix suffix num guarantee fit 32bit integer Follow can solve problem o1 extra space complexity the output array count extra space space complexity analysis
0array
you give array integer num slide window size k move left array right you k number window each time slide window move right positionReturn max slide window Example 1input num 13135367 k 3Output 335567explanation Window position Max 1 3 1 3 5 3 6 7 3 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 5 1 3 1 3 5 3 6 7 6 1 3 1 3 5 3 6 7 7example 2input num 1 k 1Output 1 Constraints1 numslength 105104 numsi 1041 k numslength
0array
write efficient algorithm search value target m x n integer matrix matrix this matrix follow propertiesinteger row sorted ascending leave rightinteger column sort ascend Example 1input matrix 14711152581219369162210131417241821232630 target 5output trueExample 2input matrix 14711152581219369162210131417241821232630 target 20output false Constraintsm matrixlengthn matrixilength1 n m 300109 matrixij 109All integer row sort ascending orderAll integer column sort ascend order109 target 109
0array
give string expression number operator return possible result compute different possible way group number operator you return answer orderthe test case generate output value fit 32bit integer number different result exceed 104 Example 1input expression 211output 02explanation211 0 211 2example 2input expression 2345output 3414101010explanation2345 34 2345 14 2345 10 2345 10 2345 10 Constraints1 expressionlength 20expression consist digits operator all integer value input expression range 0 99
2string
give string s t return true t anagram s false otherwiseAn Anagram word phrase form rearrange letter different word phrase typically original letter exactly Example 1input s anagram t nagaramoutput trueexample 2input s rat t caroutput false constraints1 slength tlength 5 104s t consist lowercase english letter follow what input contain unicode character how adapt solution case
2string
give integer array num exactly element appear element appear exactly twice find element appear you return answer orderyou write algorithm run linear runtime complexity use constant extra space Example 1input num 121325output 35explanation 5 3 valid answerexample 2input num 10output 10example 3input num 01output 10 constraints2 numslength 3 104231 numsi 231 1each integer num appear twice integer appear
0array
give array num contain n distinct number range 0 n return number range miss array Example 1input num 301output 2explanation n 3 3 number number range 03 2 miss number range appear numsexample 2input num 01output 2explanation n 2 2 number number range 02 2 miss number range appear numsexample 3input num 964235701output 8explanation n 9 9 number number range 09 8 miss number range appear num Constraintsn numslength1 n 1040 numsi nAll number num unique Follow could implement solution o1 extra space complexity on runtime complexity
0array
convert nonnegative integer num english word representation Example 1input num 123Output one Hundred Twenty ThreeExample 2input num 12345output Twelve Thousand three Hundred Forty FiveExample 3input num 1234567output one million two hundred Thirty Four Thousand Five Hundred Sixty Seven constraints0 num 231 1
2string
give array integer citation citationsi number citation researcher receive ith paper return compute researcher hindexaccorde definition hindex Wikipedia a scientist index h h n paper h citation n h paper h citation eachIf possible value h maximum take hindex Example 1input citation 30615output 3explanation 30615 mean researcher 5 paper total receive 3 0 6 1 5 citation respectivelysince researcher 3 paper 3 citation remain 3 citation hindex 3example 2input citation 131output 1 Constraintsn citationslength1 n 50000 citationsi 1000
0array
give array integer citation citationsi number citation researcher receive ith paper citation sort ascending order return compute researcher hindexaccorde definition hindex Wikipedia a scientist index h h n paper h citation n h paper h citation eachIf possible value h maximum take hindexyou write algorithm run logarithmic time Example 1input citation 01356output 3explanation 01356 mean researcher 5 paper total receive 0 1 3 5 6 citation respectivelysince researcher 3 paper 3 citation remain 3 citation hindex 3example 2input citation 12100output 2 Constraintsn citationslength1 n 1050 citationsi 1000citation sort ascending order
0array
give integer n return number perfect square number sum nA perfect square integer square integer word product integer for example 1 4 9 16 perfect square 3 11 Example 1input n 12Output 3explanation 12 4 4 4example 2input n 13Output 2explanation 13 4 9 constraints1 n 104
1graph
give stre num contain digits integer target return possibility insert binary operators andor digits num resultant expression evaluate target valuenote operand return expression contain lead zero Example 1input num 123 target 6output 123123explanation both 123 123 evaluate 6example 2input num 232 target 8output 232232explanation both 232 232 evaluate 8example 3input num 3456237490 target 9191output Explanation there expression create 3456237490 evaluate 9191 Constraints1 numlength 10num consist digits231 target 231 1
2string
give integer array num 0s end maintain relative order nonzero elementsnote inplace make copy array example 1input num 010312output 131200example 2input num 0output 0 Constraints1 numslength 104231 numsi 231 1 Follow could minimize total number operation
0array
design iterator support peek operation exist iterator addition hasnext operationsimplement PeekingIterator classpeekingiteratoriteratorint num Initializes object give integer iterator iteratorint Returns element array move pointer elementboolean hasnext return true element arrayint peek Returns element array move pointerNote each language different implementation constructor Iterator support int boolean hasnext function Example 1inputpeekingiterator peek hasNext1 2 3 outputnull 1 2 2 3 falseexplanationpeekingiterator peekingiterator new PeekingIterator1 2 3 123peekingiteratornext return 1 pointer move element 123peekingiteratorpeek return 2 pointer 123peekingiteratornext return 2 pointer move element 123peekingiteratornext return 3 pointer move element 123peekingiteratorhasnext return false Constraints1 numslength 10001 numsi 1000all call peek validAt 1000 call hasnext peek Follow how extend design generic work type integer
0array
give array integer num contain n 1 integer integer range 1 n inclusivethere repeat number num return repeat numberyou solve problem modifying array num use constant extra space Example 1input num 13422output 2example 2input num 31342output 3 Constraints1 n 105numslength n 11 numsi nAll integer num appear precisely integ appear times Follow uphow prove duplicate number exist numscan solve problem linear runtime complexity
0array
accord Wikipedias article the Game Life know simply Life cellular automaton devise british mathematician John Horton Conway 1970The board m x n grid cell cell initial state live represent 1 dead represent 0 each cell interact neighbor horizontal vertical diagonal follow rule take Wikipedia articleany live cell few live neighbor die cause underpopulationany live cell live neighbor live generationany live cell live neighbor die overpopulationany dead cell exactly live neighbor live cell reproductionThe state create apply rule simultaneously cell current state birth death occur simultaneously give current state m x n grid board return state Example 1input board 010001111000output 000101011010example 2input board 1110output 1111 Constraintsm boardlengthn boardilength1 m n 25boardij 0 1 Follow upcould solve inplace Remember board need update simultaneously you update cell use update value update cellsin question represent board 2D array in principle board infinite cause problem active area encroach border array ie live cell reach border how address problem
0array
give pattern string s find s follow patternhere follow mean match bijection letter pattern nonempty word s Example 1input pattern abba s dog cat cat dogOutput trueExample 2input pattern abba s dog cat cat fishOutput falseexample 3input pattern aaaa s dog cat cat dogoutput false Constraints1 patternlength 300pattern contain lowercase english letters1 slength 3000s contain lowercase english letter space s contain lead trail spacesAll word s separate single space
2string
you play Bulls Cows game friendyou write secret number ask friend guess number when friend make guess provide hint follow infothe number bull digit guess correct positionthe number cow digit guess secret number locate wrong position specifically nonbull digit guess rearrange bullsgiven secret number secret friend guess guess return hint friend guessthe hint format xAyB x number bull y number cow note secret guess contain duplicate digit Example 1input secret 1807 guess 7810output 1a3bexplanation Bulls connect cow underlined1807 7810example 2input secret 1123 guess 0111output 1a1bexplanation bull connect cow underlined1123 1123 0111 0111note unmatched 1s count cow nonbull digit rearrange allow 1 bull Constraints1 secretlength guesslength 1000secretlength guesslengthsecret guess consist digit
2string
give integer array num return length long strictly increase subsequence example 1input num 109253710118output 4explanation the long increase subsequence 237101 length 4example 2input num 010323output 4example 3input num 7777777output 1 Constraints1 numslength 2500104 numsi 104 Follow can come algorithm run on logn time complexity
0array
give integer array num handle multiple query follow typecalculate sum element num index leave right inclusive leave rightimplement NumArray classNumArrayint num Initializes object integer array numsint sumrangeint leave int right return sum element num index leave right inclusive ie numsleft numsleft 1 numsright example 1inputnumarray sumrange sumrange sumrange2 0 3 5 2 1 0 2 2 5 0 5outputnull 1 1 3explanationnumarray numarray new numarray2 0 3 5 2 1numarraysumrange0 2 return 2 0 3 1numarraysumrange2 5 return 3 5 2 1 1numarraysumrange0 5 return 2 0 3 5 2 1 3 constraints1 numslength 104105 numsi 1050 leave right numslengthat 104 call sumrange
0array
give 2D matrix matrix handle multiple query follow typecalculate sum element matrix inside rectangle define upper left corner row1 col1 low right corner row2 col2Implement NumMatrix classNumMatrixint matrix Initializes object integer matrix matrixint sumRegionint row1 int col1 int row2 int col2 return sum element matrix inside rectangle define upper left corner row1 col1 low right corner row2 col2You design algorithm sumregion work o1 time complexity Example 1inputnummatrix sumregion sumregion sumRegion3 0 1 4 2 5 6 3 2 1 1 2 0 1 5 4 1 0 1 7 1 0 3 0 5 2 1 4 3 1 1 2 2 1 2 2 4outputnull 8 11 12explanationnummatrix nummatrix new nummatrix3 0 1 4 2 5 6 3 2 1 1 2 0 1 5 4 1 0 1 7 1 0 3 0 5nummatrixsumregion2 1 4 3 return 8 ie sum red rectanglenumMatrixsumRegion1 1 2 2 return 11 ie sum green rectanglenumMatrixsumRegion1 2 2 4 return 12 ie sum blue rectangle Constraintsm matrixlengthn matrixilength1 m n 200104 matrixij 1040 row1 row2 m0 col1 col2 nAt 104 call sumregion
0array
an additive number string digit form additive sequenceA valid additive sequence contain number except number subsequent number sequence sum precede twogiven string contain digit return true additive number false otherwisenote Numbers additive sequence lead zeros sequence 1 2 03 1 02 3 invalid Example 1input 112358output trueexplanation the digit form additive sequence 1 1 2 3 5 8 1 1 2 1 2 3 2 3 5 3 5 8example 2input 199100199output trueexplanation the additive sequence 1 99 100 199 1 99 100 99 100 199 Constraints1 numlength 35num consist digits follow how handle overflow large input integer
2string
give integer array num handle multiple query follow typesupdate value element numscalculate sum element num index leave right inclusive leave rightimplement NumArray classNumArrayint num Initializes object integer array numsvoid updateint index int val Updates value numsindex valint sumrangeint leave int right return sum element num index leave right inclusive ie numsleft numsleft 1 numsright Example 1inputnumarray sumrange update sumrange1 3 5 0 2 1 2 0 2outputnull 9 null 8explanationnumarray numarray new NumArray1 3 5numarraysumrange0 2 return 1 3 5 9numarrayupdate1 2 num 1 2 5numarraysumrange0 2 return 1 2 5 8 constraints1 numslength 3 104100 numsi 1000 index numslength100 val 1000 leave right numslengthat 3 104 call update sumrange
0array