Hacking a Google Interview Handout 3



Similar documents
Algorithms and Data Structures Written Exam Proposed SOLUTION

Chapter 14 The Binary Search Tree

Client-server Sockets

Here is a quick diagram of the ULV SSO/Sync Application. Number 3 is what we deal with in this document.

MiTel VoIP Phone System

Singletons. The Singleton Design Pattern using Rhapsody in,c

Analysis of Algorithms I: Binary Search Trees

Using Adversary Structures to Analyze Network Models,

Where were they Allied and Central Powers located?

Data Structures and Data Manipulation

Apache Tomcat Clustering

CS330 Design Patterns - Midterm 1 - Fall 2015

Immersion Day. Creating an Elastic Load Balancer. Rev

Developing SQL and PL/SQL with JDeveloper

Overview. Semantics of EPCs. EPC Tools. Problem: Vicious Circle. Non-local Semantics of EPCs

UI Performance Monitoring

LAB #11: RESONANCE IN AIR COLUMNS

For Internet Facing and Private Data Systems

Chapter 2 Probability Topics SPSS T tests

Data Structures CSC212 (1) Dr Muhammad Hussain Lecture - Binary Search Tree ADT

Alex. Adam Agnes Allen Arthur

TESTING WITH JUNIT. Lab 3 : Testing

Load Balancer Configuration for Redundancy for SIP Federation

Power Management in Cloud Computing using Green Algorithm. -Kushal Mehta COP 6087 University of Central Florida

Hacking a Google Interview Handout 2

INTRODUCTION. Technology is changing everything. Today: Impact on PT Prac1ce Tomorrow: Electronic Health Record and Smart Mobile Devices

Ensuring Data Availability for the Enterprise with Storage Replica

EFFECTIVE NOTE- TAKING METHODS. Student Success Workshop Series Sauk Valley Community College

Small Business Administration

How To Analyze Logs On Aloha On A Pcode On A Linux Server On A Microsoft Powerbook (For Acedo) On A Macbook Or Ipad (For An Ubuntu) On An Ubode (For Macrocess

Magrathea Non-Geographic Numbering Plan

Software Metrics in Static Program Analysis

SIIT-DC: IPv4 Service Continuity for IPv6 Data Centres. Tore Anderson Redpill Linpro AS 8th Belgian IPv6 Council, Bruxelles, November 2015

CIMHT_006 How to Configure the Database Logger Proficy HMI/SCADA CIMPLICITY

Endowing a virtual assistant with intelligence: a multi-paradigm approach

Developer Guide. Android Printing Framework. ISB Vietnam Co., Ltd. (IVC) Page i

YELLOW statements you agreed with (number of checks you made)

Implementing DHCPv6 on an IPv6 network

MULTIPLE REGRESSION EXAMPLE

Introduction to Object-Oriented Programming

RTCU Gateway 2 Monitor Tool User's Manual

Working with Youth to Develop Critical Thinking Skills On Sexual Violence and Dating Violence: Three Suggested Classroom Activities

JA003 Výběrová angličtina pro přírodovědce

TUTORIAL FOR INITIALIZING BLUETOOTH COMMUNICATION BETWEEN ANDROID AND ARDUINO

There are a couple of notes about this however: It is best to have the IP subnet that the VoIP device on be on the same subnet as the DXL Exchanges.

Linked Lists Linked Lists, Queues, and Stacks

ΕΠΛ 674: Εργαστήριο 5 Firewalls

Deploying the BIG-IP LTM with. Citrix XenApp. Deployment Guide Version 1.2. What s inside: 2 Prerequisites and configuration notes

Practical Load Balancing

Packet Sniffing on Layer 2 Switched Local Area Networks

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Feel free to use these letters to contact your friends and family about Swim-A-Thon! Dear,

Use these cards as a matching game

TFE listener architecture. Matt Klein, Staff Software Engineer Twitter Front End

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

Cloud.. Migration? Bursting? Orchestration? Vincent Lavergne SED EMEA, South Gary Newe Sr SEM EMEA, UKISA

Preparing professionals to meet our diverse community s lifelong educational needs

Solving Systems of Linear Equations Using Matrices

BUILDING COMPETENT SMGC, HK SHANE W EARLY

Installing and Setting up Microsoft DNS Server

Project 4 DB A Simple database program

CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators

15-441: Computer Networks Project 1: Internet Relay Chat (IRC) Server

Effective performance appraisal: Asking the right questions. Professor Carol Cardno Unitec Institute of Technology Auckland, New Zealand

Fashion Design & Merchandising Course Description

ΕΠΛ 475: Εργαστήριο 9 Firewalls Τοίχοι πυρασφάλειας. University of Cyprus Department of Computer Science

STREAMEZZO RICH MEDIA SERVER

Evaluation of AgitarOne

From Systems to Services

Mining for Bugs with Graph Database Queries

Challenges for cloud software engineering

Setting up the integration between Oracle Social Engagement & Monitoring Cloud Service and Oracle RightNow Cloud Service

Variable length subnetting

Network Terminology Review

SolarWinds. Understanding SolarWinds Charts and Graphs Technical Reference

ICON UK 2015 node.js for Domino developers. Presenter: Matt White Company: LDC Via

Distributed Embedded Systems

Figure out the early start and early finish. Early start. Early finish

White Paper. Fabasoft on Linux Cluster Support. Fabasoft Folio 2015 Update Rollup 2

ABSTRACT FACTORY AND SINGLETON DESIGN PATTERNS TO CREATE DECORATOR PATTERN OBJECTS IN WEB APPLICATION

How to create Event Filters directly from the Event Viewer

The ADT Binary Search Tree

Transcription:

HackingaGoogleInterview Handout3 CourseDescription Instructors:BillJacobsandCurtisFonger Time:January12 15,5:00 6:30PMin32 124 Website:http://courses.csail.mit.edu/iap/interview Question:DeckShuffling Givenanarrayofdistinctintegers,giveanalgorithmtorandomlyreorderthe integerssothateachpossiblereorderingisequallylikely.inotherwords,givena deckofcards,howcanyoushufflethemsuchthatanypermutationofcardsis equallylikely? Goodanswer:Gothroughtheelementsinorder,swappingeachelementwitha randomelementinthearraythatdoesnotappearearlierthantheelement.this takeso(n)time. Notethatthereareseveralpossiblesolutionstothisproblem,aswellasseveral good lookinganswersthatareincorrect.forexample,aslightmodificationtothe abovealgorithmwherebyoneswitcheseachelementwithanyelementinthearray doesnotgiveeachreorderingwithequallyprobability.theanswergivenhereis,in ouropinion,thebestsolution.ifyouwanttoseeothersolutions,checkthe "Shuffling"pageonWikipedia. BinarySearchTrees Abinarysearchtreeisadatastructurethatkeepsitemsinsortedorder.Itconsists ofabinarytree.eachnodehasapointertotwochildren(oneorbothofwhichmay benull),anoptionalpointertoitsparent(whichmaybenull),andoneelementthat isbeingstoredinthetree(perhapsastringoraninteger).forabinarysearchtree tobevalid,eachnode'selementmustbegreaterthaneveryelementinitsleft subtreeandlessthaneveryelementinitsrightsubtree.forexample,abinarytree mightlooklikethis: 17 / \ 6 46 / \ \ 3 12 56 / / \ / 1 9 15 48

Tocheckwhetheranelementappearsinabinarysearchtree,oneneedonlyfollow theappropriatelinksfromparenttochild.forexample,ifwewanttosearchfor15 intheabovetree,westartattheroot,17.since15<17,wemovetotheleftchild,6. Since15>6,wemovetotherightchild,12.Since15>12,wemovetotheright childagain,15.nowwehavefoundthenumberwewerelookingfor,sowe'redone. Toaddanelementtoabinarysearchtree,webeginasifweweresearchingforthe element,followingtheappropriatelinksfromparenttochild.whenthedesired childisnull,weaddtheelementasanewchildnode.forexample,ifweweretoadd 14totheabovetree,wewouldgodownthetree.Oncewereached15,wewouldsee thatthenodehasnoleftchild,sowewouldadd14asaleftchild. Toremoveanelementfromabinarysearchtree,wefirstfindthenodecontaining thatelement.ifthenodehaszerochildren,wesimplyremoveit.ifithasonechild, wereplacethenodewithitschild.ifithastwochildren,weidentifythenextsmallerornext largerelementinthetree(itdoesn'tmatterwhich),usingan algorithmwhichwedonotdescribehereforthesakeofbrevity.wesettheelement storedinthenodetothisvalue.then,wesplicethenodethatcontainedthevalue fromthetree.thiswillberelativelyeasy,sincethenodewillhaveatmostonechild. Forexample,toremove6fromthetree,wefirstchangethenodetohavethevalue 3.Then,weremovethenodethatusedtohavethevalue3,andwemake1theleft childofthenodethatusedtohavethevalue6. Asmallmodificationtoabinarysearchtreeallowsittobeusedtoassociatekeys withvalues,asinahashtable.insteadofstoringasinglevalueineachnode,one couldstoreakey valuepairineachnode.thetreewouldbeorderedbasedonthe nodes'keys. Interviewerssometimesaskaboutbinarysearchtrees.Inaddition,binarysearch treesareoftenusefulasacomponentofananswertointerviewquestions.the importantthingtorememberisthatinsertion,removal,andlookuptakeo(logn) time(wherenisthenumberofelementsinthetree),sincetheheightofawellbalancedbinarysearchtreeiso(logn).althoughintheworstcase,abinarysearch treemighthaveaheightofo(n),thereare"self balancing"binarysearchtreesthat periodicallyreorganizeabsttoensureaheightofo(logn).manyself balancing BST'sguaranteethatoperationstakeO(logn)time.Ifyouwanttolearnmoreabout particulartypesbinarysearchtrees,suchasred blacktrees,werecommendlooking themup. Question:PathBetweenNodesinaBinaryTree Designanalgorithmtofindapathfromonenodeinabinarytreetoanother.

GoodAnswer:Therewillalwaysbeexactlyonepath:fromthestartingnodetothe lowestcommonancestorofthenodestothesecondnode.thegoalistoidentifythe lowestcommonancestor. Foreachnode,keeptrackofasetofnodesinthebinarytree(usingahashtableora BST)aswellasacurrentnode.Ateachiteration,foreachofthetwocurrentnodes, changethecurrentnodetobeitsparentandaddittotheappropriateset.thefirst elementthatisaddedtoonesetwhenitisalreadypresentintheothersetisthe lowestcommonancestor.thisalgorithmtakeso(n)time,wherenisthelengthof thepath.forexample,ifwewerefindingthelowestcommonancestorof3and15 intheabovetree,ouralgorithmwoulddothefollowing: Current node 1 Current node 2 Set 1 Set 2 -------------------------------------------------------- 3 15 3 15 6 12 3, 6 15, 12 17 6 3, 6, 17 15, 12, 6 Toimprovethesolution,weactuallyonlyneedtouseonesetinsteadoftwo. BitwiseOperations Integersarerepresentedinacomputerusingbasetwo,usingonly0'sand1's.Each placeinabinarynumberrepresentsapoweroftwo.therightmostbitcorresponds to2^0,theseconddigitfromtherightcorrespondsto2^1,andsoon.forexample, thenumber11000101inbinaryisequalto2^0+2^2+2^6+2^7=197.negative integerscanalsoberepresentedinbinary;lookup"two'scomplement"on Wikipediaformoredetails. Thereareafewoperationsthatacomputercanperformquicklyononeortwo integers.thefirstis"bitwiseand",whichtakestwointegersandreturnsaninteger thathasa1onlyinplaceswherebothoftheinputshada1.forexample: 00101011 & 10110010 ---------- 00100010 Anotheroperationis"bitwiseor",whichtakestwointegersandreturnsaninteger thathasa0onlyinplaceswherebothoftheinputshada0.forexample: 00101011 10110010 ---------- 10111011

"Bitwisexor"hasa1ineachplacewherethebitsinthetwointegersisdifferent. Forexample: 00101011 ^ 10110010 ---------- 10011001 "Bitwisenegation"takesanumberandinvertseachofthebits.Forexample: ~ 00101011 ---------- 11010100 "Leftshifting"takesabinarynumber,addsacertainnumberofzerostotheend,and removesthesamenumberofbitsfromthebeginning.forexample,00101011<<4 isequalto10110000.likewise,rightshiftingtakesabinarynumber,addsacertain numberofzerostothebeginning,andremovesthesamenumberofbitsfromthe end.forinstance,00101011>>>4=00000010.actually,thereisamorecommon formofrightshifting(the"arithmeticrightshift")thatreplacesthefirstfewbits withacopyofthefirstbitinsteadofwithzeros.forexample,10110010>>4= 11111011. Interviewersliketoaskquestionsrelatedtobitwiselogic.Often,thereisatricky waytosolvetheseproblems.bitwisexorcanoftenbeusedinatrickywaybecause twoidenticalnumbersinanexpressioninvolvingxorwill"cancelout".forexample, 15^12^15=12. Question:Compute2^x Howcanyouquicklycompute2^x? Goodanswer:1<<x(1left shiftedbyx) Question:IsPowerof2 Howcanyouquicklydeterminewhetheranumberisapowerof2? Goodanswer:Checkwhetherx&(x 1)is0.Ifxisnotanevenpowerof2,the highestpositionofxwitha1willalsohavea1inx 1;otherwise,xwillbe100...0 andx 1willbe011...1;and'ingthemtogetherwillreturn0.

Question:BeatingtheStockMarket Sayyouhaveanarrayforwhichtheithelementisthepriceofagivenstockondayi. Ifyouwereonlypermittedtobuyoneshareofthestockandselloneshareofthe stock,designanalgorithmtofindthebesttimestobuyandsell. Goodanswer:Gothroughthearrayinorder,keepingtrackoftheloweststockprice andthebestdealyou'veseensofar.wheneverthecurrentstockpriceminusthe currentloweststockpriceisbetterthanthecurrentbestdeal,updatethebestdeal tothisnewvalue. ProgramDesign Althoughitsometimesmayseemlikeit,interviewersaren'talwaysinterestedin littleprogrammingtricksandpuzzles.sometimestheymayaskyoutodesigna programorasystem.forexample,it'snotuncommontobeaskedtosketchout whatclassesyouwouldneedifyouweretowriteapokergameprogramora simulationofcartrafficatanintersection.therearemanydifferentquestionsthe interviewercouldaskaboutdesign,sojustkeepinmindthatifyouneedtodesign theclassesforaprogram,trytokeepyourdesignsimpleandatthesametimeallow forfutureextensionsonyourdesign. Forexample,ifyouweredesigningafive carddrawpokergameprogram,youcould haveagamemodeinterfaceorsuperclassandhaveafivecarddrawsubclassto encapsulatetheparticularrulesforthatversionofthegame.thereforeifthe interviewerthenasksyouhowyoucouldextendthesystemtoallowatexashold 'emgame,youcouldsimplyagainmakeatexasholdemsubclassofgamemode. DesignPatterns Adesignpatternisausefuldesigntechniquethatprogrammershavediscoveredto besousefulovertheyearsthattheygiveaspecificnametoit.interviewers sometimesaskyoutolistsomedesignpattersyouknow,andmayevenaskyouto describehowaparticularoneworks.butbesidesquestionsthatdirectlytestyour knowledgeofthem,designpattersareveryusefulasbuildingblocksforsolving otherquestions,especiallytheonesthatfocusonprogramdesign.thereareseveral designpatternsthatexist,andwerecommendthatyoutakealookatthe"design Pattern"pageonWikipediatogetanideaofseveralofthebest knowones,butthere areafewthattrulystandoutintheirpopularityandusefulness. Listener/ObserverPattern: Thismaybethemostpopulardesignpatternoutthere.Theideaisthis:suppose therewereane maillistforhackingagoogleinterview(unfortunatelythereisn't one,butifwehadbeenabitmoreforward thinking,perhapswewouldhavemade one).thislistwouldallowforimportantannouncementstobesenttoanyonewho

caredabouttheclass.everystudentwhoputthemselvesonthelistwouldbea "listener"(or"observer").theteacherwouldbethe"announcer"(or"subject"in sometexts).everytimetheteacherwantedtoletthestudentsknowsomething, theywouldgothoughthee maillistandsendanannouncemente mailtoeach listener. Inaprogram,wewouldhaveaListenerinterfacethatanyclasscouldimplement. ThatListenerinterfacewouldhavesomesortof"update()"methodthatwouldbe calledwhenevertheannouncerwantedtotellthelistenerssomething.the announcerwouldstorealistofallthelisteners.ifwewantedtoaddanobject"foo" asalistener,wewouldcall"announcer.addlistener(foo)",whichwouldcausethe announcertoaddfootoitslistoflisteners.whenevertheannouncerdidsomething importantthatitwantedtotellthelistenersabout,itwouldgothoughitslistof listenersandcall"update()"oneachofthoseobjects. Goingbacktothepokergameprogram,youmightmentiontotheinterviewerthat youcouldusethelistenerdesignpatternforseveralthings.forexample,youcould havetheguibealistenertoseveralobjectsinthegame(suchasplayerhands,the pot,etc.)foranychangesingamestateforwhichitwouldneedtoupdatethe display. SingletonPattern: Thesingletonpatternisusedwhenyouwanttomakesurethereisexactlyone instanceofsomethinginyourprogram.ifyouweremakingalordoftherings game,youwouldwanttomakesurethattheoneringwasonlyinstantiatedonce! WehavetogiveFrodoachance! InJava,forinstance,tomakesurethereisonlyoneofsomething,youcando somethinglikethis: public class OnlyOneOfMe { private static OnlyOneOfMe theoneinstance = null; private OnlyOneOfMe() { // do stuff to make the object } } public static OnlyOneOfMe getinstance() { if (theoneinstance == null) { theoneinstance = new OnlyOneOfMe(); } return theoneinstance; }

Noticethatthereisnopublicconstructor.Ifyouwantaninstanceofthisclass,you havetocall"getinstance()",whichensuresthatonlyoneinstanceoftheclassisever made. Model View Controller: Model view controller(mvc)isadesignpatterncommonlyusedinuserinterfaces. Itsgoalistokeepthe"data"separatefromtheuserinterface.Forexample,when designingaprogramthatdisplaysstockinformation,thecodethatdownloadsthe stockinformationshouldnotdependonthecodethatdisplaystheinformation. Theexactmeaningofmodel view controllerisabitambiguous.essentially,a programthatusesmodel view controllerusesseparateprogrammingentitiesto storethedata(the"model"),todisplaythedata(the"view"),andtomodifythedata (the"controller").inmodel view controller,theviewusuallymakesheavyuseof listenerstolistentochangesandeventsinthemodelorthecontroller. Model view controllerisagoodbuzzwordtowhipoutwhenyou'reaskedadesign questionrelatingtoauserinterface. ClassicQuestion#7:RansomNote Let'ssayyou'vejustkidnappedAlyssaHackeryouwanttoleavearansomnotefor BenBitdiddle,sayingthatifheeverwantstoseeheragain,heneedstoswearto neveruseschemeagain.youdon'twanttowritethenotebyhand,sincetheywould beabletotraceyourhandwriting.you'restandinginalyssa'sapartmentandyou seeamillioncomputermagazines.youneedtowriteyournotebycuttingletters outofthemagazinesandpastingthemtogethertoformaletter.here'sthe question:givenanarbitraryransomnotestringandanotherstringcontainingallthe contentsofallthemagazines,writeafunctionthatwillreturntrueiftheransom notecanbemadefromthemagazines;otherwise,itwillreturnfalse.remember, everyletterfoundinthemagazinestringcanonlybeusedonceinyourransomnote. Forexample,iftheransomnotestringwas"noscheme"andthemagazinestring was"programminginterviewsareweird",youwouldreturnfalsesinceyoucan't formthefirststringbygrabbingandrearranginglettersfromthesecondstring. Pretty goodanswer:makeadatastructuretostoreacountofeachletterinthe magazinestring.ifyou'reprogramminginc,youcanmakeanarrayoflength256 andsimplyusetheasciivalueforeachcharacterasitsspotinthearray,since charactersare1byte.ifyou'reprogramminginjava,youcanjustuseahashtable instead(sincecharactersare2bytesinjava).thengothroughthemagazinestring andforeachcharacter,incrementthevalueforthatletterinyourdatastructure. Afteryougothoughthewholemagazinestring,youshouldhaveanexactcountof howmanytimeseachcharacterappearsinthemagazinestring.thengothrough eachcharacterintheransomnotestringandforeverycharacteryouencounter,

decrementthevalueforthatletterinyourdatastructure.ifyoueverfindthatafter youdecrementacounttosomethinglessthan0,youknowyoucan'tmakethe ransomnote,soyouimmediatelyreturnfalse.ifhoweveryougetthoughtheentire ransomnotewithoutrunningoutofavailableletters,youreturntrue. Evenbetteranswer:Becausethemagazinestringmaybeverylarge,wewantto reducethetimewespendgoingthroughthemagazinestring.weusethesameidea asabove,exceptwegothroughtheransomnoteandthemagazinestringatthe sametime.keeponepointerforourcurrentcharacterintheransomnoteand anotherpointerforourcurrentcharacterinourmagazinestring.first,checktosee ifthecountinourdatastructureforourcurrentransomnotecharacterisgreater than0.ifitis,decrementitandadvancethepointerinourransomnote.ifitisn't, startgoingthroughthecharactersinthemagazinestring,updatingthecountsinthe datastructureforeachcharacterencountered,untilwereachthecharacterweneed forourransomnote.thenstopadvancingthemagazinestringpointerandstart advancingtheransomnotepointeragain.ifwegettotheendoftheransomnote, wereturntrue.ifwegettotheendofthemagazinestring(meaningwedidn'tfind enoughlettersforourransomnote),wereturnfalse.