0% found this document useful (0 votes)
323 views5 pages

Hacking A Google Interview Handout 2

The document describes a course on hacking Google interviews. It provides examples of common interview questions and optimal algorithms to solve them. Specifically, it discusses reversing words in a string, sorting algorithms like merge sort and quicksort, finding the kth smallest element, and detecting cycles in a linked list. The optimal solutions generally take O(n log n) time.

Uploaded by

Himanshu Agarwal
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
323 views5 pages

Hacking A Google Interview Handout 2

The document describes a course on hacking Google interviews. It provides examples of common interview questions and optimal algorithms to solve them. Specifically, it discusses reversing words in a string, sorting algorithms like merge sort and quicksort, finding the kth smallest element, and detecting cycles in a linked list. The optimal solutions generally take O(n log n) time.

Uploaded by

Himanshu Agarwal
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

HackingaGoogleInterviewHandout2

CourseDescription Instructors:BillJacobsandCurtisFonger Time:January1215,[Link]PMin32124 Website:[Link] ClassicQuestion#4:Reversingthewordsinastring Writeafunctiontoreversetheorderofwordsinastringinplace. Answer:Reversethestringbyswappingthefirstcharacterwiththelastcharacter, thesecondcharacterwiththesecondtolastcharacter,[Link],gothrough thestringlookingforspaces,[Link] eachofthewordsyouencounterbyagainswappingthefirstcharacterwiththelast character,thesecondcharacterwiththesecondtolastcharacter,andsoon. Sorting Often,aspartofasolutiontoaquestion,youwillneedtosortacollectionof [Link](n logn)time.(Thatis,thefastestsortingalgorithmforarbitrarydatatakesO(nlogn) time.) MergeSort: [Link],youdividethearrayinhalfand [Link],youcombinethetwohalvesintoa [Link]: int[] mergeSort(int[] array) { if ([Link] <= 1) return array; int middle = [Link] / 2; int firstHalf = mergeSort(array[0..middle - 1]); int secondHalf = mergeSort( array[middle..[Link] - 1]); return merge(firstHalf, secondHalf); } Thealgorithmreliesonthefactthatonecanquicklycombinetwosortedarraysinto [Link]

[Link] arrayandadvancesthepointer. Quicksort: [Link](n^2)timeintheworstcaseand O(nlogn)expectedtime. Tosortanarrayusingquicksort,onefirstselectsarandomelementofthearrayto bethe"pivot".Onethendividesthearrayintotwogroups:agroupofelementsthat [Link] this,therewillbeanarrayconsistingofelementslessthanthepivot,followedbythe pivot,[Link],onerecursivelysortsthe portionofthearraybeforethepivotandtheportionofthearrayafterthepivot.A quicksortfunctionwouldlooklikethis: void quicksort(int[] array, int startIndex, int endIndex) { if (startIndex >= endIndex) { // Base case (array segment has 1 or 0 elements } else { int pivotIndex = partition(array, startIndex, endIndex); quicksort(array, startIndex, pivotIndex - 1); quicksort(array, pivotIndex + 1, endIndex); } } Quicksortistypicallyveryfastinpractice,butrememberthatithasO(n^2)worst caserunningtime,sobesuretomentionanothersortingalgorithm,suchasmerge sort,ifyouneedguaranteedO(nlogn)runningtime. OrderStatistics: Sometimes,aninterviewerwillaskyoutodescribeanalgorithmtoidentifythekth [Link],youselectarandompivot [Link],basedonthe indexofthepivotelement,youknowwhichhalfofthearraythedesiredelementlies [Link],sayk=15andn=30,andafteryouselectyourpivotandpartition thearray,thefirsthalfhas10elements(thehalfbeforethepivot).Youknowthat [Link] element,[Link] reasonthatthisisnotO(nlogn)isthattherecursivepartitioncallisonlyonone halfofthearray,sotheexpectedrunningtimeisn+(n/2)+(n/4)+(n/8)+...= O(n).

Notethatfindingthemedianofanarrayisaspecialcaseofthiswherek=n/2. Thisisaveryimportantpoint,asaninterviewerwilloftenaskyoutofindawayto getthemedianofanarrayofnumbers. Question:NearestNeighbor [Link] describedusingastring(theirname)andanumber(theirpositionalonganumber line).Eachpersonhasthreefriends,whicharethethreepeoplewhosenumberis [Link]'sthreefriends. Goodanswer:Sortthearrayinascendingorderofthepeople'[Link] person,[Link] [Link](nlogn)time,since sortingthepeopletakesthatmuchtime. LinkedLists [Link] [Link]"null"pointerto [Link],inwhichcase [Link](O(1))timeto addanodetoorremoveanodefromalinkedlist(ifyoualreadyhaveapointerto thatnode).IttakesO(n)timetolookupanelementinalinkedlistifyoudon't alreadyhaveapointertothatnode. ClassicQuestion#5:CycleinaLinkedList Howcanonedeterminewhetherasinglylinkedlisthasacycle? Goodanswer:Keeptrackoftwopointersinthelinkedlist,andstartthematthe [Link],advancethefirst [Link] everthesame(otherthanatthebeginningofthealgorithm),[Link] apointereverreachestheendofthelinkedlistbeforethepointersarethesame, [Link],thepointersneednotmoveoneandtwonodesata time;[Link](n) [Link]. Okayanswer:Foreverynodeyouencounterwhilegoingthroughthelistonebyone, putapointertothatnodeintoaO(1)lookuptimedatastructure,suchasahashset. Then,whenyouencounteranewnode,seeifapointertothatnodealreadyexistsin [Link](n)time,butalsotakesO(n)space.

Okayanswer:Gothroughtheelementsofthelist."Mark"eachnodethatyoureach. Ifyoureachamarkednodebeforereachingtheend,thelisthasacycle;otherwise,it [Link](n)time. [Link] [Link] cyclefromanodeinagraphconsistingofnodesthathaveatmostoneoutgoing edge. StacksandQueues Aninterviewerwillprobablyexpectyoutoknowwhatqueuesandstacksare. [Link] [Link]:[Link] [Link] [Link](firstin,firstout). Astackisanotherabstractdatatypewithtwocommonoperations:pushandpop. [Link] [Link](lastin,first out).Astackoperateslikeastackofcafeteriatrays. HashTables Ahashtableisusedtoassociatekeyswithvalues,sothateachkeyisassociatedwith [Link]"hash"function,which [Link] [Link], onecomputesthekey'shashcodeandusesittodecidethehashbucketinwhichthe [Link],ifthehashvalueis53andthereare8hashbuckets, onemightusethemodfunctiontodecidetoputthemappinginbucket53mod8, [Link],onecomputesthebucketin whichthekeywouldresideandcheckswhetherthekeyisthere;ifso,onecan [Link],one likewiselocatesthekey'smappingandremovesitfromtheappropriatebucket. Notethatthehashfunctionisgenerallydecidedoninadvance. [Link] "collision".[Link] ofkeyvaluepairsforeachbucket. Insertion,removal,andlookuptakeexpectedO(1)time,providedthatthehash functionissufficiently"random".Intheworstcase,eachkeyhashestothesame bucket,soeachoperationtakesO(n)[Link],itiscommontoassume constanttime.

[Link] ourexperience,someinterviewerslikehashtablesandsomedon'[Link],some interviewerswillallowyoutoassumeconstanttime,[Link] wanttouseahashtable,werecommendsubtlytryingtofigureoutwhichcategory [Link],forexample,saysomethinglike,"Well,I couldusedahashtable,butthatwouldhavebadworstcaseperformance."The interviewermightthenindicatethathe'llallowyoutouseahashtable. ClassicQuestion#6:Datastructureforanagrams GivenanEnglishwordintheformofastring,howcanyouquicklyfindallvalid anagramsforthatstring(allvalidrearrangementsofthelettersthatformvalid Englishwords)?Youareallowedtoprecomputewhateveryouwanttoandstore whateveryouoptionallyprecomputeondisk. Answer:Wewanttouseahashtable!Ifyourinterviewerreallyhateshashtables (whichtheysometimesdoforsomereason),[Link]'s [Link],gothrougheach wordinthedictionary,sortthelettersofthewordinalphabeticalorder(so "hacking"wouldbecome"acghikn")andaddthesortedlettersasakeyinthetable [Link] example,theentryfor"opst"wouldbethelist["opts","post","stop","pots","tops", "spot"].Then,wheneveryougetastring,yousimplysortthelettersofthestring [Link](nlogn)forsorting thestring(whichisrelativelysmall)andapproximatelyO(1)forthelookupinthe hashtable. Thereareseveralotherpossibleanswerstothisquestion,butwefeelthatthe answeraboveisconsideredanoptimalsolution. Question:FactorialZeros Withoutusingacalculator,howmanyzerosareattheendof"100!"?(that's 100*99*98*...*3*2*1) Answer:Whatyoudon'twanttodoisstartmultiplyingitallout!Thetrickis rememberingthatthenumberofzerosattheendofanumberisequaltothe numberoftimes"10"(or"2*5")[Link] thinkabouttheprimefactorizationof100!andhowmany2sand5sthereare. Thereareabunchmore2sthan5s,sothenumberof5sisalsothenumberof10sin thefactorization.Thereisone5foreveryfactorof5inourfactorialmultiplication (1*2*...*5*...*10*...*15*...)andanextra5for25,50,75,[Link] 20+4=24zerosattheendof100!.

You might also like