1. Trang chủ
  2. » Công Nghệ Thông Tin

Elements of programming interviews in java

535 104 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 535
Dung lượng 10,15 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Sincenot everyonewill have the timetoworkthrough EPIin itsentirety,wehave preparedastudy guideTable1.2onPage9to problems youshould solve, based ontheamountoftimeyouhave available.. The c

Trang 1

ELEMENTS OF PROGRAMMING

Trang 3

Adnan Azizisa Research ScientistatFacebook Previously,he wasaprofessorat

theDepartmentofElectrical andComputer Engineering atTheUniversity ofTexas

atAustin, where he conducted research andtaughtclasses inapplied algorithms He

received his Ph.D.fromTheUniversity of California at Berkeley;hisundergraduatedegreeisfromIndian Institutesof TechnologyKanpur. Hehas workedat Google,

Qualcomm,IBM,and severalsoftwarestartups.Whennot designing algorithms,he

playswith his children, Laila,Imran,andOmar

Tsung-Hsien Lee is a SeniorSoftware Engineer at Uber Previously, he worked

asa Software Engineer at Googleand asSoftware Engineer Intern at Facebook

He received both his M.S.and undergraduate degrees from National Tsing HuaUniversity Hehas apassion for designingandimplementing algorithms Helikes

to apply algorithms to everyaspectofhislife Hetakesspecial prideinhelping toorganizeGoogleCodeJam2014and2015

Amit Prakashisaco-founder and CTOof ThoughtSpot, a SiliconValleystartup.Previously, he was a Memberof the TechnicalStaff at Google,where he worked

primarilyonmachinelearningproblemsthat arise in thecontextofonlineadvertising.Beforethat he workedat Microsoftin the web searchteam Hereceived his Ph.D

fromTheUniversity of Texasat Austin; hisundergraduate degreeisfromIndianInstitutesof TechnologyKanpur.Whenhe isnot improvingbusinessintelligence,he

indulgesin hispassion forpuzzles,movies,travel, and adventures withNidhiand

Aanya

Elements ofProgrammingInterviews: The Insiders' Guide

byAdnan Aziz,Tsung-Hsien Lee,and Amit Prakash

Copyright©2015 Adnan Aziz, Tsung-Hsien Lee, and Amit Prakash All rights

reserved

Nopartofthispublication maybereproduced,stored in a retrievalsystem,ortrans¬

mitted, inany form,orbyanymeans, electronic, mechanical,photocopying,record¬

ing,orotherwise, without theprior consent ofthe authors

The views andopinions expressedin this work are thoseof the authors and donotnecessarily reflecttheofficial policyorposition oftheiremployers

Wetypesetthis bookusing PTpXand the Memoir class.WeusedTikZ todrawfigures.

AllanYtaccreated the cover, based on adesign briefweprovided

Thecompanionwebsiteforthe book includescontactinformationand a listofknownerrorsforeach versionofthe book.If youcomeacrossan error or animprovement,pleaselet us know

Version2.0.0

Website: http://elementsofprogramminginterviews.com

Trang 4

To my father, Ishrat Aziz,

forgiving me my lifelong love of learning

Adnan Aziz

for the everlasting support and love they give me

Tsung-Hsien Lee

the most loving parents I can imagine

Amit Prakash

Trang 7

6.3 Multiply two arbitrary-precision integers 66

8.4 Testfor overlappinglists—lists arecycle-free 119

8.5 Testfor overlappinglists—listsmayhavecycles 121

8.9 Implement cyclic right shift for singlylinked lists 125

8.11 Test whether asinglylinked list ispalindromic 127

ii

Trang 8

8.12 Implementlistpivoting 128

9.7 Compute binary treenodes in orderof increasing depth 143

10.3 Computethe lowest commonancestorin abinary tree 155

10.6 Find aroot toleaf pathwithspecifiedsum 159

10.7 Implementan inorder traversal without recursion 160

10.8 Implementapreordertraversal without recursion 161

10.11 Implementan inorder traversal with0(1) space 164

10.13 Reconstructabinary tree fromapreordertraversal with markers . 167

10.14 Forma linked listfromthe leavesofabinary tree 168

12.1 Search a sortedarray for firstoccurrenceofk 190

Trang 9

12.2 Search a sortedarray forentryequal toitsindex 191

13.6 Find thenearest repeatedentries in anarray 217

13.7 Find the smallestsubarray coveringall values 218

13.8 Find smallestsubarray sequentially coveringall values 222

13.9 Find thelongest subarraywith distinct entries 224

13.10 Find thelength ofalongestcontained interval 225

13.11 Computetheaverage ofthetopthree scores 227

14.7 Partitioningandsortinganarraywithmany repeatedentries . 246

15.1 Testifabinary tree satisfiestheBSTproperty 25615.2 Find thefirst keygreaterthan agivenvalue in aBST 259

15.6 Find the closest entries in three sortedarrays 265

Trang 10

15.7 Enumeratenumbersoftheform a +bÿJl 267

15.9 Build a minimumheight BST froma sortedarray 271

16.2 Generateallnonattackingplacements of n-Queens 285

17.8 Find the minimumweightpathin atriangle 323

17.10 Countthe numberofmovestoclimb stairs 326

18.7 Computethe maximumwater trapped byapair ofvertical lines . 345

Trang 11

19 Graphs 350

20.1 Implement caching fora multithreadeddictionary 376

20.3 Implement synchronization for two interleavingthreads 379

20.7 The readers-writersproblemwith writepreference 385

21.5 Designasystemfor detecting copyrightinfringement 394

21.17 Designanoptimized way of distributing large files 406

21.19 Estimate the hardwarecostofaphoto sharingapp 407

vi

Trang 12

25.2 Find thefirst missing positiveentry Q< 437

25.4 Computethe maximumproduct ofall entries but one O 43925.5 Computethelongest contiguous increasing subarray O 441

25.7 Identifypositionsattackedbyrooks O 445

Trang 13

25.8 Justifytext O' 447

25.11 Computethelongest substringwithmatchingparens O 451

25.13 Implementapostordertraversal without recursion O 454

25.17 Find the kthlargestelement—largen,small k O 462

25.22 Converta sorteddoublylinked list into aBST O 470

25.31 Computethe maximumsubarraysum in a circulararray ©'•••• 490

25.36 Searchforapair-sumin an abs-sortedarray ©> 502

25.38 Find thelongest subarraywhose sum<k & 507

Trang 14

And it ought to be remembered that thereis nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things.

Let's beginwithFigure1 below.It depicts movementsin the shareprice ofacompany

over40 days.Specifically,foreachday,the chart shows thedaily highand low, andtheprice attheopeningbell (denotedbythe whitesquare).Suppose youwereasked

in an interviewto designanalgorithmthat determines the maximumprofitthat couldhave been madeby buyingand thensellingasingleshare over agivenday range,subjecttothe constraint that thebuyand the sell havetotakeplace atthestartofthe

day.(Thisalgorithmmaybe neededtobacktest atrading strategy.)

You may want tostopreadingnow, andattemptthisproblemonyourown.First clarify theproblem For example, youshould ask for theinput format.Let'ssaytheinputconsistsof threearrays L, H,andS,of nonnegativefloatingpoint

numbers,representingthe low,high,andstarting prices foreachday.The constraintthat thepurchaseand sale have to takeplace atthestartof thedaymeansthat it

suffices toconsiderS. You maybetempted to simply return thedifferenceof the

Figure1: Share priceasafunction of time.

Trang 15

minimumand maximum elements inS.If youtryafew testcases,youwill see thatthe minimum can occurafterthe maximum, which violates therequirementin the

problem statement—youhaveto buy before youcansell

At thispoint, abrute-force algorithmwould beappropriate Foreach pair of

indicesiand j > i,if S[/]- S[i]isgreater than thelargest differenceseensofar,updatethelargest difference toS[/]- S[i], Youshould be abletocode thisalgorithmusingapair ofnestedfor-loopsand testit in amatterofafewminutes.Youshouldalso derive its timecomplexityasafunctionof thelength n of theinput array.The

outer loopisinvokedn— 1 times, and the ith iterationprocesses n1— ielements

Processingan element entailscomputingadifference, performingacompare,and

possibly updatinga variable, allofwhich takeconstanttime Hence,the run time is

proportional toYj"=o(n-1-0 = i.e., the timecomplexity ofthebrute-forcealgorithmis0(n2). Youshould also consider thespace complexity,i.e., how much

memoryyour algorithmuses.Thearray itselftakesmemory proportional ton, andthe additionalmemoryusedbythebrute-force algorithmisaconstant independent

of n—acouple ofiteratorsand onefloatingpointvariable

Onceyou have a working algorithm, try to improve upon it Specifically, an

0(n2)algorithmisusually notacceptablewhenfaced withlargearrays You may

have heardofanalgorithm designpatterncalleddivide-and-conquer It yieldsthe

followingalgorithm for thisproblem Split S into two subarrays, S[0: LfJ]and

S[Lf J+1 : n-1];computethe best resultforthefirstand secondsubarrays;andcombine these results.Inthe combinestepwetake the betterofthe resultsforthetwosubarrays However,wealso needtoconsider the case where theoptimum buyandsell takeplaceinseparatesubarrays When this is the case, thebuy mustbe in the

first subarray,and the sell in the secondsubarray,sincethebuy musthappen before

the sell If theoptimum buyand sell are indifferent subarrays,theoptimum buypriceisthe minimumpricein thefirst subarray,and theoptimumsellpriceis in themaximumpricein the second subarray Wecancomputethesepricesin0(n)timewith asinglepassovereachsubarray Therefore,the timecomplexityT(n)forthe

divide-and-conquer algorithm satisfiesthe recurrence relation T(n)= 2T(|)+ 0(n),

which solvesto0(n log«)

Thedivide-and-conquer algorithmiselegantandfast.Its implementationentailssome cornercases,e.g.,anemptysubarray, subarrays of lengthone, andanarrayinwhich thepricedecreasesmonotonically,but it can still be written and testedbya

gooddeveloperin20-30minutes

Lookingcarefullyatthe combinestepof thedivide-and-conquer algorithm, youmayhave aflashof insight Specifically,you maynoticethat the maximumprofit

that can be madeby sellingonaspecificdayisdeterminedbythe minimumofthestockpricesovertheprevious days.Sincethe maximumprofitcorresponds to selling

onsome day,thefollowingalgorithm correctlycomputesthe maximumprofit.Iteratethrough S, keepingtrackof the minimum elementmseenthusfar Ifthedifference

of thecurrentelement and misgreaterthan the maximumprofit recorded sofar,updatethe maximumprofit.Thisalgorithmperformsaconstant amountofworkperarrayelement,leading toan0(n)timecomplexity Itusestwofloat-valuedvariables(the minimum element and the maximumprofitrecorded sofar)and an iterator, i.e.,

2

Trang 16

0(1)additionalspace Itisconsiderablysimpler to implementthan the

divide-and-conquer algorithm—afewminutesshouldsuffice towriteandtestit.Workingcode

ispresentedin Solution6.6onPage70

Ifin a45-60minutes interview,youcandevelopthealgorithmdescribed above,

implementandtestit, andanalyzeitscomplexity, youwould have had averysuc¬

cessfulinterview In particular, youwould have demonstrated to yourinterviewerthatyou possessseveralkeyskills:

- Theability to rigorously formulatereal-worldproblems

- The skillstosolveproblemsanddesign algorithms

- The toolsto go fromanalgorithm toa testedprogram

- Theanalyticaltechniques required todetermine thecomputational complexity

of yoursolution

Book organization

Interviewingsuccessfullyisabout more thanbeingableto intelligentlyselect data

structuresanddesign algorithms quickly Forexample, youalso needtoknow how

toidentifysuitablecompanies,pitchyourself,askfor helpwhenyouarestuck on aninterviewproblem,andconveyyourenthusiasm Theseaspectsof interviewingarethesubjectof Chapters 1-3,and are summarized in Table 1.1 onPage8

Chapter 1isspecificallyconcerned with preparation Chapter 2discusses how

youshould conductyourselfatthe interviewitself Chapter3 describesinterviewingfromthe interviewer'sperspective.The latter isimportant forcandidatestoo,because

oftheinsightsitoffersintothe decisionmakingprocess Chapter 4reviewsproblemsolving

Sincenot everyonewill have the timetoworkthrough EPIin itsentirety,wehave

preparedastudy guide(Table1.2onPage9)to problems youshould solve, based ontheamountoftimeyouhave available

Theproblem chaptersareorganizedasfollows Chapters 5-15areconcerned withbasic datastructures,such asarraysand binarysearchtrees,and basicalgorithms,

such asbinarysearch and quicksort Inour experience, this is the material that

mostinterviewquestionsarebased on Chapters 16-19coveradvanced algorithmdesignprinciples,such asdynamic programmingand heuristics, as well asgraphs.Chapter 20 focusesonparallel programming

Eachchapter beginswith an introductionfollowed by problems The introduc¬tionitselfconsistsofabriefreviewofbasicconceptsandterminology, followed by

a bootcamp Each bootcampis(1.) astraightforward,illustrativeexamplethatil¬

lustrates the essenceofthechapterwithoutbeing too challenging;and (2.)toptipsfor thesubject matter, presentedin tabular format For chapterswhere thepro¬gramminglanguageincludesfeaturesthat are relevant, wepresentthesefeatures

in listform This list is ordered with basicusage coming first, followed bysubtler

aspects. Basicusageisdemonstratedusingmethods calls withconcretearguments,e.g.,Arrays.asList(1,2,4,8). Subtleraspectsofthelibrary,such asways toreducecodelength, underappreciated features,andpotentialpitfalls,appearlater in the list

Broadly speaking,theproblemsareorderedby subtopic,with morecommonlyasked

problems appearing first Chapter 25consistsof a collectionof morechallengingproblems

Trang 17

Domain-specificknowledgeiscovered inChapters 21,22,23,and 24,which areconcerned withsystemdesign, programming languageconcepts, object-orientedpro¬gramming,andcommonlyused tools Keepin mind that somecompaniesdonot

ask thesequestions—youshouldinvestigatethetopicsaskedby companies youare

interviewing at before investing toomuch time in them Theseproblemsare more

likely tobe askedofarchitects, seniordevelopersandspecialists

The notation,specifically the symbols we use for describing algorithms, e.g.,

£"=o i2,[a, b),<2,3,5,7),A[i : j],\x~\,(1011)2, n!,{x|x2 > 2),etc.,issummarizedstart¬ingonPage514 Itshould befamiliar to anyonewith a technical undergraduatedegree,but we stillrequestyou toreview itcarefullybefore gettingintothe book,and wheneveryouhave doubts about themeaning ofasymbol.Terms,e.g., BFSand

dequeue,areindexedstartingonPage516

The EPI editorial style

Solutions are based on basicconcepts,such asarrays,hash tables, andbinarysearch,used in cleverways Somesolutions userelativelyadvancedmachinery,e.g.,Dijk-stra'sshortestpath algorithm Youwillencountersuchproblemsin an interviewonly

if youhave agraduate degreeorclaimspecialized knowledge

Mostsolutions include codesnippets Please read Section1onPage11 to famil¬

iarizeyourselfwith theJavaconstructsandpracticesused in this book.Sourcecode,which includes randomized and directedtestcases, can befound atthe book website.Domainspecificproblemsareconceptualandnot meant tobe coded; afew algorithmdesignproblemsarealso in thisspirit

Oneofourkey design goals for EPIwastomakelearningeasierby establishinga

uniform wayin whichtodescribeproblemsand solutions.We refer toourexpositionstyleastheEPIEditorialStyle

Problemsarespecifiedasfollows:

(1.) We establish context,e.g.,a real-world scenario, anexample, etc

(2.) Westate theproblemtobe solved Unlike a textbook, but as istrueforaninterview, we donot give formalspecifications,e.g., wedonotspecifythedetailedinput formatorsaywhattodo onillegal inputs Asageneralrule,avoidwritingcode thatparses input SeePage15 foran elaboration

(3.) We giveashort hint—youshould read thisonly if yougetstuck (The hint issimilartowhat an interviewer willgiveyou if youdonotmakeprogress.)

Solutionsaredevelopedasfollows:

(1.) We beginasimplebrute-force solution.

(2.) Wethenanalyzethebrute-force approachandtrytogetintuition for whyit is

inefficientand where we canimprove uponit, possibly by looking at concrete

examples,relatedalgorithms, etc

(3.) Based on theseinsights,wedevelopamore efficient algorithm,and describe it

inprose

(4.) Weapplytheprogram toaconcrete input

(5.) We give code forthekeysteps.

(6.) We analyzetimeandspacecomplexity.

(7.) Weoutlinevariants—problemswhoseformulationorsolution is similartothesolvedproblem Usevariantsfor practice,and to test your understanding of

the solution

4

Trang 18

Notethatexceptionsexiststothisstyle—for exampleabrute-forcesolutionmaynotbemeaningful,e.g., ifit entailsenumeratingalldouble-precisionfloatingpoint

numbers in somerange Forthechapters atthe endofthe book, whichcorrespond

tomoreadvancedtopics,such asDynamic Programming,andGraph Algorithms,

we use moreparsimonious presentations, e.g.,weforgoexamples of applyingthederivedalgorithm toaconcrete example

Level and prerequisites

Weexpect readerstobefamiliarwith datastructuresandalgorithms taught atthe

undergraduatelevel Thechaptersonconcurrencyandsystemdesign requireknowl¬

edge oflocks, distributedsystems,operatingsystems(OS), andinsightintocommonly

usedapplications Some of the material in the laterchapters,specificallydynamicprogramming,graphs,andgreedy algorithms,ismoreadvanced andgearedtowardscandidates withgraduate degreesorspecialized knowledge

The reviewatthestartof eachchapterisnot meant tobecomprehensiveandifyouarenotfamiliarwith the material, youshould first studyit in analgorithms

textbook There are dozensofsuchtextsand ourpreferenceisto masteroneortwogoodbooks rather thansuperficiallysample many AlgorithmsbyDasgupta, etal.issuccinctandbeautifullywritten; Introductionto Algorithmsby Cormen, et al.isan

amazing reference

Reader engagement

Manyof the best ideas in EPIcamefromreaders likeyou Thestudy guide, ninja

notation, andhints, are afew examples of many improvementsthat werebrought

aboutbyourreaders Thecompanionwebsite, elementsofprogramminginterviews.com,includes a Stack Overflow-style discussionforum, and links to oursocial media

presence Italso has linksblog postings,code, and bugreports. Youcanalways

communicatewith usdirectly—ourcontactinformationisonthe website

Trang 19

Part I

The Interview

Trang 20

Before everything else, getting ready is the secret of success.

—H FORDThemost importantpartofinterviewpreparationisknowingthe material andprac¬ticingproblem solving However,the nontechnicalaspectsof interviewingarealso

very important,and oftenoverlooked Chapters1-3 are concerned with the non¬technicalaspectsof interviewing, ranging fromr6sum6preparation tohowhiring

decisions are made Theseaspectsof interviewingaresummarized in Table1.1onthefollowingpage

Study guide

Ideally,youwouldprepare foran interviewby solvingall theproblemsinEPI.This

isdoable over12monthsif yousolve aproblemaday,wheresolvingentailswriting

aprogramandgettingittowork on sometestcases

Sincedifferentcandidates havedifferenttime constraints, we have outlined several

studyscenarios, and recommended a subsetof problems foreach scenario This

informationissummarized in Table1.2on Page9 Thepreparationscenariosweconsider are Hackathon (a weekend entirelydevoted to preparation), finalscram(one week, 3-4 hoursper day), term project (fourweeks,1.5-2.5hoursper day),and

algorithmsclass (3-4 months, 1 hourper day)

TheproblemsinEPIare meant tobe representative of theproblems you will

encounterin an interview.If youneed a datastructureandalgorithms refresher,take

a lookattheEPIwebsite, which includes a collectionofreviewproblemsthat willgetyou ready for EPImorequicklythat a textbook would

Alarge majority of the interviewquestions at Google,Amazon,Microsoft,andsimilarcompaniesaredrawnfrom thetopicsinChapters 5-15 Exercise commonsensewhenusingTable1.2, e.g., if youareinterviewing forapositionwith afinancialfirm,do moreproblemsrelatedto probability

Althoughan interviewermay occasionallyask aquestion directly from EPI, you

shouldnotbaseyour preparationonmemorizingsolutions.Rote learningwilllikely

leadto your givingaperfectsolutiontothewrong problem

Chapter 25containsa diverse collectionof challenging questions Usethemto

honeyour problem solvingskills, butgo tothemonly afteryouhave mademajor

inroads into the earlierchapters If youhave agraduate degree,orclaimspecializedknowledge,youshoulddefinitelysolve someproblems from Chapter 25

Trang 21

The Interview Lifecycle, on the current

page

• Identifycompanies,contacts

• Resumepreparation

o Basicprinciples

o Website withlinks toprojects

o Linkedlnprofile&recommendations

General Advice, on Page 17

• Knowthecompany&interviewers

• Mindyourbodylanguage

• Be ready fora stress interview

• Learn from badoutcomes

• Negotiatethe bestoffer

At the Interview, on Page 13

• Don'tsolvethewrong problem

• Getspecs&requirements

• Spellout thebrute-force solution

• Applypatterns

• Assumevalid inputs

• Testforcorner-cases

• Useproper syntax

• Managethe whiteboard

• Be aware ofmemorymanagement

• Getfunction signatures right

Conducting an Interview, on Page 20

• Don'tbeindecisive

• Create a brandambassador

• Coordinatewithotherinterviewers

o lookfor patterns of mistakes

• Characteristicsofagoodproblem:

o nosinglepoint of failure

o hasmultiplesolutions

o coversmultipleareas

o is calibratedoncolleagues

o does notrequireunnecessarydomain

knowledge

• Controlthe conversation

o draw outquietcandidates

o manageverbose/overconfidentcandi¬ dates

• Useaprocessfor recording&scoring

• Applythelitmustest

Generally speaking,interviewing takesplaceinthefollowingsteps:

(1.) Identify companies that you are interested in,and, ideally,find people you

know at thesecompanies

(2.) Prepare yourresumeusing theguidelineson thefacing page,and submitit via

a personalcontact (preferred),or throughanonline submissionprocessora

campuscareerfair

(3.) Perform an initialphonescreening, which oftenconsistsof a question-answersessionover thephoneor video chat with an engineer Youmaybe asked tosubmit codeviaa shared documentoranonlinecodingsitesuch as ideone.com,collabedit.com,orcoderpad.io Don't take the screeningcasually—it canbe ex¬

tremely challenging

(4.) Gofor anon-siteinterview—thisconsistsof aseriesofone-on-oneinterviewswith engineers andmanagers,and a conversation withyour HumanResources

8

Trang 22

Table1.2: First read Chapter 4. Foreach chapter, first read its introductorytext Usetextbooks for reference only Unlessaproblem is italicized, it entails writing code.ForScenarioi,write andtestcode for the problems in Columns0 toi-1, and pseudo-code for the problems in Columni.

Scenario 1 Scenario 2 Scenario 3 Scenario 4

Hackathon Finals cram Term project Algorithms

(5.) Receiveoffers—these areusuallyastartingpoint for negotiations

Note that there may be variations—e.g., acompany may contact you, or youmaysubmit viayour college'scareerplacement center Thescreeningmayinvolve

a homeworkassignment tobe donebeforeorafter the conversation The on-siteinterviewmaybe conducted over a video chat session Moston-sitesarehalfaday,

but othersmaylast the entireday For anything involvinginteractionovera network,

beabsolutelysuretoworkout logistics(aquietplace totalk with a landline ratherthan a mobile,familiaritywith thecodingwebsite and chatsoftware,etc.) well inadvance

Werecommend thatyouinterviewatasmany placesasyoucanwithout ittakingaway from yourjoborclasses Theexperiencewillhelp you feelmorecomfortable

withinterviewingandyou maydiscoveryou reallylike acompanythatyoudidnot

know much about

The resume

It alwaysastonishes ustoseecandidates who've worked hardfor atleastfour years

in school, andoften many more in theworkplace, spend30 minutesjottingdownrandomfactoidsabout themselves andcallingthe result a r6sum6

A r6sum6 needstoaddressHR staff,the individualsinterviewingyou,and the

hiring manager TheHR staff, who typically firstreview your resume, look forkeywords,soyouneedtobe sureyouhave those covered Thepeople interviewingyouand thehiringmanagerneedtoknow whatyou'vedone that makesyou special,

soyouneedtodifferentiateyourself.

Hereare somekey points to keepin mind whenwritinga r6sum&

Trang 23

(1.) Havea clearstatementof yourobjective;inparticular,make sure thatyoutailor

yourr6sum6foragivenemployer

E.g.,"My outstanding abilityisdevelopingsolutionsto computationallychal¬

lengingproblems; communicatingthem in written and oral form; andworking

withteams to implementthem.Iwould liketo applythese abilitiesat XYZ."

(2.) The most important points—the ones that differentiate you from everyone

else—should comefirst People reading your r6sum6proceedinsequential

order, soyou want to impressthem with what makesyou special earlyon

(Maintainingalogical flow, thoughdesirable, issecondarycompared tothis

principle.)

Asaconsequence, youshouldnotlistyour programming languages,work,etc earlyon, since these arelikelycommon to everyone Youshouldlistsignificantclassprojects(this alsohelpswithkeywords forHR.), as well

course-as talks/papers you've presented,and even standardized testscores, if trulyexceptional

(3.) The r6sum6 should beofahigh-quality:nospellingmistakes; consistentings,capitalizations, numberings;andcorrect grammarandpunctuation Usefew fonts.PortableDocument Format(PDF) ispreferred,since it renders wellacrossplatforms.

spac-(4.) Includecontact information,a Linkedlnprofile,and,ideally,aURL toapersonalhomepagewithexamples of yourwork Thesesamples maybe classprojects,athesis, and linksto companiesandproducts you'veworked on Includedesign

documents as well as alink toyourversioncontrolrepository

(5.) If youcanworkatthecompanywithoutrequiringany special processing (e.g.,

if youhave aGreenCard, and areapplying forajobin theUS), make anoteof

that

(6.) Have friendsreviewyourr6sum6;theyare certaintofind problemswith itthat

youmissed.Itisbettertogetsomethingwrittenup quickly,and thenrefineitbased onfeedback

(7.) A r6sum6 doesnothavetobe onepage long—two pagesareperfectlyappro¬priate.(Overtwo pagesisprobably notagoodidea.)

(8.) As a rule, weprefernot toseea listof hobbies/extracurricularactivities(e.g.,

"readingbooks","watching TV", "organizing teapartyactivities") unlessthey

arereally different (e.g., "Olympicrower") andnotcontroversial

Wheneverpossible,have afriendorprofessionalacquaintance atthecompany routeyour r6sum6totheappropriate manager/HR contact—the oddsof it reachingthe

righthands are muchhigher Atonecompanywhosepracticeswe arefamiliarwith,

a r6sum6 submittedthroughacontactis50timesmorelikely toresult in a hire thanonesubmitted online Don'tworryaboutwastingyourcontact's time—employeesoftenreceivea referralbonus, and being responsible for bringing instarsisalsoviewedpositively

Mock interviews

Mock interviews are agreatway of preparing foran interview Getafriend toask

you questions (from EPIoranyother source) and solve them on a whiteboard, with

penandpaper,or ona shared document.Have your friendtakenotesandgiveyou

10

Trang 24

feedback,bothpositiveandnegative Makea videorecording ofthe interview You

willcringeasyouwatch it, but it is bettertolearnof yourmannerismsbeforehand

Askyour friend to givehints whenyougetstuck Inadditionto sharpening yourproblem solvingandpresentationskills, theexperiencewillhelpreduceanxiety at

the actual interviewsetting Ifyou cannot findafriend, youcanstillgo throughthesameprocess, recordingyourself.

Usuallywedeclarehelperclasses as static inner classesofthetop-levelclass that

providesthe solution.Youshould becomfortablewith thesyntaxusedtoinstantiate

ananonymousclass,e.g.,thecomparator objectin thesortingcode onPage235.Ourtestcode lives within themainO methodofthetop-levelclass.Wealso have

aJunit testsuite, with onetest per programwhichjust wrapsthe eachprogram's

main().

Wehave electednot tousepopular third-partylibraries, such asApache Commons,

andGoogle Guava—everyprogramusestheJDK,andnothingelse.We wroteavery

small numberof utility functions, largely for testcode,e.g., filland printmethods

Apart fromthese,everysolutionfileisself-contained

Whereverpossible, youshould use the standardlibrary forbasic containers.Someproblems explicitly require you towriteyourown containerclasses

Best practices for interview code

Nowwedescribepracticeswe use inEPIthat arenotsuitablefor productioncode

Theyarenecessitatedbythefinitetime constraintsofan interview.SeeSection2on

Page14 formoreinsights

• Wemakefields public,rather than usegettersandsetters

• Wedonotprotectagainstinvalidinputs, e.g.,nullreferences, negativeentries

in anarraythat'ssupposed tobe allnonnegative, input streamsthat contain

objectsthat arenotoftheexpectedtype,etc

• We occasionally use staticfields to passvalues—this reduces the numberof

classes we needtowrite,atthecostof losingthreadsafety.

• Whenaskedto implementa container class, wedonot provide genericsolutions,

e.g.,wespecializethe containertoInteger,evenwhen atypelike ? extendsNumberwill work

NowwedescribepracticeswefollowinEPIwhich areindustry-standard,but wewouldnotrecommendforan interview

• Weuselong identifiers for pedagogy, e.g.,queueOfMaximalUsers.Inan actualinterview,youshould use shorter, lessdescriptivenamesthan we have in our

programs—writingqueueOfMaximalUsersrepeatedlyisvery time-consumingcompared to writingq

Trang 25

• We followtheGoogleJavastyle guide,whichyoushould reviewbefore diving

intoEPI.Theguideisfairly straightforward —itmostlyaddressesnamingand

spacingconventions, which shouldnotbe ahigh prioritywhenpresentingyour

solution

• Weusetheappropriate exception type,e.g.,NoSuchElementExceptionwhen

dequeinganemptyqueue.This isnotneeded in an interview, wherethrowingRuntimeExceptionsuffices

• Whenspecifying types,we usethe weakesttypethatprovidesthefunctionality

weuse,e.g.,theargumenttoafunctionfor computingthe fcth smallest element

in anarrayisa List, rather thanArrayList.This isgenerallyconsidered a best

practice—it enables code reuse viapolymorphism—but isnotessentialtouse

in an interview.(You shouldspend yourtimemakingsuretheprogramworks,ratherthan,e.g., ifyoushould beusingListor RandomAccess astheargumenttype.)

Anindustrybestpracticethat we use inEPIand recommendyouuse in an inter¬view isexplicitly creatingclassesfordataclumps,i.e.,groups ofvalues that donot

haveanymethods on them.Manyprogrammerswould use agenericPair orTuple

class, but we havefoundthat this leadstoconfusingandbuggyprograms

Books

OurfavoriteJavareferenceisPeter Sestoft's"JavaPrecisely",which does agreat job

of coveringthelanguage constructswithexamples ThedefinitivebookforJavais

"Java:TheComplete Reference" byOraclePress—this,alongwith theJava Language Specification,isthego-toresourcefor language lawyers

JoshuaBloch's"EffectiveJava"(second edition) is oneof the best all-roundpro¬grammingbooks we have come across,addressing everything fromthepitfallsof

inheritance,totheExecutor framework For designpatterns,welike "Head First

Design Patterns" by Freemanet ah Its primarydrawback is its bulk TonyBevis'

"JavaDesign PatternEssentials"conveysthe samecontentin a more succinct butlessentertaining fashion Notethatprograms for interviewsaretooshort to take

advantage of designpatterns.

"JavaConcurrencyin Practice",by Goetzetal.does awonderfuljobof explainingpitfallsandpracticesaround multithreadedJavaprograms

12

Trang 26

The essence of strategy is choosing what not to do.

—M E PORTER

A typicalonehour interview with asingleinterviewer consistsof fiveminutesof

introductions andquestionsabout the candidate's r6sum6 This isfollowed by five

tofifteenminutesof questioningonbasicprogrammingconcepts. The coreof theinterview isoneortwodetaileddesign questionswhere the candidate isexpected

topresenta detailed solution on a whiteboard,paper,orintegrated development

environments(IDEs) Dependingonthe interviewer and thequestion,the solution

mayberequired toincludesyntactically correctcode andtests

Approaching the problem

No matterhow clever and wellprepared youare, the solutiontoan interviewproblemmay notoccurto you immediately Hereare somethings tokeepin mind when this

Feelfree toask the interviewer what time andspace complexityhe would like in

yoursolution If youaretoldto implementan0(n) algorithmor use0(1) space,itcansimplifyyour life considerably Itispossiblethat he willrefuse tospecifythese,

orbevagueaboutcomplexity requirements,but there is no harm inasking Even iftheyare evasive,you maygetsomeclues

Work on concreteexamples:Consider theproblem of determiningthe smallest

amountof changethatyou cannot make with agiven set ofcoins, as described on

Page30 Thisproblem may seemdifficult at first However, if you tryout thesmallestamountthatcannotbe made with some smallexamples, e.g.,(1,2), (1,3),(1,2,4), (1,2,5),youwillgetthekey insights:examine coins in sorted order, and look

foralarge"jump" —a coin which islargerthan the sumoftheprecedingcoins

Trang 27

Spell out the brute-force solution: Problems that areputto youin an interviewtend tohavean obviousbrute-forcesolution that has ahightimecomplexitycom¬

pared tomoresophisticatedsolutions For example,insteadof trying toworkout

aDPsolutionforaproblem (e.g., forProblem17.7onPage320),tryall thepossi¬

bleconfigurations. Advantages tothisapproachinclude: (1.) ithelps you exploreopportunities for optimizationand hence reach a better solution, (2.) it gives you

anopportunity todemonstrate someproblem solvingandcodingskills, and(3.) itestablishesthat bothyouand the interviewer arethinkingabout the sameproblem

Bewarned that thisstrategycan sometimesbe detrimentalifit takesalongtimeto

describe thebrute-force approach

Think out loud: One of theworst things youcando in an interview istofreeze

upwhensolvingtheproblem Itisalwaysagoodidea tothinkoutloud andstayengaged Onthe one hand, this increasesyourchancesoffindingtherightsolutionbecause itforces you toputyour thoughtsin a coherent manner.Onthe other hand,thishelpsthe interviewerguideyour thought processin therightdirection.Even ifyouarenotabletoreach thesolution, the interviewer willformsomeimpression ofyourintellectualability

Apply patterns: Patterns—general reusable solutions to commonly occurringproblems—canbe agood way toapproachabafflingproblem Examplesinclude

findingagooddatastructure, seeing if your problemisagood fit forageneralal¬

gorithmictechnique, e.g., divide-and-conquer,recursion, ordynamic programming,

andmappingtheproblem toagraph Patternsaredescribed inChapter 4

Presenting the solution

Onceyouhave analgorithm,it isimportant topresentit in a clear manner Your

solution will be muchsimpler if youtakeadvantage oflibraries such asJavaCollec¬tionsorC++Boost However,it isfarmoreimportantthatyouusethelanguage you

aremostcomfortablewith.Hereare somethings tokeepin mind whenpresentingasolution

Libraries: Do not reinvent the wheel (unless askedto inventit) In particular,masterthe libraries,especiallythe datastructures For example,donot wastetimeand losecredibility trying toremember howto passanexplicitcomparatortoaBSTconstructor.Remember that a hashfunctionshould useexactlythosefieldswhich areused in theequalitycheck Acomparison functionshould be transitive

Focus on thetop-level algorithm:It's OKtousefunctionsthatyouwillimplement

later This will letyou focusonthe mainpartofthealgorithm,willpenalize youless

if you don'tcomplete thealgorithm (Hash, equals, and compare functionsare

goodcandidatesfor deferred implementation.) Specifythatyouwill handle main

algorithm first,then comer cases AddTODOcommentsfor portionsthatyou want

tocomebackto

Manage the whiteboard: Youwilllikelyuse moreofthe board thanyouexpect,so

startatthetop-leftcomer.Make useof functions—skip implementing anythingthat'strivial(e.g.,findingthe maximumofanarray)orstandard(e.g.,a threadpool) Bestpractices for codingona whiteboard arevery different frombestpractices for coding

onaproduction project For example,don'tworryaboutskippingdocumentation,

orusingtherightindentation Writingona whiteboard is much slower than on a

14

Trang 28

keyboard,sokeeping your identifiersshort (our recommendation is no more than 7characters) butrecognizableisa bestpractice Havea conventionfor identifiers, e.g.,

i,j,kfor arrayindices,A,B,Cfor arrays, u,v,wforvectors,sforaString,sbfora

StringBuilder,etc

Assume validinputs:Inaproductionenvironment, it isgood practice tocheck

if inputsarevalid,e.g.,that astring purporting torepresentanonnegative integeractuallyconsistssolely ofnumericcharacters, noflightin a timetable arrivesbefore

itdeparts, etc.Unlesstheyarepartoftheproblem statement,in an interviewsetting,

such checks areinappropriate: they take timetocode, and distractfromthe core

problem.(You shouldclarifythisassumptionwith the interviewer.)

Test for comer cases: For many problems, your generalideamayworkfor most

validinputsbut there maybepathologicalvalidinputswhereyour algorithm(or

your implementation of it)fails For example, your binarysearch codemaycrash

if theinputisanemptyarray; oryou maydo arithmetic withoutconsideringthe

possibility of overflow Itisimportant to systematicallyconsider thesepossibilities

If there is time, write unittests Small,extreme,orrandominputsmakefor good

stimuli Don'tforgettoadd codefor checkingthe result Occasionally,the codeto

handle obscure corner casesmaybetoo complicated to implementin an interview

setting Ifso,youshould mentionto the interviewer that youare awareof these

problems,and could address themif required

Syntax: Interviewersrarelypenalize you forsmallsyntaxerrors since modern

IDEexcelat handlingthese details However,lotsofbadsyntaxmayresult in the

impressionthatyouhave limitedcoding experience Once youaredonewritingyourprogram,make apass throughittofix anyobvioussyntaxerrorsbefore claiming you

aredone

Candidatesoftentendtogetfunction signatures wrongand itreflects poorlyonthem.For example,it would bean errortowriteafunctioninCthatreturnsanarray

butnotits size

Memory management: Generally speaking,it is besttoavoidmemory manage¬ment operations altogether See if youcan reusespace For example,somelinkedlistproblemscanbe solved with0(1)additionalspace by reusing existingnodes

Your Interviewer Is Not AlanTuring:Interviewers arenot capable of analyzinglongprograms, particularlyona whiteboard orpaper Therefore, theyaskquestions

whose solutions use shortprograms A good tipisthatif yoursolution takes morethan50-70linestocode, it's asignthatyouareonthewrongtrack, andyoushouldreconsideryour approach

Know your interviewers & the company

Itcanhelp youagreatdealif thecompanycanshare withyouthebackground ofyourinterviewers in advance Youshould use search and social networkstolearnmoreabout thepeople interviewing you Letting yourinterviewersknow thatyou

have researched them helpsbreak the ice and formstheimpression that youareenthusiastic and willgotheextramile For fresh graduates,it is alsoimportant to

thinkfromtheperspective ofthe interviewers as described inChapter3

Onceyouaceyourinterviewsand have anoffer, youhave animportantdecision

tomake—isthis theorganizationwhereyou want towork? Interviews are agreat

Trang 29

timetocollect thisinformation.Interviewsusuallyend with the interviewersletting

the candidates askquestions Youshould make the best useofthis timeby getting

theinformation youwould need andcommunicating tothe interviewerthatyouare

genuinelyinterested in thejob.Based onyourinteractionwith the interviewers,youmaygetagoodideaoftheir intellect,passion,andfairness.This extendstotheteam

andcompany

Inadditionto knowing yourinterviewers,youshould know about thecompany

vision,history, organization,products,andtechnology Youshould beready totalkabout whatspecificallyappeals to you,and toask intelligent questionsabout the

companyand the job Preparea listof questionsin advance; itgetsyou helpfulinformationaswell as showsyour knowledgeand enthusiasmfortheorganization.You mayalsowant tothinkofsomeconcreteideas aroundthingsyoucould dofor

thecompany;becareful not tocomeacross asapushyknow-it-all

All companies want brightand motivatedengineers However,companies differgreatlyin their culture andorganization Hereisabrief classification

Matureconsumer-facing company, e.g.,Google: wantscandidates who under¬standemerging technologies from theuser's perspective Suchcompanieshave a

deeper technologystack, muchof which isdevelopedin-house Theyhave the re¬sourcesand the timetotraina new hire

Enterprise-oriented company, e.g.,Oracle: looksfor developers familiar withhow large projectsareorganized, e.g., engineers who arefamiliar with reviews,documentation, andrigorous testing

Government contractor, e.g., Lockheed-Martin: values knowledge of specifi¬

cationsand testing, and looksfor engineerswho are familiar with

government-mandatedprocesses

Startup,e.g.,Uber:valuesengineerswho take initiative anddevelop productsontheir own Suchcompaniesdonothave timetotrainnewhires, and tendtohire can¬didates who arevery fastlearners or arealready familiarwith theirtechnologystack,

e.g.,their webapplication framework,machinelearningsystem,etc.Embedded

sys-tems/chipdesign company, e.g.,National Instruments: wantssoftware engineers

who knowenoughabout hardwaretointerfacewith the hardwareengineers Thetool chain anddevelopment practices atsuchcompaniestendtobevery mature

General conversation

Ofteninterviewerswill askyou questionsaboutyourpastprojects,such as a senior

design projector aninternship Thepoint of this conversation isto answer the

followingquestions:

Can the candidateclearlycommunicate acomplexidea?This is oneofthemostimportantskillsfor workingin anengineering team If youhave agrandidea toredesignabigsystem,canyoucommunicate it to your colleaguesandbringthem

on board? Itiscrucial to practicehow you willpresent yourbest work Beingprecise,clear, and having concreteexamplescangoalong wayhere Candidates

communicatingin alanguagethat isnottheirfirst language,should takeextracare

to speak slowlyand make more useofthe whiteboardtoaugmenttheir words

Is the candidatepassionateabout his work? We always wantourcolleagues to

be excited,energetic,andinspiring towork with.If you feel passionatelyaboutyour

16

Trang 30

work, andyour eyes lightupwhendescribingwhatyou'vedone, itgoesalong way

inestablishing youasagreatcolleague Hence,whenyouareasked todescribea

project fromthepast,it is bestto pick somethingthatyouarepassionateabout ratherthan aprojectthat wascomplexbut didnotinterestyou

Is there apotentialinterest match with someproject?The interviewermay gauge

areasof strengths forapotential projectmatch.If youknow therequirements ofthe

job,you may want to steer the conversation in that direction Keepin mind thatbecausetechnology changessofast many teamspreferastronggeneralist,sodon't

pigeonholeyourself.

Other advice

A bad mental andphysicalattitude can leadtoanegative outcome Don'tlet these

simplemistakes leadto your years of preparation going to waste

Be honest: Nobody wantsacolleaguewhofalselyclaimstohave tested code ordone a code review.Dishonestyin an interview is afast pass toanearlyexit.Remember,nothingbreaks the truth more thanstretchingit—youshould beready

todefend anything youclaim onyourr6sum6.If your knowledge of Pythonextends

onlyasfarashavingcut-and-paste samplecode, donotaddPython toyourresume

Similarly, ifyouhave seen aproblem before, youshouldsayso (Be sure that it

reallyisthe sameproblem,and bear in mindyoushould describe acorrectsolution

quickly if youclaimtohave solved itbefore.) Interviewers have been knownto

colludetoask the samequestion ofa candidatetoseeifhe tells the second interviewerabout thefirstinstance.An interviewermayfeignignoranceonatopiche knows in

depth toseeifa candidatepretends toknow it

Keep apositive spirit: A cheerfuland optimisticattitude can goalongway.Absolutely nothingis to begained, and much can be lost,by complaining how

difficult your journeywas, howyouarenotamorningperson,how inconsiderate the

airline/hotel/HRstaffwere,etc

Don'tapologize: Candidates sometimesapologizein advancefora weakGPA,rustycodingskills, ornot knowingthetechnologystack Theirlogicisthatby beingproactive theywill somehow benefitfromloweredexpectations Nothing canbe

furtherfromthe truth It focusesattentiononshortcomings More generally, ifyou

donotbelieve inyourself,you cannotexpectotherstobelieve inyou

Keepmoneyandperksout of the interview:Moneyisabigelement inanyjob

but it is bestleftdiscussed with theHRdivisionafteranofferismade The same is

trueforvacation time,daycaresupport,andfundingfor conferencetravel

Appearance: Most software companieshave a relaxed dress-code, and newgrad¬uates maywonderif theywill lookfoolish by overdressing.Thedamagedone when

youaretoocasual isgreaterthan the minor embarrassmentyou may feel at being

overdressed.Itisalwaysagoodideatoerronthe sideofcautionand dressformallyfor yourinterviews.Atthe minimum, be clean andwell-groomed

Be aware ofyour body language:Think ofafriendorcoworker slouched all thetimeorabsentmindedly doing thingsthatmay offendothers Work onyourposture,eye contactand handshake, and remembertosmile

Trang 31

Stress interviews

Some companies, primarilyin thefinance industry,make apractice of havingone

of the interviewerscreateastressfulsituationforthe candidate Thestress maybe

injectedtechnically, e.g.,viaaninja problem,orthroughbehavioral means,e.g.,theinterviewerrejectingacorrectanswerorridiculingthe candidate Thegoalistoseehow a candidatereacts tosuch situations—does hefallapart,becomebelligerent,or

getswayed easily.Theguidelinesin theprevioussectionshouldhelp you througha

stressinterview (Bear in mindyouwillnotknowa prioriifaparticularinterviewerwill beconductingastressinterview.)

Learning from bad outcomes

Therealityisthatnot everyinterviewresults in ajoboffer There aremanyreasons

for not gettingaparticularjob. Somearetechnical: you mayhave missed thatkeyflashof insight, e.g.,thekey to solvingthemaximum-profit onPage1 in linear time

Ifthis is the case,goback and solve thatproblem,aswell as relatedproblems.Often, yourinterviewermayhavespentafewminuteslooking atyourresume —

this is adepressinglycommonpractice.This can leadto your beingaskedquestions

ontopicsoutsideofthe areaof expertise youclaimed onyourr6sum6,e.g., routingprotocolsor Structured QueryLanguage (SQL).If so, make sure your r6sum6 is

accurate,and brushuponthattopic forthefuture

Youcanfailan interviewfornontechnical reasons,e.g., youcameacross as un¬interested, oryoudid notcommunicateclearly Thecompany mayhave decided

not tohire inyourarea, or another candidate with similarabilitybut more relevant

experiencewashired

Youwillnotgetany feedback froma badoutcome,so it isyour responsibility totryandpiece togetherthe causes Remember theonlymistakes are the onesyoudon'tlearnfrom

Negotiating an offer

An offerisnotanoffertill it is onpaper,with all the detailsfilledin All offersare

negotiable Wehave seencompensation packages bargainedup totwicethe initial

offer,but 10-20% is moretypical.Whennegotiating,remember there isnothing tobe

gained,and muchtolose,by beingrude.(Being firmisnotthe same asbeingrude.)

Togetthe bestpossible offer,getmultiple offers,and beflexibleabout theform ofyour compensation For example,basesalaryislessflexiblethan stockoptions, sign-

onbonus, relocation expenses,and Immigrationand NaturalizationService (INS)

filingcosts.Be concrete—insteadof just asking formoremoney,askfora P%highersalary Otherwise the recruiter willsimplycomeback with a small increase in the

sign-onbonus and claimtohavemet yourrequest.

YourHR contactisaprofessionalnegotiator,whosefiduciarydutyistothe com¬

pany He will know and use negotiating techniquessuch as reciprocity, getting

consensus,puttingwords inyourmouth ("don'tyouthink that'sreasonable?"), aswell as threats,togetthe bestpossibledealforthecompany.(This is what recruitersthemselves are evaluated oninternally.) TheWikipediaarticle onnegotiationlays

baremanytricks we have seen recruitersemploy

18

Trang 32

One suggestion:sticktoemail, where it is harderforsomeoneto paint youinto

a comer If youareaskedfor something(such as acopy ofacompeting offer),getsomethinginreturn Oftenit is betterto bypasstheHR contactandspeak directly

with thehiring manager

Atthe endoftheday,rememberyour long termcareer iswhatcounts,andjoining

acompanythat has abrighter future(social-mobile vs.legacyenterprise),oroffers

aposition that has moreopportunities torise(developer vs.tester) is much more

importantthan a 10-20%differenceincompensation

Trang 33

Translated"If you know both yourself and your enemy, you can win numerous battles with¬ out jeopardy "

"The Art of War,"

SUN TZU, 515 B.C.

Inthischapterwe reviewpracticesthathelpinterviewersidentifya tophire Westronglyrecommend interviewees read it—knowingwhat an interviewer islookingforwillhelp youpresent yourself better and increase the likelihoodofasuccessfuloutcome

Forsomeoneatthebeginning oftheir career,interviewingmay feellike ahugeresponsibility Hiring a bad candidate isexpensive for theorganization, not just

because the hire isunproductive,but also because he is a drain on theproductivity

ofhismentorsandmanagers,andsetsa badexample Firingsomeone isextremelypainfulaswell as badfor tothe moraleoftheteam Onthe other hand,discardinggood candidates isproblematic for a rapidly growing organization Interviewersalso havea moralresponsibility not tounfairlycrush the interviewee's dreams and

aspirations

Objective

The ultimategoal of anyinterview is todetermine the odds that a candidate will

be asuccessful employee ofthecompany The ideal candidate issmart,dedicated,articulate,collegial,andgetsthingsdonequickly,both as an individual and in ateam.Ideally,yourinterviewsshould bedesignedsuch that agoodcandidate scores 1.0 and

a bad candidate scores 0.0

Onemistake,frequentlymadebynovice interviewers, istobe indecisive Unlessthe candidate walks onwaterorcompletelydisappoints,the interviewer triesnot to

make a decision and scores the candidate somewhere in the middle This means thatthe interview was a wastedeffort

A secondaryobjectiveofthe interviewprocessisto turnthe candidate into a brandambassadorfortherecruiting organization Even ifa candidate isnotagood fit for

theorganization,hemayknow others who would be.Itisimportant forthe candidate

tohave an overallpositive experience duringtheprocess Itseemsobvious that it is

a bad ideaforan interviewertocheck email while the candidate istalkingorinsultthe candidate over a mistake he made, but such behavior isdepressinglycommon

20

Trang 34

Outsideofastressinterview, the interviewer should work onmakingthe candidate

feel positivelyabout theexperience,and,byextension, thepositionand thecompany

What to ask

One important question youshould askyourself asan interviewer is how much

trainingtime yourwork environment allows For astartupit isimportant that anewhire isproductive fromthefirstweek, whereas alarger organizationcanbudgetforseveral monthsof training Consequently,in astartupit isimportant to testthecandidate on thespecifictechnologiesthat he will use, in addition to hisgeneral

abilities

Foralarger organization,it is reasonablenot to emphasizedomainknowledge

and insteadtestcandidates on datastructures, algorithms,systemdesignskills, and

problem solving techniques.Thejustificationforthis is asfollows Algorithms,data

structures,andsystemdesignunderlie allsoftware Algorithmsand datastructure

code isusuallya smallcomponentofasystemdominatedbythe userinterface(UI),

input/output(I/O), andformatconversion.Itisoftenhidden inlibrarycalls.However,

such code isusuallythe crucialcomponentintermsofperformanceandcorrectness,

andoftenservestodifferentiate products.Furthermore,platformsandprogramminglanguages change quicklybut afirm grasp ofdatastructures, algorithms,andsystemdesign principles, willalways be a foundational part of any successful software

endeavor.Finally,many ofthemostsuccessfulsoftware companieshave hired based

onabilityandpotentialrather thanexperienceorknowledge ofspecifics,underlying

theeffectivenessofthisapproach to selectingcandidates

Most big organizations have a structured interviewprocesswhere designated

interviewersareresponsible for probingspecificareas For example, you maybeaskedtoevaluate the candidate on theircodingskills,algorithm knowledge,critical

thinking,ortheability to designcomplexsystems. This bookgivesinterviewersaccess to afairly largecollection of problems tochoose from Whenselectinga

problem keepthefollowingin mind:

Nosingle pointof failure—if youaregoing toaskjustonequestion, youshould

not pickaproblemwhere the candidatepassesthe interviewifandonly ifhegets

oneparticular insight.The best candidatemaymissasimple insight,and a mediocrecandidatemaystumble across therightidea There should beatleasttwoorthree

opportunities forthe candidatestoredeem themselves For example, problemsthatcanbe solved by dynamic programming canalmostalwaysbe solved througha

greedy algorithmthat isfastbutsuboptimumorabrute-force algorithmthat is slowbutoptimum Insuch cases, evenifthe candidatecannotgetthekey insight,he canstill demonstrate someproblem solvingabilities Problem6.6onPage70exemplifies

thistypeof question

Multiple possible solutions—if a given problem has multiplesolutions, thechancesofagoodcandidatecomingupwith a solution increases Italsogivestheinterviewermorefreedom to steerthe candidate.Agreatcandidatemay finishwithonesolutionquickly enough todiscuss otherapproachesand thetrade-offsbetweenthem.For example,Problem12.9onPage202canbe solvedusinga hash table or abitarray;the best solution makes useof binarysearch

Trang 35

Covermultipleareas—evenif youareresponsible for testingthe candidate on

algorithms, youcouldeasilypickaproblemthat alsoexposessomeaspectsof design

andsoftware development For example,Problem20.8onPage385 testscandidates

onconcurrencyaswell as datastructures Problem6.15onPage83requiresknowl¬

edge ofbothprobabilityandbinarysearch

Calibrate oncolleagues —interviewersoftenhave an incorrect notionofhowdif¬ficultaproblemisforathirtyminuteor onehour interview.Itisagoodideatochecktheappropriateness ofaproblem by askingoneof your colleagues tosolve it and

seeinghow muchdifficultytheyhave with it

Nounnecessarydomainknowledge —it isnotagoodideato quiza candidate onadvancedgraph algorithms ifthejobdoesnot requireit and the candidate doesnot

claimany special knowledge ofthefield.(Theexception tothis rule isif you want totestthe candidate'sresponse tostress.)

Conducting the interview

Conductingagoodinterview isakin tojuggling. Atahighlevel,you want toask

your questionsand evaluate the candidate'sresponses Manythingscanhappenin

an interview that couldhelp youreach a decision, so it isimportant totakenotes At

the same time, it isimportant tokeepa conversationgoingwith the candidate and

help him out ifhegetsstuck.Ideally,have a seriesofhints workedout beforehand,

which can then beprovided progressivelyasneeded Comingupwith theright set

ofhintsmay requiresomethinking Youdonot want to give awaytheproblem,yetfindaway forthe candidatetomakeprogress Hereare situationsthatmaythrow

you off:

A candidatethatgets stuck and shuts up: Somecandidatesgetintimidatedby

theproblem,theprocess,orthe interviewer, andjustshutup Insuch situations, acandidate'sperformancedoesnotreflecthistruecaliber Itisimportant toputthecandidateatease,e.g., by beginningwith astraightforwardquestion, mentioning

that aproblemistough,oraskingthemtothinkoutloud

A verbose candidate: Candidateswhogo offon tangentsand keepon talking

withoutmakingprogressrender an interviewineffective Again,it isimportant to

take controlofthe conversation.For example youcouldassertthat aparticular path

willnotmakeprogress

An overconfident candidate: Itiscommonto meetcandidates who weaken theircasebydefendingan incorrect answer Togive the candidate afair chance, it is

important todemonstrate to him that he is makinga mistake, and allowhim tocorrectit Often the best way of doing this isto construct a testcasewhere thecandidate's solution breaks down

Scoring and reporting

Atthe end ofan interview, the interviewersusuallyhave agoodidea ofhow thecandidate scored However,it isimportant tokeep notesand revisit them beforemakingafinaldecision Whiteboardsnapshotsand samples of anycode that thecandidatewroteshould also be recorded Youshould standardizescoringbased onwhich hints weregiven,howmany questionsthe candidate was abletogetto,etc.Althoughisolated minor mistakes can beignored,sometimeswhenyoulookatall

22

Trang 36

the mistakestogether,clearsigns ofweakness in certain areasmay emerge,such as alackofattentiontodetail andunfamiliaritywithalanguage.

When therightchoice isnotclear, waitforthenextcandidate insteadof possiblymakinga badhiringdecision The litmustestistoseeif youwouldreact positively

tothe candidatereplacinga valuable memberof your team

Trang 37

It's not that I'm so smart,it's just that I stay with problems longer.

—A EINSTEIN

Inthischapterwedescribeapproaches to solving programming problemsthat can

help you when youarefaced with a trickyinterview problem Specifically, wecoverkeydatastructuresin Section4.1,wepresentalgorithmpatternsin Section4.2

onPage30, we describe ideas and notationfrom complexity theoryin Section4.3

onPage40,and we discussstrategies for coping withcomputationallyintractable

problemsin Section 4.4 onPage41

Bearin minddevelopingproblem solvingskills is likelearning to playa musicalinstrument—books and teachers canpoint youin therightdirection, butonlyyour

hard work will takeyouthere Justasa musician,youneed toknow underlyingconcepts,buttheoryisnosubstitutefor practice Itisprecisely forthis reason that

EPI focusesonproblems

4.1 DATASTRUCTURE REVIEW

Adatastructureisaparticular way of storingandorganizingrelated data itemsso that

theycanbemanipulatedefficiently. Usually,thecorrectselectionofdatastructures

iskey to designingagood algorithm Differentdatastructuresaresuitedtodifferentapplications;some arehighlyspecialized For example, heapsareparticularlywell-suitedfor algorithmsthatmergesorted datastreams,whilecompiler implementationsusuallyusehash tablesto lookup identifiers

The datastructuresdescribed in thischapterarethe onescommonlyused Otherdatastructures,such asskiplists,treaps,Fibonacciheaps,tries, anddisjoint-setdata

structures,have morespecialized applications

Solutionsoften requirea combinationofdatastructures.For example, trackingthe

mostvisitedpagesona website involves a combinationofaheap,aqueue,abinary

searchtree,and a hash table.SeeSolution25.21onPage469fordetails

Trang 38

Table 4.1:Data structures.

memoryand theprimitive operationsonthem

Fastaccessforelementatan index, slowlookups(un¬less sorted) and insertions Be comfortablewith no¬tionsofiteration,resizing, partitioning, merging, etc.Knowhowstringsarerepresentedinmemory.Under¬stand basicoperatorssuch as comparison, copying,matching, joining, splitting, etc

Understandtrade-offswithrespectto arrays Becom¬

fortablewith iteration, insertion, and deletion within

singlyanddoublylinked lists Knowhow to imple¬menta list withdynamicallocation, and witharrays.Recognize where last-in first-out (stack) and first-infirst-out (queue)semanticsareapplicable Know array

and linked listimplementations

Use for representinghierarchical data Knowabout

depth, height,leaves, searchpath,traversalsequences,successor/predecessor operations

Keybenefit:0(1) lookup find-max,O(logn) insertion,

and0(logn) deletionofmax Nodeandarray repre¬

sentations.Min-heapvariant

Keybenefit: 0(1)insertions, deletions and lookups.Key disadvantages: not suitable for order-related

queries; need for resizing; poor worst-case perfor¬

mance Understand implementation using array of

buckets and collision chains.Knowhashfunctionsforintegers, strings,objects.

Key benefit: O(logn) insertions, deletions, lookups,find-min, find-max,successor,predecessorwhentree

isheight-balanced Understand nodefields, pointerimplementation Be familiarwith notionof balance,andoperations maintainingbalance

Acommonproblemrelatedtobasictypesiscomputingthe numberofbitsset to1

in aninteger-valuedvariablex.To solve thisproblem youneedtoknow howtoma¬

nipulateindividual bits in aninteger Onestraightforwardapproachisto iterativelytestindividual bitsusingthe value1asa bitmask.Specifically,weiterativelyidentify

bitsof xthat areset to 1 by examiningthe bitwise-AND of xwith the bitmask,shifting

x rightonebitata time The overallcomplexityis0(n)wherenisthelength ofthe

integer

Anotherapproach,whichmayrunfasteron someinputs,isbased oncomputing

y =x & ~(x-1), where&isthe bitwise-ANDoperatorand~isthe bitwisecomplementoperator.The variableyis1at exactlythe lowest bitof xthat is 1; all other bits inyare

0.For example, if x =(00101100)2, then x-1=(00101011)2, ~(x-1)=(11010100)2,

Trang 39

and y = (00101100)2&(11010100)2 = (00000100)2 This calculation is robust—it is

correctfor unsignedandtwo's-complement representations Consequently,this bit

maybe removedfromxby computingx ©y,where © is the bitwise-XORfunction

The timecomplexityis0(s),where s is the numberofbitsset to1 in x.

Thefactthat x&~(x-1) isolates the lowest bit that is1in x isimportant enough

thatyoushould memorize it.However,it is alsofairlyeasy toderive First,suppose

x isnot0, i.e., it has hasa bit that is one.Subtractingonefromxchangestherightmost

bittozeroandsetsall the lower bitstoone(if youadd one now,yougettheoriginal

value back) Theeffectistomaskouttherightmostone.Thereforex&~(x-1) has a

singlebitset toone,namely,therightmost 1in x. Now supposex is 0. Subtracting

onefromxunderflows, resultingin a word in which all bits areset toone Again,

x&~(x -1) is 0

Asimilar derivation shows that x &c(x -1)replacesthe lowest bit that is 1 with

0 For example, if x = (00101100)2, then x-1 = (00101011)2, so x &c(x -1) =

(00101100)2&(00101011)2=(00101000)2 Thisfactcanalso bevery useful

Considersharpeningyourbitmanipulationskillsby writing expressionsthat usebitwiseoperators,equalitychecks, and Booleanoperatorstodo thefollowing.

• Rightpropagatetherightmost setbit inx,e.g., turns(01010000)2to

(01011111)2-• Computex modulo apower of two, e.g., returns 13 for77 mod64

• Testifx is apower of 2,i.e., evaluatesto trueforx =1, 2,4, 8, ,falseforallother values

In practice, if thecomputationisdone repeatedly, themostefficient approach

would be to create a lookup table In this case, we could use a 65536 entryinteger-valued array P,such that P[/]is the number of bitsset to1 in i. If x is

64bits, the result can becomputed by decomposingx into4disjoint16-bit words,

hi, HI, hi,andhO. The 16-bit words arecomputed usingbitmasks andshifting,e.g.,

hiis(x»16 &(1111111111111111)2) Thefinalresult isP[h3] + P[h2] + P[hl] +P[M)]

Computingtheparity ofanintegeriscloselyrelatedto countingthe numberofbits

set to 1,and wepresenta detailedanalysis oftheparityproblemin Solution5.1on

Page46

Problemsinvolving manipulation ofbit-level data areoftenasked in interviews.It

iseasy tointroduce errors in code thatmanipulatesbit-level data; as thesayinggoes,

whenyou playwith bits,expecttogetbitten

ARRAYS

Conceptually,anarraymaps integersin therange [0, n- 1] toobjectsofagiventype,

wherenisthe numberofobjectsin thisarray Array lookupand insertion arefast,makingarrayssuitableforavariety ofapplications Readingpastthe last elementof

anarrayisa common error,invariablywithcatastrophic consequences

Thefollowingproblemariseswhenoptimizingquicksort: givenanarray Awhoseelements arecomparable,and an indexi,reorder the elementsof Asothat the initialelements are all less thanA[i],and arefollowed byelementsequal to A[i],which in

turnarefollowed byelementsgreaterthanA[i], using0(1)space

Thekey tothe solution istomaintaintwo regionsonoppositesidesofthearray

thatmeettherequirements,andexpandtheseregionsoneelementata time Detailsaregivenin Solution6.1onPage63

26

Trang 40

A stringcanbe viewed as aspecialkindof array, namelyonemadeoutofcharac¬

ters We treat strings separately from arraysbecause certainoperationswhich are

commonlyapplied to strings—for example, comparison, joining, splitting, searchingfor substrings, replacingonestringbyanother,parsing, etc.—donotmake senseforgeneral arrays

Oursolutiontothelook-and-sayproblemillustratesoperationsonstrings The

look-and-saysequence beginswith 1; thesubsequent integersdescribe thedigitsappearingin thepreviousnumber in thesequence Thefirst eight integersin the

look-and-saysequenceare<1, 11, 21,1211,111221,312211,13112221,1113213211) The

look-and-sayproblementailscomputingthe nthintegerin thissequence Although

theproblemiscastintermsof integers,thestringrepresentationisfarmore convenient

for counting digits.Details aregivenin Solution 7.8 onPage104

LISTS

Alistimplementsan ordered collectionofvalues, whichmayincluderepetitions In

thecontextofthis book we view a list as asequence ofnodes where each node has a

link tothenextnode in thesequence Inadoublylinked list each node also has alink

tothepriornode

Alist is similartoanarrayin that it containsobjectsin a linear order Thekeydifferencesare thatinsertingand deleting elements in a list has timecomplexity

0(1) Onthe other hand,obtainingthe fcth element in a list isexpensive, having 0(n)

timecomplexity.Lists areusually buildingblocksof morecomplexdatastructures.However, theycanbe thesubjectof tricky problemsin their ownright,asillustrated

bythefollowing:

LetLbe asinglylinked list.Assumeitsnodes are numberedstarting at0.Define

thezip of L tobe the listconsisting oftheinterleaving ofthe nodes numbered 0,1, 2,

with the nodes numberedn—1,n—2,n—3, .,wherenisthe numberofnodes in thelist

Suppose youwereaskedtowriteaprogramthatcomputesthezip ofa list, withthe constraint that it uses0(1) space. Theoperation of thisprogramisillustrated in

Figure4.1

& — H 'o IH - H ii H - HUH - HUH - H u |xl

®xl®9® 8x124® 9x183® 9x211® 8x229®

(a) List before zipping The number in hex below each node represents its address in memory.

8x229® 9x124® 9x211® 8x183®

(b) List after zipping Note that nodes are reused—no memory has been allocated.

Figure 4.1 : Zippingalist.

Ngày đăng: 04/03/2019, 10:04

TỪ KHÓA LIÊN QUAN