ByteDance編碼面試問題

文章推薦指數: 80 %
投票人數:10人

大量的ByteDance面試問題,通常在ByteDance中提出。

練習並破解ByteDance編碼面試。

Skiptocontent MenuTutorialCup MenuTwitterFacebookLinkedInBufferRedditTumblrTwitterFacebookLinkedInBufferRedditTumblrCategoriesofQuestionsByteDanceArrayQuestionsByteDanceStringQuestionsByteDanceTreeQuestionsByteDanceStackQuestionsByteDanceQueueQuestionsByteDanceMatrixQuestionsByteDanceOtherQuestionsByteDanceArrayQuestionsQuestion1.CombinationSumLeetcodeSolutionTheproblemCombinationSumLeetcodeSolutionprovidesusanarrayorlistofintegersandatarget.Wearetoldtofindthecombinationsthatcanbemadeusingtheseintegersanynumberoftimesthatadduptothegiventarget.Somoreformally,wecanusethegiven...ReadmoreQuestion2.MaximumSubarrayLeetcodeSolutionProblemStatementGivenanintegerarraynums,findthecontiguoussubarray(containingatleastonenumber)whichhasthelargestsumandreturnitssum.Examplenums=[-2,1,-3,4,-1,2,1,-5,4]6Explanation:[4,-1,2,1]hasthelargestsum=6.nums=[-1]-1Approach1(DivideandConquer)Inthisapproach...ReadmoreQuestion3.UniquePathsLeetcodeSolutionTheproblemUniquePathsLeetcodeSolutionstatesthatyouaregiventwointegersrepresentingthesizeofagrid.Usingthesizeofthegrid,thelength,andbreadthofthegrid.Weneedtofindthenumberofuniquepathsfromthetopleftcornerofthegridto...ReadmoreQuestion4.MergeSortedArraysLeetcodeSolutionIntheproblem“MergeSortedArrays”,wearegiventwoarrayssortedinnon-descendingorder.Thefirstarrayisnotfullyfilledandhasenoughspacetoaccommodateallelementsofthesecondarrayaswell.Wehavetomergethetwoarrays,suchthatthefirstarraycontainselements...ReadmoreQuestion5.SearchinRotatedSortedArrayLeetcodeSolutionConsiderasortedarraybutoneindexwaspickedandthearraywasrotatedatthatpoint.Now,oncethearrayhasbeenrotatedyouarerequiredtofindaparticulartargetelementandreturnitsindex.Incase,theelementisnotpresent,return-1.Theproblemisgenerally...ReadmoreQuestion6.KthlargestelementinanArrayLeetcodeSolutionsInthisproblem,wehavetoreturnthekthlargestelementinanunsortedarray.Notethatthearraycanhaveduplicates.So,wehavetofindtheKth largestelementinthesortedorder,notthedistinctKthlargestelement.ExampleA={4,2,5,3...ReadmoreQuestion7.FindFirstandLastPositionofElementinSortedArrayLeetcodeSolutionProblemstatementInthisarticletitled“FindFirstandLastPositionofElementinSortedArrayLeetcodeSolution,”wewilldiscussthesolutiontoaleetcodeproblem.Inthegivenproblemwearegivenanarray.Wearealsogivenatargetelement.Elementsinthearrayaresequencedin...ReadmoreQuestion8.CountallsubsequenceshavingproductlessthanKTheproblem“CountallsubsequenceshavingproductlessthanK”statesthatyouaregivenanarrayofintegers.NowfindthenumberofsubsequencesthathaveaproductlessthanagiveninputK.Examplea[]={1,2,3,4,5}k=8Numberofsubsequencesless...ReadmoreQuestion9.PrintmodifiedarrayafterexecutingthecommandsofadditionandsubtractionYouaregivenanarrayofsizen,initiallyallthevaluesinthearraywillbe0,andthequeries.Eachquerycontainsthefourvalues,typeofthequeryT,leftpointoftherange,therightpointofarangeandanumberk,youhaveto...ReadmoreQuestion10.BestTimetoBuyandSellStockProblemStatementTheproblem“BestTimetoBuyandSellStock”statesthatyouaregivenanarrayofpricesoflengthn,wheretheithelementstoresthepriceofstockonithday.Ifwecanmakeonlyonetransaction,thatis,tobuyononedayand...ReadmoreQuestion11.TopKFrequentElementsProblemStatementIntopKfrequentelementswehavegivenanarraynums[],findthekmostfrequentlyoccurringelements.Examplesnums[]={1,1,1,2,2,3}k=212 nums[]={1}k=11NaiveApproachforTopKFrequentElementsBuild...ReadmoreQuestion12.SumofminimumandmaximumelementsofallsubarraysofsizekProblemStatementTheproblem“Sumofminimumandmaximumelementsofallsubarraysofsizek”statesthatyouaregivenanarraycontainingpositiveandnegativeintegers,findthesumofminimumandmaximumelementsofallthesub-arraysofsizek.Examplesarr[]={5,9,8,3,...ReadmoreQuestion13.MinimumnumberofdistinctelementsafterremovingmitemsProblemStatementTheproblem“Minimumnumberofdistinctelementsafterremovingmitems”statesthatyouhaveanarrayandanintegerm.Eachelementofthearrayindicatesanitemid’s.Theproblemstatementaskstoremovemelementsinsuchawaythatthereshouldbeaminimum...ReadmoreQuestion14.SubsetLeetcodeInSubsetLeetcodeproblemwehavegivenasetofdistinctintegers,nums,printallsubsets(thepowerset).Note:Thesolutionsetmustnotcontainduplicatesubsets.AnarrayAisasubsetofanarrayBifacanbeobtainedfromBbydeletingsome(possibly,zero...ReadmoreQuestion15.WordSearchWordsearchissomethingliketheword-findingpuzzlesatsometimeinourlife.TodayIbringtothetableamodifiedcrossword.MyreadersmustbeabitperplexedastowhatIamtalkingabout.WithoutwastinganymoretimeletusgettotheproblemstatementCan...ReadmoreQuestion16.MedianofTwoSortedArraysGiventwosortedarraysAandBofsizenandmrespectively.Findthemedianofthefinalsortedarrayobtainedaftermergingthegiventwoarraysorinotherwords,wesaythatfindmedianoftwosortedarrays.(Expectedtimecomplexity:O(log(n)))Approach1for...ReadmoreQuestion17.SearchanElementinSortedRotatedArrayInsearchinsortedrotatedarrayproblemwehavegivenasortedandrotatedarrayandanelement,checkifthegivenelementispresentinthearrayornot.ExamplesInputnums[]={2,5,6,0,0,1,2}target=0OutputtrueInputnums[]={2,...ReadmoreQuestion18.SearchinSortedRotatedArrayAnelementsearchinsortedrotatedarraycanbefoundusingbinarysearchinO(logn)time.TheobjectiveofthispostistofindagivenelementinasortedrotatedarrayinO(logn)time.Someexampleofasortedrotatedarrayisgiven.ExampleInput:arr[]={7,8,9,10,1,2,3,5,6};...ReadmoreQuestion19.MaximumSubarrayIntheMaximumSubarrayproblemwehavegivenanintegerarraynums,findthecontiguoussubarraywhichhasthelargestsumandprintthemaximumsumsubarrayvalue.ExampleInputnums[]={-2,1,-3,4,-1,2,1,-5,4}Output6AlgorithmThegoalistofind...ReadmoreQuestion20.FindPeakElementLet’sunderstandFindPeakElementproblem.Todaywehavewithusanarraythatneedsitspeakelement.Now,youmustbewonderingastowhatdoImeanbythepeakelement?Thepeakelementisonewhichisgreaterthanallitsneighbours.Example:Givenanarrayof...ReadmoreQuestion21.CoinChangeProblemCoinChangeProblem–Givensomecoinsofdifferentvaluesc1,c2,…,cs(Forinstance:1,4,7….).Weneedanamountn.Usethesegivencoinstoformtheamountn.Youcanuseacoinasmanytimesasrequired.Findthetotalnumberofwaysinwhich...ReadmoreQuestion22.MaximumSubarraySumusingDivideandConquerProblemStatementInthe“MaximumSubarraySumusingDivideandConquer”problemwehavegivenanarrayofbothpositiveandnegativeintegers.Writeaprogramthatwillfindthelargestsumofthecontiguoussubarray.InputFormatThefirstlinecontaininganintegerN.Second-linecontaininganarrayof...ReadmoreQuestion23.ArrangegivenNumberstoFormtheBiggestNumberIIProblemStatementInthe“ArrangegivenNumberstoFormtheBiggestNumberII”problem,wehavegivenanarrayofpositiveintegers. Arrangetheminsuchawaythatthearrangementwillformthelargestvalue.InputFormatThefirstandonlyonelinecontaininganintegern.Second-linecontaining...ReadmoreQuestion24.MaximumSumIncreasingSubsequenceProblemStatementInthe“MaximumSumIncreasingSubsequence”problemwehavegivenanarray.Findthesumofthemaximumsubsequenceofthegivenarray,thatistheintegersinthesubsequenceareinsortedorder.Asubsequenceisapartofanarraywhichisasequencethatis...ReadmoreQuestion25.FindthePeakElementfromanArrayProblemStatementInthe“FindthePeakElementfromanArray”problemwehavegivenaninputarrayofintegers.Findapeakelement.Inanarray,anelementisapeakelement,iftheelementisgreaterthanboththeneighbours.Forcornerelements,wecanconsidertheonly...ReadmoreQuestion26.PartitionProblemProblemStatementInthePartitionproblem,wehavegivenasetthatcontainsnelements.Findwhetherthegivensetcanbedividedintotwosetswhosesumofelementsinthesubsetsisequal.ExampleInputarr[]={4,5,11,9,8,3}OutputYesExplanationThearray...ReadmoreQuestion27.SubarraywithGivenSumProblemStatementInthesubarraywiththegivensumproblem,wehavegivenanarraycontainingnpositiveelements.Wehavetofindthesubarrayinwhichthesumofalltheelementsofthesubarrayequaltoagiven_sum.Subarrayisobtainedfromtheoriginalarraybydeletingsome...ReadmoreQuestion28.MergeTwoSortedArraysProblemStatementInmergetwosortedarraysproblem,wehavegiventwoinputsortedarrays,weneedtomergethesetwoarrayssuchthattheinitialnumbersaftercompletesortingshouldbeinthefirstarrayandremaininginthesecondarray.ExampleInputA[]={1,3,5,7,...ReadmoreQuestion29.CountofTripletsWithSumLessthanGivenValueProblemStatementWehavegivenanarraycontainingNnumberofelements.Inthegivenarray,Countthenumberoftripletswithasumlessthanthegivenvalue.ExampleInputa[]={1,2,3,4,5,6,7,8}Sum=10Output7Possibletripletsare:...ReadmoreQuestion30.MergingTwoSortedArraysProblemStatementInmergingtwosortedarraysproblemwehavegiventwosortedarrays,onearraywithsizem+nandtheotherarraywithsizen.Wewillmergethensizedarrayintom+nsizedarrayandprintthem+nsizedmergedarray.ExampleInput63M[]=...ReadmoreQuestion31.FindTripletinArrayWithaGivenSumProblemStatementGivenanarrayofintegers,findthecombinationofthreeelementsinthearraywhosesumisequaltoagivenvalueX.Herewewillprintthefirstcombinationthatweget.Ifthereisnosuchcombinationthenprint-1.ExampleInputN=5,X=15arr[]=...ReadmoreQuestion32.SmallestPositiveNumberMissinginanUnsortedArrayProblemStatementInthegivenunsortedarrayfindthesmallestpositivenumbermissinginanunsortedarray.Apositiveintegerdoesn’tinclude0.Wecanmodifytheoriginalarrayifneeded.Thearray maycontainpositiveandnegativenumbers.Examplea.Inputarray:[3,4,-1,0,-2,2,1,...ReadmoreQuestion33.MoveAlltheZerostotheEndoftheGivenArrayProblemStatementInthegivenarraymoveallthezeroswhicharepresentinthearraytotheendofthearray.Herethereisalwaysawayexisttoinsertallthenumberofzeroestotheendofthearray.ExampleInput99170140...ReadmoreQuestion34.CountNumberofOccurrencesinaSortedArrayProblemStatementInthe“CountNumberofOccurrencesinaSortedArray”problem,wehavegivenasortedarray.CountthenumberofoccurrencesorfrequencyinasortedarrayofXwhereXisaninteger.ExampleInput131222233344...ReadmoreQuestion35.AProductArrayPuzzleProblemStatementInaproductarraypuzzleproblemweneedtoconstructanarraywheretheithelementwillbetheproductofalltheelementsinthegivenarrayexceptelementattheithposition.ExampleInput 5103562Output180600360300900...ReadmoreQuestion36.MajorityElementProblemStatementGivenasortedarray,weneedtofindthemajorityelementfromthesortedarray.Majorityelement:Numberoccurringmorethanhalfthesizeofthearray.Herewehavegivenanumberxwehavetocheckitisthemajority_elementornot.ExampleInput52...ReadmoreByteDanceStringQuestionsQuestion37.ImplementTrie(PrefixTree)LeetcodeSolutionProblemStatementTheImplementTrie(PrefixTree)LeetCodeSolution–“ImplementTrie(PrefixTree)”asksyoutoimplementtheTrieDataStructure thatperformsinserting,searchingandprefixsearchingefficiently.Example:Input:["Trie", "insert", "search", "search", "startsWith", "insert", "search"][[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]Output:[null, null, true, false, true, null, true]Explanation:Afterinsertingallthestrings,trielookslikethis.Wordappleissearchedwhich...ReadmoreQuestion38.RemoveInvalidParenthesesLeetcodeSolutionProblemStatementTheRemoveInvalidParenthesesLeetcodeSolution–  statesthatyou’regivenastringsthatcontainsparenthesisandlowercaseletters.Weneedtoremovetheminimumnumberofinvalidparenthesestomaketheinputstringvalid.Weneedtoreturnallpossibleresultsinanyorder.Astringis...ReadmoreQuestion39.MultiplyStringsLeetcodeSolutionTheproblemMultiplyStringsLeetcodesolutionasksustomultiplytwostringswhicharegiventousasinput.Wearerequiredtoprintorreturnthisresultofmultiplyingtothecallerfunction.Sotoputitmoreformallygiventwostrings,findtheproductofthegivenstrings....ReadmoreQuestion40.LongestRepeatedSubsequenceTheproblem“LongestRepeatedSubsequence”statesthatyouaregivenastringasaninput.Findoutthelongestrepeatedsubsequence,thatisthesubsequencethatexiststwiceinthestring.Exampleaeafbdfdg3(afd)ApproachTheproblemasksustofindoutthelongestrepeatedsubsequenceinthestring....ReadmoreQuestion41.LongestSubstringWithoutRepeatingCharactersLeetCodeSolutionLongestSubstringWithoutRepeatingCharactersLeetCodeSolution–Givenastring,wehavetofindthelengthofthelongestsubstringwithoutrepeatingcharacters.Let’slookintoafewexamples:Examplepwwkew3Explanation:Answeris“wke”withlength3aav2Explanation:Answeris“av”withlength2Approach-1...ReadmoreQuestion42.PalindromeSubstringQueriesProblemStatementTheproblem“PalindromeSubstringQueries”statesthatyouaregivenaStringandsomequeries.Withthosequeries,youhavetodetermineiftheformedsubstringfromthatqueryisapalindromeornot.ExampleStringstr="aaabbabbaaa"Queriesq[]={{2,3},{2,8},{5,7},...ReadmoreQuestion43.MaximumweighttransformationofagivenstringProblemStatementThemaximumweighttransformationofagivenstringproblemstatesthatgivenastringconsistingonlyoftwocharacters‘A’and‘B’.Wehaveanoperationwherewecantransformstringtoanotherstringbytogglinganycharacter.Thusmanytransformationsarepossible.Outofallthepossible...ReadmoreQuestion44.EditDistanceIntheeditdistanceproblemwehavetofindtheminimumnumberofoperationsrequiredtoconvertastringXoflengthntoanotherstringYoflengthm.Operationsallowed:InsertionDeletionSubstitutionExampleInput:String1=“abcd”String2=“abe”Output:Minimumoperationsrequiredis2(...ReadmoreQuestion45.DecodeStringSuppose,youaregivenanencodedstring.Astringisencodedinsomekindofpattern,yourtaskistodecodethestring.Letussay,[string]ExampleInput3[b]2[bc]OutputbbbcacaExplanationHere“b”occurs3timesand“ca”occur2times....ReadmoreQuestion46.NextPermutationInthenextpermutationproblemwehavegivenaword,findthelexicographicallygreater_permutationofit.Exampleinput:str="tutorialcup"output:tutorialpcuinput:str="nmhdgfecba"output:nmheabcdfginput:str="algorithms"output:algorithsminput:str="spoonfeed"output:NextPermutation...ReadmoreQuestion47.ValidParenthesesLeetCodeSolutionInValidParenthesesLeetCodeproblemwehavegivenastringcontainingjustthecharacters‘(‘,‘)’,‘{‘,‘}’,‘[‘and‘]’,determineiftheinputstringisvalid.HerewewillprovideaValidParenthesesLeetCodeSolutiontoyou.Aninputstringisvalidif:Openbracketsmustbeclosed...ReadmoreQuestion48.PermutationsofaGivenStringUsingSTLProblemStatementInthe“PermutationsofaGivenStringUsingSTL”problem,wehavegivenastring“s”.PrintallthepermutationsoftheinputstringusingSTLfunctions.InputFormatThefirstandonlyonelinecontainingastring“s”.OutputFormatPrintallthepermutationofthegiven...ReadmoreQuestion49.LengthofLongestvalidSubstringProblemStatementInthe“LengthofLongestvalidSubstring”wehavegivenastringthatcontainstheopeningandclosingparenthesisonly.Writeaprogramthatwillfindthelongestvalidparenthesissubstring.InputFormatThefirstandonlyonelinecontainingastrings.OutputFormatThefirstand...ReadmoreQuestion50.SmallestwindowinastringcontainingallcharactersofanotherstringFindtheshortestsubstringinagivenstringthatcontainsallthecharactersofagivenwordorFindtheSmallestwindowinastringcontainingallcharactersofanotherstringGiventwostringssandt,writeafunctionthatwillfindtheminimumwindowinswhichwill...ReadmoreQuestion51.ArrangegivenNumberstoFormtheBiggestNumberIIProblemStatementInthe“ArrangegivenNumberstoFormtheBiggestNumberII”problem,wehavegivenanarrayofpositiveintegers. Arrangetheminsuchawaythatthearrangementwillformthelargestvalue.InputFormatThefirstandonlyonelinecontaininganintegern.Second-linecontaining...ReadmoreByteDanceTreeQuestionsQuestion52.MinimumnumberofdistinctelementsafterremovingmitemsProblemStatementTheproblem“Minimumnumberofdistinctelementsafterremovingmitems”statesthatyouhaveanarrayandanintegerm.Eachelementofthearrayindicatesanitemid’s.Theproblemstatementaskstoremovemelementsinsuchawaythatthereshouldbeaminimum...ReadmoreQuestion53.ConvertBSTtoMinHeapProblemStatementGivenacompleteBinarySearchTree,writeanalgorithmtoconvertitintoaMinHeap,whichistoconvertBSTtoMinHeap.TheMinHeapshouldbesuchthatthevaluesontheleftofanodemustbelessthanthevaluesontheright...ReadmoreQuestion54.ConvertanormalBSTtoBalancedBSTProblemStatementGivenaBinarySearchTree(BST),writeanalgorithmtoconverttheBSTtoaBalancedBinarySearchTree.AbalancedBinarySearchtreeisnothingbutabinarysearchtreewhosedifferencebetweentheheightofleftsubtreeandrightsubtreeislessthanorequalto1....ReadmoreQuestion55.ConstructBinaryTreefromGivenInorderandPreorderTraversalsInthisproblem,wehaveinorderandpreorderofthebinarytree.WeneedtoconstructabinarytreefromthegivenInorderandPreordertraversals.ExampleInput:Inorder=[D,B,E,A,F,C]Preorder=[A,B,D,E,C,F]Output:Pre-ordertraversalofthetreeformedby...ReadmoreQuestion56.RecoverBinarySearchTreeConsiderabinarysearchtree,twonodesofthetreehavebeenswapped,designanalgorithmtorecoverthebinarysearchTree.ExampleConsiderthebinarysearchtreegivenbelowwhosetwonodeshavebeenswappedasinput.IncorrectnodesontheBSTaredetected(highlighted)andthenswappedtoobtain...ReadmoreQuestion57.ValidateBinarySearchTreeProblemInValidateBinarySearchTreeproblemwehavegiventherootofatree,wehavetocheckifitisabinarysearchtreeornot.Example:Output:trueExplanation:Thegiventreeisabinarysearchtreebecauseallelementswhicharelefttoeachsubtree...ReadmoreByteDanceStackQuestionsQuestion58.DecodeStringSuppose,youaregivenanencodedstring.Astringisencodedinsomekindofpattern,yourtaskistodecodethestring.Letussay,[string]ExampleInput3[b]2[bc]OutputbbbcacaExplanationHere“b”occurs3timesand“ca”occur2times....ReadmoreByteDanceQueueQuestionsQuestion59.SumofminimumandmaximumelementsofallsubarraysofsizekProblemStatementTheproblem“Sumofminimumandmaximumelementsofallsubarraysofsizek”statesthatyouaregivenanarraycontainingpositiveandnegativeintegers,findthesumofminimumandmaximumelementsofallthesub-arraysofsizek.Examplesarr[]={5,9,8,3,...ReadmoreQuestion60.QueueReconstructionbyHeightProblemDescriptionofQueueReconstructionbyHeightSupposeyouhavearandomlistofpeoplestandinginaqueue.Eachpersonisdescribedbyapairofintegers(h,k),wherehistheheightofthepersonandkisthenumberofpeopleinfrontofthisperson...ReadmoreByteDanceMatrixQuestionsQuestion61.WordSearchLeetcodeSolutionProblemStatementGivenanmxnboardandaword,findifthewordexistsinthegrid.Thewordcanbeconstructedfromlettersofsequentiallyadjacentcells,where“adjacent”cellsarehorizontallyorverticallyneighbouring.Thesamelettercellmaynotbeusedmorethanonce.Example...ReadmoreByteDanceOtherQuestionsQuestion62.RestoreIPAddressesLeetcodeSolutionProblemStatementTheRestoreIPAddressesLeetCodeSolution–“RestoreIPAddresses”statesthatgiventhestringwhichcontainsonlydigits,weneedtoreturnallpossiblevalidIPAddressesinanyorderthatcanbeformedbyinsertingdotsintothestring.Notethatwe’renotallowedtoreturn...ReadmoreQuestion63.StringCompressionLeetCodeSolutionProblemStatementStringCompressionLeetCodeSolution–Givenanarrayofcharacters chars,compressitusingthefollowingalgorithm:Beginwithanemptystring s.Foreachgroupof consecutiverepeatingcharacters in chars:Ifthegroup’slengthis 1,appendthecharacterto s.Otherwise,appendthecharacterfollowedbythegroup’slength.Thecompressedstring...ReadmoreQuestion64.PossibleBipartitionLeetCodeSolutionProblemStatementPossibleBipartitionLeetCodeSolution–Wewanttosplitagroupofn people(labeledfrom 1 to n)intotwogroupsof anysize.Eachpersonmaydislikesomeotherpeople,andtheyshouldnotgointothesamegroup.Giventheinteger n andthearray dislikes where dislikes[i]=[ai,bi] indicatesthatthepersonlabeled ai does...ReadmoreQuestion65.MaximumProductofSplittedBinaryTreeLeetCodeSolutionProblemStatementMaximumProductofSplittedBinaryTreeLeetCodeSolution–Giventheroot ofabinarytree,splitthebinarytreeintotwosubtreesbyremovingoneedgesuchthattheproductofthesumsofthesubtreesismaximized.Return themaximumproductofthesumsofthetwosubtrees....ReadmoreQuestion66.MaximumProductofThreeNumbersLeetCodeSolutionProblemStatementMaximumProductofThreeNumbersLeetCodeSolution–Wearegivenanarray,thequestionasksustocalculatethemaximumproductofany3numbers.ExamplesExample1:Input:nums=[1,2,3]Output:6Example2:Input:nums=[1,2,3,4]Output:24Example3:Input:nums=...ReadmoreQuestion67.RandomPickIndexLeetCodeSolutionProblemStatementRandomPickIndexLeetCodeSolution-Wearegivenaconstructorofclass“Solution”andafunction“pick”oftypeint.Wearerequiredtoimplementthe“Solution”classasSolution(int[]nums) Initializestheobjectwiththearray nums.intpick(inttarget) Picksarandomindex i from nums where nums[i]==target.Iftherearemultiple...ReadmoreQuestion68.NextGreaterElementIIILeetCodeSolutionProblemStatementTheproblem,NextGreaterElementIIILeetCodeSolution statesthatyouaregivenapositiveintegernandyouneedtofindthenextgreatestintegerusingthedigitspresentinnonly.Iftheredoesnotexistanysuchinteger,youneedtoprint-1.Moreover,thenew...ReadmoreQuestion69.BinaryTreeLongestConsecutiveSequenceLeetCodeSolutionProblemStatementBinaryTreeLongestConsecutiveSequenceLeetCodeSolution–Giventheroot ofabinarytree,return thelengthofthelongestconsecutivesequencepath.Thepathreferstoanysequenceofnodesfromsomestartingnodetoanynodeinthetreealongwiththeparent-childconnections.Thelongestconsecutive...ReadmoreQuestion70.MoveZeroesLeetCodeSolutionProblemStatementTheproblem,MoveZeroesLeetCodeSolution statesthatyouaregivenanarraycontainingzeroandnon-zeroelementsandyouneedtomoveallthezeroestotheendofthearray,maintainingtherelativeorderofnon-zeroelementsinthearray.Youalsoneedtoimplementanin-place...ReadmoreQuestion71.01MatrixLeetCodeSolutionProblemStatementInthisproblem01MatrixLeetCodeSolution,weneedtofindthedistanceofthenearest0foreachcellofthegivenmatrix.Thematrixconsistsonlyof0’sand1’sandthedistanceofanytwoadjacentcellsis1.ExamplesExample1:Input:mat=...ReadmoreQuestion72.FactorialTrailingZeroesLeetCodeSolutionProblemStatementFactorialTrailingZeroesLeetCodeSolution–Givenanintegern,return thenumberoftrailingzeroesin n!.Notethat n!=n*(n-1)*(n-2)*...*3*2*1.Input:n=3Output:0Explanation:3!=6,notrailing...ReadmoreQuestion73.WordLadderLeetCodeSolutionProblemStatementTheWordLadderLeetCodeSolution–“WordLadder”statesthatyouaregivenastringbeginWord,stringendWord,andawordList.Weneedtofindtheshortesttransformationsequencelength(ifnopathexists,print0) frombeginWordtoendWordfollowingthegivenconditions:AlltheIntermediateWordsshould...ReadmoreQuestion74.LongestSubstringwithAtLeastKRepeatingCharactersLeetCodeSolutionProblemStatementTheproblemLongestSubstringwithAtLeastKRepeatingCharactersLeetCodeSolution saysgivenastringS andanintegerk,return thelengthofthelongestsubstringof S suchthatthefrequencyofeachcharacterinthissubstringisgreaterthanorequalto k.ExampleforLongestSubstringwithAtLeast...ReadmoreQuestion75.LastStoneWeightIILeetCodeSolutionProblemStatementTheproblemLastStoneWeightII saysyouaregivenanarrayofintegersstoneswherestones[i] istheweightofthe ith stone.Weareplayingagamewiththestones.Oneachturn,wechooseanytwostonesandsmashthemtogether.Supposethestoneshaveweightsx andy...ReadmoreQuestion76.LargestBSTSubtreeLeetCodeSolutionProblemStatementTheLargestBSTSubtreeLeetCodeSolutionproblemsaysgiventherootofabinarytree,findthelargestsubtree,whichisalsoaBinarySearchTree(BST),wherethelargestmeanssubtreehavingthelargestnumberofnodes.Note: Asubtreemustincludeallofitsdescendants.Ina Binary...ReadmoreQuestion77.MeetingRoomsIILeetCodeSolutionProblemStatementTheMeetingRoomsIILeetCodeSolution–“MeetingRoomsII”statesthatyouaregivenanarrayofmeetingtimeintervals“intervals”where“intervals[i]=[start[i],end[i]]”,returntheminimumnumberofconferenceroomsrequired.Example:intervals=[[0,30],[5,10],[15,20]]2Explanation:Meetingonecanbedone...ReadmoreQuestion78.SubarraySumEqualsKLeetCodeSolutionProblemStatementTheSubarraySumEqualsKLeetCodeSolution–“SubarraySumEqualsK”statesthatyouaregivenanarrayofintegers“nums”andaninteger‘k’,returnthetotalnumberofcontinuoussubarrayswhosesumequalsto‘k’.Example:nums=[1,2,3],k=32Explanation:There...ReadmoreQuestion79.LongestPalindromicSubstringLeetCodeSolutionProblemStatementTheLongestPalindromicSubstringLeetCodeSolution–“LongestPalindromicSubstring”statesthatYouareGivenastrings,returnthelongestpalindromicsubstringins.Note:Apalindromeisawordthatreadsthesamebackwardasforwards,e.g.madam.Example: s="babad""bab"Explanation:All...ReadmoreQuestion80.BestTimetoBuyandSellStockLeetCodeSolutionProblemStatementTheBestTimetoBuyandSellStockLeetCodeSolution–“BestTimetoBuyandSellStock”statesthatYouaregivenanarrayofpriceswhereprices[i]isthepriceofagivenstockonanithday.Youwanttomaximizeyourprofitbychoosing...ReadmoreQuestion81.LRUCacheLeetCodeSolutionQuestionDesignadatastructurethatfollowstheconstraintsofaLeastRecentlyUsed(LRU)cache.Implementthe LRUCache class:LRUCache(intcapacity) InitializetheLRUcachewith positive size capacity.intget(intkey) Returnthevalueofthe key ifthekeyexists,otherwisereturn -1.voidput(intkey,intvalue) Updatethevalueofthe key ifthe key exists.Otherwise,addthe key-value pairto...ReadmoreQuestion82.PermutationsLeetcodeSolutionTheproblemPermutationsLeetcodeSolutionprovidesasimplesequenceofintegersandasksustoreturnacompletevectororarrayofallthepermutationsofthegivensequence.So,beforegoingintosolvingtheproblem.Weshouldbefamiliarwithpermutations.So,apermutationisnothingbutanarrangement...ReadmoreQuestion83.TwoSumLeetcodeSolutionInthisproblem,wehavetofindapairoftwodistinctindicesinasortedarraythattheirvaluesadduptoagiventarget.Wecanassumethatthearrayhasonlyonepairofintegersthatadduptothetargetsum.Notethatthearrayis...ReadmoreQuestion84.LexicographicalNumbersLeetcodeSolutionProblemstatementIntheproblem”LexicographicalNumbers”wearegivenanumbern.Ourtaskistoprintnumbersbetween1andninlexicographicalorder.Examplen=13[11011121323456789]Explanation:Aswehavetoprintnumbersbetween...ReadmoreQuestion85.Maximumnumberofsegmentsoflengthsa,bandcTheproblem“Maximumnumberofsegmentsoflengthsa,bandc”statesthatyouaregivenapositiveintegerN,andyouneedtofindthemaximumnumberofsegmentsoflengthsa,b,andcthatcanbeformedusingN.ExampleN=7a=5,b...ReadmoreQuestion86.ASpaceOptimizedDPsolutionfor0-1KnapsackProblemProblemStatementWearegivenaknapsackwhichcanholdsomeweight,weneedtopicksomeoftheitemsoutofgivenitemswithsomevalue.Theitemsshouldbepickedsuchthatthevalueoftheknapsack(totalvalueofpickedupitems)shouldbemaximized....ReadmoreQuestion87.K-thDistinctElementinanArrayYouaregivenanintegerarrayA,printk-thdistinctelementinanarray.Thegivenarraymaycontainduplicatesandtheoutputshouldprintk-thdistinctelementamongalluniqueelementsinanarray.Ifkismorethananumberofdistinctelements,thenreportit.ExampleInput:...ReadmoreQuestion88.IntersectionofTwoArraysInintersectionoftwoarraysproblem,wehavegiventwoarrays,weneedtoprinttheirintersection(commonelements).ExampleInputarr1[]={1,2,2,1}arr2[]={2,2}Output{2,2}Inputarr1={4,9,5}arr2={9,4,9,8,4}Output{4,9}Algorithm...ReadmoreQuestion89.LeetcodePermutationsInthisleetcodeproblempremutationwehavegivenanarrayofdistinctintegers,printallofitspossiblepermutations.ExamplesInputarr[]={1,2,3}Output123132213231312321Inputarr[]={1,2,...ReadmoreQuestion90.MergeKSortedLinkedListsMergeKsortedlinkedlistsproblemissofamousaspertheinterviewpointofview.ThisquestionaskssomanytimesinbigcompanieslikeGoogle,Microsoft,Amazon,etc. Asthenamesuggestswe’vebeenprovidedwithksortedlinkedlists.Wehavetomergethemtogetherintoa...ReadmoreQuestion91.FindMedianfromdataStreamInFindMedianfromthedataStreamproblem,wehavegiventhatintegersarebeingreadfromadatastream.Findthemedianofalltheelementsreadsofarstartingfromthefirstintegertillthelastinteger.ExampleInput1:stream[]={3,10,5,20,7,6}Output:36.5...ReadmoreQuestion92.SlidingWindowMaximumInSlidingWindowMaximumproblemwehavegivenanarraynums,foreachcontiguouswindowofsizek,findthemaximumelementinthewindow.ExampleInputnums[]={1,3,-1,-3,5,3,6,7}k=3Output{3,3,5,5,6,7}ExplanationNaiveApproachforSlidingWindowMaximumForeverycontiguouswindowofsizek,traverse...ReadmoreQuestion93.WordBreakWordBreakisaproblemthatbeautifullyillustratesawholenewconcept.Wehaveallheardofcompoundwords.Wordsmadeupofmorethantwowords.Todaywehavealistofwordsandallwe’vegottodoischeckifallthewordsfromthedictionarycan...ReadmoreQuestion94.ReverseNodesinK-GroupProblemInReverseNodesinK-Groupproblemwehavegivenalinkedlist,Reversethelinkedlistinagroupofkandreturnthemodifiedlist.Ifthenodesarenotmultipleofkthenreversetheremainingnodes.Thevalueofkisalwayssmallerorequalto...ReadmoreQuestion95.LRUCacheImplementationLeastRecentlyUsed(LRU)Cacheisatypeofmethodwhichisusedtomaintainthedatasuchthatthetimerequiredtousethedataistheminimumpossible.LRUalgorithmusedwhenthecacheisfull.Weremovetheleastrecentlyuseddatafromthecachememoryof...ReadmoreQuestion96.NqueenproblemNqueenproblemusingtheconceptofBacktracking.Hereweplacequeensuchthatnoqueenunderattackcondition.Theattackconditionofthequeensisiftwoqueensareonthesamecolumn,row,anddiagonalthentheyareunderattack.Let’sseethisbythebelowfigure.Here...ReadmoreRecentPostsClosestLeafinaBinaryTreeLeetCodeSolutionUglyNumberIILeetCodeSolutionInvalidTransactionsLeetCodeSolutionFindaPeakElementIILeetCodeSolutionCombinationSumIVLeetCodeSolutionAlgorithmInterviewQuestionsArrayInterviewQuestionsCProgrammingTutorialC++TutorialDBMSTutorialDigitalElectronicsTutorialDynamicProgrammingInterviewQuestionsGitTutorialGraphInterviewQuestionsHashingInterviewQuestionsInterviewQuestionsJavaTutorialJavaScriptTutorialLeetCodeSolutionsLinkedListInterviewQuestionsMatrixInterviewQuestionsPHPTutorialPythonBasicsQueueInterviewQuestionsRProgrammingTutorialSeleniumTutorialSortingInterviewQuestionsSpringBootTutorialSQLInterviewQuestionsSQLTutorialStackInterviewQuestionsStringInterviewQuestionsTechnicalInterviewQuestionsTestingTutorialTreeInterviewQuestionsTypesofTestingWordPressSearchreportthisadreportthisadreportthisadScrollbacktotop Translate»xx



請為這篇文章評分?