Table Of ContentELEMENTS OF
PROGRAMMING
INTERVIEWS w
Java
A
¥
ADNAN AZIZ
TSUNG-HSIEN LEE
AMIT PRAKASH
Elements of
Programming
Interviews in Java
The Insiders' Guide
AdnanAziz
Tsung-HsienLee
AmitPrakash
ElementsOfProgramminglnterviews.com
Adnan Aziz isa ResearchScientistatFacebook. Previously, hewasa professor at
theDepartmentof ElectricalandComputerEngineeringatTheUniversityof Texas
atAustin,whereheconductedresearchandtaughtclassesinappliedalgorithms.He
receivedhisPh.D.fromTheUniversityofCaliforniaatBerkeley;hisundergraduate
degreeisfromIndianInstitutesof TechnologyKanpur. HehasworkedatGoogle,
Qualcomm,IBM,andseveralsoftwarestartups. Whennotdesigningalgorithms,he
playswithhischildren,Laila,Imran,andOmar.
Tsung-Hsien Lee is a Senior Software Engineer at Uber. Previously, he worked
as a Software Engineer at Google and as Software Engineer Intern at Facebook.
He received both his M.S. and undergraduate degrees from National Tsing Hua
University. Hehasapassionfordesigningand implementingalgorithms. Helikes
toapplyalgorithmstoeveryaspectof hislife. Hetakesspecialprideinhelpingto
organizeGoogleCodeJam2014and2015.
Amit Prakash isa co-founder and CTO of ThoughtSpot, a Silicon Valley startup.
Previously, he was a Member of the Technical Staff at Google, where he worked
primarilyonmachinelearningproblemsthatariseinthecontextofonlineadvertising.
Before thatheworked atMicrosoftin the websearch team. He received hisPh.D.
from The University of Texasat Austin; his undergraduate degree is from Indian
InstitutesofTechnologyKanpur.Whenheisnotimprovingbusinessintelligence,he
indulgesin hispassionforpuzzles,movies,travel,andadventureswithNidhiand
Aanya.
Elementsof ProgrammingInterviews:TheInsiders'Guide
byAdnanAziz,Tsung-HsienLee,andAmitPrakash
Copyright © 2015 Adnan Aziz, Tsung-Hsien Lee, and Amit Prakash. All rights
reserved.
Nopartof thispublicationmaybereproduced,storedinaretrievalsystem,ortrans¬
mitted,inanyform,orbyanymeans,electronic,mechanical,photocopying,record¬
ing,orotherwise,withoutthepriorconsentof theauthors.
Theviewsandopinionsexpressedinthisworkarethoseof theauthorsanddonot
necessarilyreflecttheofficialpolicyorpositionoftheiremployers.
WetypesetthisbookusingPTpXandtheMemoirclass.WeusedTikZtodrawfigures.
AllanYtaccreatedthecover,basedonadesignbriefweprovided.
Thecompanionwebsiteforthebookincludescontactinformationandalistofknown
errorsforeachversionof thebook. Ifyoucomeacrossanerrororanimprovement,
pleaseletusknow.
Version2.0.0
Website: http://elementsofprogramminginterviews.com
To my father,Ishrat Aziz,
forgiving me mylifelongloveof learning
AdnanAziz
To my parents,Hsien-Kuo Leeand Tseng-Hsia Li,
for theeverlasting supportand love theygive me
Tsung-HsienLee
Tomy parents,Manju Shreeand Arun Prakash,
the most loving parents Icanimagine
AmitPrakash
Table of Contents
Introduction 1
I TheInterview 6
1 GettingReady 7
2 StrategiesForAGreatInterview 13
3 ConductingAnInterview 20
4 ProblemSolving 24
II Problems 43
5 PrimitiveTypes 44
5.1 Computingtheparityofaword 45
5.2 Swapbits 48
5.3 Reversebits 49
5.4 Findaclosestintegerwiththesameweight 50
5.5 ComputexX ywithoutarithmeticaloperators 51
5.6 Computex/y 52
5.7 Computexv 53
5.8 Reversedigits 54
5.9 Checkifadecimalintegerisapalindrome 55
5.10 Generateuniformrandomnumbers 56
5.11 Rectangleintersection 57
6 Arrays 60
6.1 TheDutchnationalflagproblem 62
6.2 Incrementanarbitrary-precisioninteger 65
I
6.3 Multiplytwoarbitrary-precisionintegers 66
6.4 Advancingthroughanarray 68
6.5 Deleteduplicatesfromasortedarray 69
6.6 Buyandsellastockonce 70
6.7 Buyandsellastocktwice 71
6.8 Enumerateallprimeston 72
6.9 Permutetheelementsofanarray 74
6.10 Computethenextpermutation 76
6.11 Sampleofflinedata 78
6.12 Sampleonlinedata 79
6.13 Computearandompermutation 81
6.14 Computearandomsubset 82
6.15 Generatenonuniformrandomnumbers 83
6.16 TheSudokucheckerproblem 85
6.17 Computethespiralorderingofa2Darray 87
6.18 Rotatea2Darray 90
6.19 ComputerowsinPascal'sTriangle 92
7 Strings 94
7.1 Interconvertstringsandintegers 95
7.2 Baseconversion 96
7.3 Computethespreadsheetcolumnencoding 98
7.4 Replaceandremove 98
7.5 Testpalindromicity 100
7.6 Reverseallthewordsinasentence 101
7.7 Computeallmnemonicsforaphonenumber 102
7.8 Thelook-and-sayproblem 104
7.9 ConvertfromRomantodecimal 105
7.10 ComputeallvalidIPaddresses 106
7.11 Writeastringsinusoidally 107
7.12 Implementrun-lengthencoding 108
7.13 Findthefirstoccurrenceofasubstring 109
8 LinkedLists 112
8.1 Mergetwosortedlists 115
8.2 Reverseasinglesublist 116
8.3 Testforcyclicity 117
—
8.4 Testforoverlappinglists listsarecycle-free 119
—
8.5 Testforoverlappinglists listsmayhavecycles 121
8.6 Deleteanodefromasinglylinkedlist 122
8.7 Removethekthlastelementfromalist 123
8.8 Removeduplicatesfromasortedlist 124
8.9 Implementcyclicrightshiftforsinglylinkedlists 125
8.10 Implementeven-oddmerge 126
8.11 Testwhetherasinglylinkedlistispalindromic 127
ii
8.12 Implementlistpivoting 128
8.13 Addlist-basedintegers 129
9 StacksandQueues 131
9.1 ImplementastackwithmaxAPI 132
9.2 EvaluateRPNexpressions 135
9.3 Testastringover forwell-formedness 137
9.4 Normalizepathnames 138
9.5 Searchapostingslist 139
9.6 Computebuildingswithasunsetview 140
9.7 Computebinarytreenodesinorderofincreasingdepth 143
9.8 Implementacircularqueue 145
9.9 Implementaqueueusingstacks 146
9.10 ImplementaqueuewithmaxAPI 147
10 BinaryTrees 150
10.1 Testifabinarytreeisheight-balanced 152
10.2 Testifabinarytreeissymmetric 154
10.3 Computethelowestcommonancestorinabinarytree 155
10.4 ComputetheLCAwhennodeshaveparentpointers 157
10.5 Sumtheroot-to-leafpathsinabinarytree 158
10.6 Findaroottoleafpathwithspecifiedsum 159
10.7 Implementaninordertraversalwithoutrecursion 160
10.8 Implementapreordertraversalwithoutrecursion 161
10.9 Computethefcthnodeinaninordertraversal 162
10.10 Computethesuccessor 163
10.11 Implementaninordertraversalwith0(1)space 164
10.12 Reconstructabinarytreefromtraversaldata 165
10.13 Reconstructabinarytreefromapreordertraversalwithmarkers . 167
10.14 Formalinkedlistfromtheleavesofabinarytree 168
10.15 Computetheexteriorofabinarytree 169
10.16 Computetherightsiblingtree 171
10.17 Implementlockinginabinarytree 173
11 Heaps 175
11.1 Mergesortedfiles 177
11.2 Sortanincreasing-decreasingarray 179
11.3 Sortanalmost-sortedarray 180
11.4 Computethekcloseststars 181
11.5 Computethemedianofonlinedata 182
11.6 Computetheklargestelementsinamax-heap 184
11.7 ImplementastackAPIusingaheap 185
12 Searching 187
12.1 Searchasortedarrayforfirstoccurrenceofk 190
iii
12.2 Searchasortedarrayforentryequaltoitsindex 191
12.3 Searchacyclicallysortedarray 192
12.4 Computetheintegersquareroot 194
12.5 Computetherealsquareroot 195
12.6 Searchina2Dsortedarray 196
12.7 Findtheminandmaxsimultaneously 198
12.8 Findthefcthlargestelement 199
12.9 FindthemissingIPaddress 202
12.10 Findtheduplicateandmissingelements 203
13 HashTables 207
13.1 Testforpalindromicpermutations 212
13.2 Isananonymousletterconstructible? 213
13.3 ImplementanISBNcache 214
13.4 ComputetheLCA,optimizingforcloseancestors 216
13.5 Computethek mostfrequentqueries 217
13.6 Findthenearestrepeatedentriesinanarray 217
13.7 Findthesmallestsubarraycoveringallvalues 218
13.8 Findsmallestsubarraysequentiallycoveringallvalues 222
13.9 Findthelongestsubarraywithdistinctentries 224
13.10 Findthelengthofalongestcontainedinterval 225
13.11 Computetheaverageofthetopthreescores 227
13.12 Computeallstringdecompositions 228
13.13 TesttheCollatzconjecture 230
13.14 Implementahashfunctionforchess 231
14 Sorting 234
14.1 Computetheintersectionof twosortedarrays 236
14.2 Mergetwosortedarrays 238
14.3 Removefirst-nameduplicates 239
14.4 Renderacalendar 240
14.5 Mergingintervals 242
14.6 Computetheunionofintervals 244
14.7 Partitioningandsortinganarraywithmanyrepeatedentries . . . 246
—
14.8 Teamphotoday 1 248
14.9 Implementafastsortingalgorithmforlists 250
14.10 Computeasalarythreshold 252
15 BinarySearchTrees 254
15.1 TestifabinarytreesatisfiestheBSTproperty 256
15.2 FindthefirstkeygreaterthanagivenvalueinaBST 259
15.3 FindtheklargestelementsinaBST 260
15.4 ComputetheLCAinaBST 261
15.5 ReconstructaBSTfromtraversaldata 262
15.6 Findtheclosestentriesinthreesortedarrays 265
IV
15.7 Enumeratenumbersoftheforma+bÿJl 267
15.8 Themostvisitedpagesproblem 269
15.9 BuildaminimumheightBSTfromasortedarray 271
15.10 InsertionanddeletioninaBST 272
15.11 TestifthreeBSTnodesaretotallyordered 275
15.12 Therangelookupproblem 276
15.13 Addcredits 279
16 Recursion 282
16.1 TheTowersofHanoiproblem 283
16.2 Generateallnonattackingplacementsof n-Queens 285
16.3 Generatepermutations 287
16.4 Generatethepowerset 289
16.5 Generateallsubsetsofsizek 291
16.6 Generatestringsof matchedparens 292
16.7 Generatepalindromicdecompositions 293
16.8 Generatebinarytrees 295
16.9 ImplementaSudokusolver 296
16.10 ComputeaGraycode 298
16.11 Computethediameterofatree 300
17 DynamicProgramming 303
17.1 Countthenumberofscorecombinations 306
17.2 ComputetheLevenshteindistance 309
17.3 Countthenumberofwaystotraversea2Darray 312
17.4 Computethebinomialcoefficients 314
17.5 Searchforasequenceina2Darray 315
17.6 Theknapsackproblem 317
17.7 Thebedbathandbeyond.comproblem 320
17.8 Findtheminimumweightpathinatriangle 323
17.9 Pickupcoinsformaximumgain 324
17.10 Countthenumberofmovestoclimbstairs 326
17.11 Theprettyprintingproblem 327
17.12 Findthelongestnondecreasingsubsequence 330
18 GreedyAlgorithmsandInvariants 333
18.1 Computeanoptimumassignmentof tasks 334
18.2 Scheduletominimizewaitingtime 335
18.3 Theintervalcoveringproblem 336
18.4 The3-sumproblem 340
18.5 Findthemajorityelement 341
18.6 Thegasupproblem 343
18.7 Computethemaximumwatertrappedbyapairofverticallines. . 345
18.8 Computethelargestrectangleundertheskyline 347
v