Hacking a Google Interview Handout 2



Similar documents
Sorting Algorithms. Nelson Padua-Perez Bill Pugh. Department of Computer Science University of Maryland, College Park

6. Standard Algorithms

Hacking a Google Interview Handout 3

>

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

Biostatistics 615/815

Algorithm Analysis [2]: if-else statements, recursive algorithms. COSC 2011, Winter 2004, Section N Instructor: N. Vlajic

Introduction to Data Structures

Binary Heap Algorithms

Introduction to Programming (in C++) Sorting. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Introduction to Stacks

The following program is aiming to extract from a simple text file an analysis of the content such as:

Big O and Limits Abstract Data Types Data Structure Grand Tour.

What Is Recursion? Recursion. Binary search example postponed to end of lecture

Analysis of Binary Search algorithm and Selection Sort algorithm

CSC148 Lecture 8. Algorithm Analysis Binary Search Sorting

J a v a Quiz (Unit 3, Test 0 Practice)

What Is Recursion? 5/12/10 1. CMPSC 24: Lecture 13 Recursion. Lecture Plan. Divyakant Agrawal Department of Computer Science UC Santa Barbara

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Converting a Number from Decimal to Binary

Data Structures. Jaehyun Park. CS 97SI Stanford University. June 29, 2015

7. Solving Linear Inequalities and Compound Inequalities

Data Structures and Algorithms

Simple sorting algorithms and their complexity. Bubble sort. Complexity of bubble sort. Complexity of bubble sort. Bubble sort of lists

DATA STRUCTURE - QUEUE

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Arrays in Java. Working with Arrays

Computer Science 210: Data Structures. Searching

4.2 Sorting and Searching

13 Classes & Objects with Constructors/Destructors

Algorithms. Margaret M. Fleck. 18 October 2010

Binary search algorithm

Data Structures and Algorithms Lists

Overview. What is software testing? What is unit testing? Why/when to test? What makes a good test? What to test?

Data Structures in the Java API

Analysis of a Search Algorithm

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., Barnette ND, McQuain WD

Introducing Variance into the Java Programming Language DRAFT

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Data Structures and Algorithms

Basic Programming and PC Skills: Basic Programming and PC Skills:

Two-Dimensional Arrays Summer 2010 Margaret Reid-Miller

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

2.3 WINDOW-TO-VIEWPORT COORDINATE TRANSFORMATION

Keys and records. Binary Search Trees. Data structures for storing data. Example. Motivation. Binary Search Trees

Practical Session 4 Java Collections

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

DATA STRUCTURE - STACK

Ordered Lists and Binary Trees

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

GPGPU Parallel Merge Sort Algorithm

Sample CSE8A midterm Multiple Choice (circle one)

Lecture Notes on Linear Search

To My Parents -Laxmi and Modaiah. To My Family Members. To My Friends. To IIT Bombay. To All Hard Workers

Class 32: The Java Collections Framework

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

Lecture Notes on Binary Search Trees

Algorithms and Data Structures Exercise for the Final Exam (17 June 2014) Stack, Queue, Lists, Trees, Heap

Shortest Path Algorithms

Conditionals (with solutions)

Dynamic Programming. Lecture Overview Introduction

Java Server Pages and Java Beans

Introduction to Java

Object-Oriented Programming

Database Management Systems Comparative Study: Performances of Microsoft SQL Server Versus Oracle

Priority Queues and Heapsort

Searching Algorithms

Dalhousie University CSCI 2132 Software Development Winter 2015 Lab 7, March 11

Data Structures and Algorithms Written Examination

! stack, queue, priority queue, dictionary, sequence, set e.g., a Stack is a list implements a LIFO policy on additions/deletions.

CSI 402 Lecture 13 (Unix Process Related System Calls) 13 1 / 17

From Pseudocode to Real Code

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Visualising Java Data Structures as Graphs

recursion here it is in C++ power function cis15 advanced programming techniques, using c++ fall 2007 lecture # VI.1

TECHNICAL UNIVERSITY OF CRETE DATA STRUCTURES FILE STRUCTURES

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

THIS CHAPTER studies several important methods for sorting lists, both contiguous

Winter 2002 MID-SESSION TEST Friday, March 1 6:30 to 8:00pm

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Abstraction and Abstract Data Types

Collections.sort(population); // Método de ordenamiento

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

QUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q

STORM. Simulation TOol for Real-time Multiprocessor scheduling. Designer Guide V3.3.1 September 2009

Transcription:

HackingaGoogleInterview Handout2 CourseDescription Instructors:BillJacobsandCurtisFonger Time:January12 15,5:00 6:30PMin32 124 Website:http://courses.csail.mit.edu/iap/interview ClassicQuestion#4:Reversingthewordsinastring Writeafunctiontoreversetheorderofwordsinastringinplace. Answer:Reversethestringbyswappingthefirstcharacterwiththelastcharacter, thesecondcharacterwiththesecond to lastcharacter,andsoon.then,gothrough thestringlookingforspaces,sothatyoufindwhereeachofthewordsis.reverse eachofthewordsyouencounterbyagainswappingthefirstcharacterwiththelast character,thesecondcharacterwiththesecond to lastcharacter,andsoon. Sorting Often,aspartofasolutiontoaquestion,youwillneedtosortacollectionof elements.themostimportantthingtorememberaboutsortingisthatittakeso(n logn)time.(thatis,thefastestsortingalgorithmforarbitrarydatatakeso(nlogn) time.) MergeSort: Mergesortisarecursivewaytosortanarray.First,youdividethearrayinhalfand recursivelysorteachhalfofthearray.then,youcombinethetwohalvesintoa sortedarray.soamergesortfunctionwouldlooksomethinglikethis: int[] mergesort(int[] array) { if (array.length <= 1) return array; int middle = array.length / 2; int firsthalf = mergesort(array[0..middle - 1]); int secondhalf = mergesort( array[middle..array.length - 1]); return merge(firsthalf, secondhalf); Thealgorithmreliesonthefactthatonecanquicklycombinetwosortedarraysinto asinglesortedarray.onecandosobykeepingtwopointersintothetwosorted

arrays.onerepeatedlyaddsthesmallerofthetwonumberspointedtotothenew arrayandadvancesthepointer. Quicksort: Quicksortisanothersortingalgorithm.IttakesO(n^2)timeintheworstcaseand O(nlogn)expectedtime. Tosortanarrayusingquicksort,onefirstselectsarandomelementofthearrayto bethe"pivot".onethendividesthearrayintotwogroups:agroupofelementsthat arelessthanthepivotandagroupofelementsthataregreaterthanthepivot.after this,therewillbeanarrayconsistingofelementslessthanthepivot,followedbythe pivot,followedbyelementsgreaterthanthepivot.then,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)worstcaserunningtime,sobesuretomentionanothersortingalgorithm,suchasmerge sort,ifyouneedguaranteedo(nlogn)runningtime. OrderStatistics: Sometimes,aninterviewerwillaskyoutodescribeanalgorithmtoidentifythekth smallestelementinanarrayofnelements.todothis,youselectarandompivot andpartitionthearrayasyouwouldinthequicksortalgorithm.then,basedonthe indexofthepivotelement,youknowwhichhalfofthearraythedesiredelementlies in.forexample,sayk=15andn=30,andafteryouselectyourpivotandpartition thearray,thefirsthalfhas10elements(thehalfbeforethepivot).youknowthat thedesiredelementisthe4thsmallestelementinthelargerhalf.toidentifythe element,youpartitionthesecondhalfofthearrayandcontinuerecursively.the reasonthatthisisnoto(nlogn)isthattherecursivepartitioncallisonlyonone halfofthearray,sotheexpectedrunningtimeisn+(n/2)+(n/4)+(n/8)+...= O(n).

Notethatfindingthemedianofanarrayisaspecialcaseofthiswherek=n/2. Thisisaveryimportantpoint,asaninterviewerwilloftenaskyoutofindawayto getthemedianofanarrayofnumbers. Question:NearestNeighbor Sayyouhaveanarraycontaininginformationregardingnpeople.Eachpersonis describedusingastring(theirname)andanumber(theirpositionalonganumber line).eachpersonhasthreefriends,whicharethethreepeoplewhosenumberis nearesttheirown.describeanalgorithmtoidentifyeachperson'sthreefriends. Goodanswer:Sortthearrayinascendingorderofthepeople'snumber.Foreach person,checkthethreepeopleimmediatelybeforeandafterthem.theirthree friendswillbeamongthesesixpeople.thisalgorithmtakeso(nlogn)time,since sortingthepeopletakesthatmuchtime. LinkedLists Alinkedlistisabasicdatastructure.Eachnodeinalinkedlistcontainsanelement andapointertothenextnodeinthelinkedlist.thelastnodehasa"null"pointerto indicatethatthereisnonextnode.alistmayalsobedoublylinked,inwhichcase eachnodealsohasapointertothepreviousnode.ittakesconstant(o(1))timeto addanodetoorremoveanodefromalinkedlist(ifyoualreadyhaveapointerto thatnode).ittakeso(n)timetolookupanelementinalinkedlistifyoudon't alreadyhaveapointertothatnode. ClassicQuestion#5:CycleinaLinkedList Howcanonedeterminewhetherasinglylinkedlisthasacycle? Goodanswer:Keeptrackoftwopointersinthelinkedlist,andstartthematthe beginningofthelinkedlist.ateachiterationofthealgorithm,advancethefirst pointerbyonenodeandthesecondpointerbytwonodes.ifthetwopointersare everthesame(otherthanatthebeginningofthealgorithm),thenthereisacycle.if apointereverreachestheendofthelinkedlistbeforethepointersarethesame, thenthereisnocycle.actually,thepointersneednotmoveoneandtwonodesata time;itisonlynecessarythatthepointersmoveatdifferentrates.thistakeso(n) time.thisisatrickyanswerthatinterviewersreallylikeforsomereason. Okayanswer:Foreverynodeyouencounterwhilegoingthroughthelistonebyone, putapointertothatnodeintoao(1) lookuptimedatastructure,suchasahashset. Then,whenyouencounteranewnode,seeifapointertothatnodealreadyexistsin yourhashset.thisshouldtakeo(n)time,butalsotakeso(n)space.

Okayanswer:Gothroughtheelementsofthelist."Mark"eachnodethatyoureach. Ifyoureachamarkednodebeforereachingtheend,thelisthasacycle;otherwise,it doesnot.thisalsotakeso(n)time. Notethatthisquestionistechnicallyill posed.anordinarylinkedlistwillhaveno cycles.whattheyactuallymeanisforyoutodeterminewhetheryoucanreacha cyclefromanodeinagraphconsistingofnodesthathaveatmostoneoutgoing edge. StacksandQueues Aninterviewerwillprobablyexpectyoutoknowwhatqueuesandstacksare. Queuesareabstractdatatypes.Aqueueisjustlikealineofpeopleatanamusement park.aqueuetypicallyhastwooperations:enqueueanddequeue.enqueueingan elementaddsittothequeue.dequeueinganelementremovesandreturnsthe elementthatwasaddedleastrecently.aqueueissaidtobefifo(first in,first out). Astackisanotherabstractdatatypewithtwocommonoperations:pushandpop. Pushinganelementaddsittothestack.Poppinganelementremovesandreturns theelementthatwasaddedmostrecently.astackissaidtobelifo(last in,firstout).astackoperateslikeastackofcafeteriatrays. HashTables Ahashtableisusedtoassociatekeyswithvalues,sothateachkeyisassociatedwith oneorzerovalues.eachkeyshouldbeabletocomputea"hash"function,which takessomeorallofitsinformationanddigestsitintoasingleinteger.thehash tableconsistsofanarrayofhashbuckets.toaddakey valuepairtoahashtable, onecomputesthekey'shashcodeandusesittodecidethehashbucketinwhichthe mappingbelongs.forexample,ifthehashvalueis53andthereare8hashbuckets, onemightusethemodfunctiontodecidetoputthemappinginbucket53mod8, whichisbucket5.tolookupthevalueforagivenkey,onecomputesthebucketin whichthekeywouldresideandcheckswhetherthekeyisthere;ifso,onecan returnthevaluestoredinthatbucket.toremovethemappingforagivenkey,one likewiselocatesthekey'smappingandremovesitfromtheappropriatebucket. Notethatthehashfunctionisgenerallydecidedoninadvance. Aproblemariseswhentwokeyshashtothesamebucket.Thiseventiscalleda "collision".thereareseveralwaystodealwiththis.onewayistostorealinkedlist ofkey valuepairsforeachbucket. Insertion,removal,andlookuptakeexpectedO(1)time,providedthatthehash functionissufficiently"random".intheworst case,eachkeyhashestothesame bucket,soeachoperationtakeso(n)time.inpractice,itiscommontoassume constanttime.

Hashtablescanoftenbeusedassmallercomponentsofanswerstoquestions.In ourexperience,someinterviewerslikehashtablesandsomedon't.thatis,some interviewerswillallowyoutoassumeconstanttime,whileotherswillnot.ifyou wanttouseahashtable,werecommendsubtlytryingtofigureoutwhichcategory yourinterviewerbelongsto.youmight,forexample,saysomethinglike,"well,i couldusedahashtable,butthatwouldhavebadworst caseperformance."the interviewermightthenindicatethathe'llallowyoutouseahashtable. ClassicQuestion#6:Datastructureforanagrams GivenanEnglishwordintheformofastring,howcanyouquicklyfindallvalid anagramsforthatstring(allvalidrearrangementsofthelettersthatformvalid Englishwords)?Youareallowedtopre computewhateveryouwanttoandstore whateveryouoptionallypre computeondisk. Answer:Wewanttouseahashtable!Ifyourinterviewerreallyhateshashtables (whichtheysometimesdoforsomereason),youcanuseatreeinstead.butlet's assumeyoucanuseahashtable.thenforthepre computingstep,gothrougheach wordinthedictionary,sortthelettersofthewordinalphabeticalorder(so "hacking"wouldbecome"acghikn")andaddthesortedlettersasakeyinthetable andtheoriginalwordasoneofthevaluesinalistofvaluesforthatkey.for example,theentryfor"opst"wouldbethelist["opts","post","stop","pots","tops", "spot"].then,wheneveryougetastring,yousimplysortthelettersofthestring andlookupthevalueinthehashtable.therunningtimeiso(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")appearswhenyoufactorthenumber.therefore thinkabouttheprimefactorizationof100!andhowmany2sand5sthereare. Thereareabunchmore2sthan5s,sothenumberof5sisalsothenumberof10sin thefactorization.thereisone5foreveryfactorof5inourfactorialmultiplication (1*2*...*5*...*10*...*15*...)andanextra5for25,50,75,and100.Thereforewehave 20+4=24zerosattheendof100!.