Share E-Book

Advanced Algorithms and Data Structures (Marcello La Rocca)(Z-Library)

Author

Rating 4.0 AI initial rating

Log in to rate

Data Structures and Algorithms
Language English

Advanced Algorithms and Data Structures introduces a collection of algorithms for complex programming challenges in data analysis, machine learning, and graph computing. Summary As a software engineer, you’ll encounter countless programming challenges that initially seem confusing, difficult, or even impossible. Don’t despair! Many of these “new” problems already have well-established solutions. Advanced Algorithms and Data Structures teaches you powerful approaches to a wide range of tricky coding challenges that you can adapt and apply to your own applications. Providing a balanced blend of classic, advanced, and new algorithms, this practical guide upgrades your programming toolbox with new perspectives and hands-on techniques.

Format PDF
Size 39.5 MB
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
M A N N I N G Marcello La Rocca Foreword by Luis Serrano
Page 2
Problems described in this book Problem Section Page Number 0-1 Knapsack 1.3, 18.1 Tasks list 2.2.1 Text compression 2.8.3 Multi-indexing 3.1 Keep a tree balanced 3.4 Memory-efficient contacts list 4.1 Non-personalized recommendations 5.1 Spell check 6.1, 6.4.1 T9 6.4.3 Autocomplete 6.4.4 Caching 7.1 Distributed cache 7.8 Find closest entry on a 2-D map 8.1 Nearest neighbor search 9.3.5 Similarity search in multi-dimensional space 10.4 Closest hub 11.1 Color reduction (compressing colors) 11.4.1 Optimization of multidimensional DB queries 11.4.3 Clustering 12 Distributed clustering 13 Shortest path on a map 14.3.6 Shortest path on a map (with roads) 14.4.4 Shortest path on a dynamic map 14.5.2 Drawing flow charts (and generic graphs) on a 2-D plane 15.1 Graph planarity 15.2 Segment intersection 15.4.1
Page 3
Advanced Algorithms and Data Structures MARCELLO LA ROCCA M A N N I N G SHELTER ISLAND
Page 4
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2021 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. Development editor: Jenny Stout 20 Baldwin Road Technical development editor: Arthur Zubarev and Aurelio De Rosa PO Box 761 Review editor: Aleksandar Dragosavljevic Shelter Island, NY 11964 Production editor: Deirdre Hiam Copy editor: Katie Petito Proofreader: Melody Dolab Technical proofreader: German Gonzalez-Morris Typesetter: Gordan Salinovic Cover designer: Marija Tudor ISBN 9781617295485 Printed in the United States of America
Page 5
Don’t let fear get in the way and don’t be afraid to say “I don’t know” or “I don’t understand” – no question is a dumb question. —Margaret H. Hamilton Simplicity is a great virtue but it requires hard work to achieve it and education to appreciate it. And to make matters worse: complexity sells better. —Edsger Dijkstra Cu `un fa nenti `un sbagghia nenti. (Only those who try make mistakes) —Sicilian proverb
Page 6
(This page has no text content)
Page 7
v contents foreword xv preface xvii acknowledgments xix about this book xxi about the author xxvi about the cover illustration xxvii 1 Introducing data structures 1 1.1 Data structures 2 Defining a data structure 2 ■ Describing a data structure 5 Algorithms and data structures: Is there a difference? 5 1.2 Setting goals: Your expectations after reading this book 6 1.3 Packing your knapsack: Data structures meet the real world 7 Abstracting the problem away 7 ■ Looking for solutions 8 Algorithms to the rescue 9 ■ Thinking (literally) outside of the box 10 ■ Happy ending 11 PART 1 IMPROVING OVER BASIC DATA STRUCTURES ................13 2 Improving priority queues: d-way heaps 15 2.1 Structure of this chapter 16
Page 8
CONTENTSvi 2.2 The problem: Handling priority 17 Priority in practice: Bug tracking 17 2.3 Solutions at hand: Keeping a sorted list 19 From sorted lists to priority queues 19 2.4 Describing the data structure API: Priority queues 19 Priority queue at work 21 ■ Priority matters: Generalize FIFO 22 2.5 Concrete data structures 22 Comparing performance 23 ■ What’s the right concrete data structure? 23 ■ Heap 24 ■ Priority, min-heap, and max- heap 26 ■ Advanced variant: d-ary heap 27 2.6 How to implement a heap 28 BubbleUp 29 ■ PushDown 33 ■ Insert 35 ■ Top 37 Update 40 ■ Dealing with duplicates 41 ■ Heapify 42 Beyond API methods: Contains 44 ■ Performance recap 45 From pseudo-code to implementation 46 2.7 Use case: Find the k largest elements 47 The right data structure . . . 47 ■ . . . and the right use 48 Coding it up 48 2.8 More use cases 49 Minimum distance in graphs: Dijkstra 49 ■ More graphs: Prim's algorithm 49 ■ Data compression: Huffman codes 50 2.9 Analysis of branching factor 55 Do we need d-ary heaps? 55 ■ Running time 56 ■ Finding the optimal branching factor 56 ■ Branching factor vs memory 57 2.10 Performance analysis: Finding the best branching factor 58 Please welcome profiling 59 ■ Interpreting results 61 ■ The mystery with heapify 66 ■ Choosing the best branching factor 67 3 Treaps: Using randomization to balance binary search trees 69 3.1 Problem: Multi-indexing 70 The gist of the solution 71 3.2 Solution: Description and API 71 3.3 Treap 72 Rotations 75 ■ A few design questions 80 ■ Implementing search 81 ■ Insert 82 ■ Delete 87 ■ Top, peek, and update 89 ■ Min, max 90 ■ Performance recap 91
Page 9
CONTENTS vii 3.4 Applications: Randomized treaps 91 Balanced trees 92 ■ Introducing randomization 94 Applications of Randomized Treaps 96 3.5 Performance analysis and profiling 97 Theory: Expected height 97 ■ Profiling height 100 ■ Profiling running time 104 ■ Profiling memory usage 106 Conclusions 107 4 Bloom filters: Reducing the memory for tracking content 110 4.1 The dictionary problem: Keeping track of things 111 4.2 Alternatives to implementing a dictionary 113 4.3 Describing the data structure API: Associative array 114 4.4 Concrete data structures 115 Unsorted array: Fast insertion, slow search 115 ■ Sorted arrays and binary search: Slow insertion, fast(-ish) search 116 ■ Hash table: Constant-time on average, unless you need ordering 117 Binary search tree: Every operation is logarithmic 118 ■ Bloom filter: As fast as hash tables, but saves memory (with a catch) 119 4.5 Under the hood: How do Bloom filters work? 120 4.6 Implementation 122 Using a Bloom filter 122 ■ Reading and writing bits 124 Find where a key is stored 126 ■ Generating hash functions 126 Constructor 127 ■ Checking a key 128 ■ Storing a key 130 Estimating accuracy 132 4.7 Applications 132 Cache 132 ■ Routers 133 ■ Crawler 134 ■ IO fetcher 134 Spell checker 134 ■ Distributed databases and file systems 135 4.8 Why Bloom filters work 135 Why there are no false negatives . . . 136 ■ . . . But there are false positives 137 ■ Bloom filters as randomized algorithms 137 4.9 Performance analysis 138 Running time 138 ■ Constructor 138 ■ Storing an element 138 ■ Looking up an element 139 4.10 Estimating Bloom filter precision 139 Explanation of the false-positive ratio formula 141 4.11 Improved variants 144 Bloomier filter 144 ■ Combining Bloom filters 144 ■ Layered Bloom filter 144 ■ Compressed Bloom filter 145 ■ Scalable Bloom filter 146
Page 10
CONTENTSviii 5 Disjoint sets: Sub-linear time processing 147 5.1 The distinct subsets problem 148 5.2 Reasoning on solutions 151 5.3 Describing the data structure API: Disjoint set 153 5.4 Naïve solution 154 Implementing naïve solution 155 5.5 Using a tree-like structure 159 From list to trees 159 ■ Implementing the tree version 160 5.6 Heuristics to improve the running time 162 Path compression 164 ■ Implementing balancing and path compression 166 5.7 Applications 168 Graphs: Connected components 169 ■ Graphs: Kruskal’s algorithm for minimum spanning tree 169 ■ Clustering 170 Unification 171 6 Trie, radix trie: Efficient string search 173 6.1 Spell-check 174 A prncess, a Damon, and an elf walkz into a bar 175 Compression is the key 176 ■ Description and API 177 6.2 Trie 177 Why is it better again? 180 ■ Search 183 ■ Insert 187 Remove 189 ■ Longest prefix 192 ■ Keys matching a prefix 193 ■ When should we use tries? 195 6.3 Radix tries 197 Nodes and edges 199 ■ Search 202 ■ Insert 204 Remove 207 ■ Longest common prefix 209 ■ Keys starting with a prefix 209 6.4 Applications 211 Spell-checker 211 ■ String similarity 213 ■ String sorting 214 T9 215 ■ Autocomplete 215 7 Use case: LRU cache 218 7.1 Don’t compute things twice 219 7.2 First attempt: Remembering values 222 Description and API 224 ■ Fresh data, please 224 ■ Handling asynchronous calls 226 ■ Marking cache values as “Loading” 227
Page 11
CONTENTS ix 7.3 Memory is not enough (literally) 228 7.4 Getting rid of stale data: LRU cache 230 Sometimes you have to double down on problems 231 ■ Temporal ordering 232 ■ Performance 238 7.5 When fresher data is more valuable: LFU 238 So how do we choose? 240 ■ What makes LFU different 240 Performance 243 ■ Problems with LFU 243 7.6 How to use cache is just as important 244 7.7 Introducing synchronization 245 Solving concurrency (in Java) 248 ■ Introducing locks 249 Acquiring a lock 250 ■ Reentrant locks 252 ■ Read locks 252 Other approaches to concurrency 253 7.8 Cache applications 254 PART 2 MULTIDEMENSIONAL QUERIES ...............................257 8 Nearest neighbors search 259 8.1 The nearest neighbors search problem 260 8.2 Solutions 261 First attempts 261 ■ Sometimes caching is not the answer 262 Simplifying things to get a hint 262 ■ Carefully choose a data structure 264 8.3 Description and API 266 8.4 Moving to k-dimensional spaces 268 Unidimensional binary search 268 ■ Moving to higher dimensions 269 ■ Modeling 2-D partitions with a data structure 270 9 K-d trees: Multidimensional data indexing 273 9.1 Right where we left off 274 9.2 Moving to k-D spaces: Cycle through dimensions 275 Constructing the BST 276 ■ Invariants 281 ■ The importance of being balanced 282 9.3 Methods 282 Search 284 ■ Insert 287 ■ Balanced tree 289 Remove 293 ■ Nearest neighbor 301 ■ Region search 310 A recap of all methods 316 9.4 Limits and possible improvements 316
Page 12
CONTENTSx 10 Similarity Search Trees: Approximate nearest neighbors search for image retrieval 319 10.1 Right where we left off 320 A new (more complex) example 321 ■ Overcoming k-d trees’ flaws 322 10.2 R-tree 322 A step back: Introducing B-trees 323 ■ From B-Tree to R-tree 324 Inserting points in an R-tree 326 ■ Search 328 10.3 Similarity search tree 330 SS-tree search 333 ■ Insert 337 ■ Insertion: Variance, means, and projections 345 ■ Insertion: Split nodes 348 ■ Delete 352 10.4 Similarity Search 359 Nearest neighbor search 359 ■ Region search 363 Approximated similarity search 364 10.5 SS+-tree 367 Are SS-trees better? 367 ■ Mitigating hyper-sphere limitations 369 Improved split heuristic 370 ■ Reducing overlap 371 11 Applications of nearest neighbor search 375 11.1 An application: Find nearest hub 376 Sketching a solution 377 ■ Trouble in paradise 379 11.2 Centralized application 380 Filtering points 381 ■ Complex decisions 383 11.3 Moving to a distributed application 386 Issues handling HTTP communication 387 ■ Keeping the inventory in sync 389 ■ Lessons learned 390 11.4 Other applications 391 Color reduction 391 ■ Particle interaction 393 ■ Multidimensional DB queries optimization 395 ■ Clustering 398 12 Clustering 400 12.1 Intro to clustering 401 Types of learning 402 ■ Types of clustering 403 12.2 K-means 405 Issues with k-means 410 ■ The curse of dimensionality strikes again 412 ■ K-means performance analysis 413 ■ Boosting k-means with k-d trees 414 ■ Final remarks on k-means 418 12.3 DBSCAN 418
Page 13
CONTENTS xi Directly vs density-reachable 419 ■ From definitions to an algorithm 420 ■ And finally, an implementation 422 Pros and cons of DBSCAN 424 12.4 OPTICS 426 Definitions 427 ■ OPTICS algorithm 428 ■ From reachability distance to clustering 433 ■ Hierarchical clustering 436 Performance analysis and final considerations 441 12.5 Evaluating clustering results: Evaluation metrics 442 Interpreting the results 446 13 Parallel clustering: MapReduce and canopy clustering 448 13.1 Parallelization 449 Parallel vs distributed 450 ■ Parallelizing k-means 451 Canopy clustering 452 ■ Applying canopy clustering 454 13.2 MapReduce 455 Imagine you are Donald Duck . . . 455 ■ First map, then reduce 459 ■ There is more under the hood 462 13.3 MapReduce k-means 463 Parallelizing canopy clustering 467 ■ Centroid initialization with canopy clustering 469 ■ MapReduce canopy clustering 471 13.4 MapReduce DBSCAN 475 PART 3 PLANAR GRAPHS AND MINIMUM CROSSING NUMBER....483 14 An introduction to graphs: Finding paths of minimum distance 485 14.1 Definitions 486 Implementing graphs 487 ■ Graphs as algebraic types 489 Pseudo-code 490 14.2 Graph properties 491 Undirected 492 ■ Connected 492 ■ Acyclic 494 14.3 Graph traversal: BFS and DFS 495 Optimizing delivery routes 495 ■ Breadth first search 497 Reconstructing the path to target 500 ■ Depth first search 502 It’s queue vs stack again 505 ■ Best route to deliver a parcel 506 14.4 Shortest path in weighted graphs: Dijkstra 507 Differences with BFS 508 ■ Implementation 509 Analysis 510 ■ Shortest route for deliveries 511
Page 14
14.5 Beyond Dijkstra’s algorithm: A* 513 How good is A* search? 517 ■ Heuristics as a way to balance real- time data 520 15 Graph embeddings and planarity: Drawing graphs with minimal edge intersections 522 15.1 Graph embeddings 523 Some basic definitions 525 ■ Complete and bipartite graphs 526 15.2 Planar graphs 528 Using Kuratowski’s theorem in practice 529 ■ Planarity testing 530 ■ A naïve algorithm for planarity testing 531 Improving performance 536 ■ Efficient algorithms 538 15.3 Non-planar graphs 539 Finding the crossing number 541 ■ Rectilinear crossing number 543 15.4 Edge intersections 545 Straight-line segments 545 ■ Polylines 549 ■ Bézier curves 550 ■ Intersections between quadratic Bézier curves 552 Vertex-vertex and edge-vertex intersections 555 16 Gradient descent: Optimization problems (not just) on graphs 558 16.1 Heuristics for the crossing number 560 Did you just say heuristics? 560 ■ Extending to curve-line edges 566 16.2 How optimization works 568 Cost functions 568 ■ Step functions and local minima 571 Optimizing random sampling 571 16.3 Gradient descent 574 The math of gradient descent 575 ■ Geometrical interpretation 576 ■ When is gradient descent appliable? 579 Problems with gradient descent 579 16.4 Applications of gradient descent 581 An example: Linear regression 583 16.5 Gradient descent for graph embedding 585 A different criterion 586 ■ Implementation 588
Page 15
CONTENTS xiii 17 Simulated annealing: Optimization beyond local minima 591 17.1 Simulated annealing 593 Sometimes you need to climb up to get to the bottom 595 Implementation 597 ■ Why simulated annealing works 598 Short-range vs long-range transitions 601 ■ Variants 602 Simulated annealing vs gradient descent: Which one should I use? 603 17.2 Simulated annealing + traveling salesman 604 Exact vs approximated solutions 606 ■ Visualizing cost 607 Pruning the domain 608 ■ State transitions 609 ■ Adjacent vs random swaps 613 ■ Applications of TSP 614 17.3 Simulated annealing and graph embedding 615 Minimum edge crossing 615 ■ Force-directed drawing 618 18 Genetic algorithms: Biologically inspired, fast-converging optimization 624 18.1 Genetic algorithms 625 Inspired by nature 627 ■ Chromosomes 631 ■ Population 633 Fitness 634 ■ Natural selection 635 ■ Selecting individuals for mating 639 ■ Crossover 645 ■ Mutations 648 ■ The genetic algorithm template 650 ■ When does the genetic algorithm work best? 651 18.2 TSP 652 Fitness, chromosomes, and initialization 653 ■ Mutations 653 Crossover 654 ■ Results and parameters tuning 656 ■ Beyond TSP: Optimizing the routes of the whole fleet 660 18.3 Minimum vertex cover 661 Applications of vertex cover 662 ■ Implementing a genetic algorithm 663 18.4 Other applications of the genetic algorithm 665 Maximum flow 665 ■ Protein folding 667 ■ Beyond genetic algorithms 668 ■ Algorithms, beyond this book 669 appendix A A quick guide to pseudo-code 671 appendix B Big-O notation 682 appendix C Core data structures 690 appendix D Containers as priority queues 704 appendix E Recursion 708 appendix F Classification problems and randomnized algorithm metrics 716 index 723
Page 16
(This page has no text content)
Page 17
xv foreword Algorithms and data structures lie at the very heart of the intersection between the beauty of theory and the excitement of cutting-edge technology. One can say that if the body of the advancements in computation is hardware, then the mind is certainly the study of algorithms and data structures. Many of the recent advances in technol- ogy have come to life thanks to the effective use of computing resources to solve prob- lems, and this is often due to the effective development and implementation of algorithms and clever use of data structures. A computer scientist, a software developer, a data scientist, or anyone whose work is dependent on the power of computation needs to be fluent in the language of algo- rithms and data structures. It is for this reason that problems in this field are some of the most common in interviews for companies in Silicon Valley or similar technology sectors. It is quite difficult, even for experts, to learn and remember all the details of all the algorithms in existence. However, it is important to have a good intuition about them in such a way that one can use them as building blocks to create larger projects or to solve problems. In order to master this intuition, one must develop a rigid theoretical and mathematical base, solid programming knowledge, and a strong understanding of the core concepts. Building this intuition is precisely what Advanced Algorithms and Data Structures does so well. In this book, Marcello combines the rigidity of the theory with the versatility of the practical application, painted with the strokes of a colorful narrative full of enjoy- able stories and real-life examples.
Page 18
FOREWORDxvi Marcello also uses his extensive experience as a developer at some of the most prominent technology companies and as a researcher in machine learning to give the reader a very clear, concise, and thorough picture of some of the most important algo- rithms and data structures used across industries and research fields. With a one-size-fits-all approach, a friendly language, and fun analogies, Marcello manages to lift the curtain and demystify complicated topics such as map reduce, genetic algorithms, and simulated annealing, with the same ease as he exposes the basics of trees and heaps. Certainly a must-read for anyone who wants to get a solid understanding of the building principles of computer science. The only question in my head after reading Advanced Algorithms and Data Structures was, “Where was this book when I was preparing for my first Silicon Valley interview?” LUIS SERRANO, PHD RESEARCH SCIENTIST IN QUANTUM ARTIFICIAL INTELLIGENCE ZAPATA COMPUTING
Page 19
xvii preface Welcome to Advanced Algorithms and Data Structures It’s great to have you on board for this journey into the world of data structures and algorithms. I hope this will be as exciting a journey for you as it was for us. The topics discussed in this book have contributed to advancing software engineer- ing and have changed the world around us. They still do make a difference, and on average, you likely come in contact every day with dozens of devices and services using these algorithms. The study of algorithms far predates the dawn of computer science: think about the Euler algorithm and the whole field of graph theory, which are three centuries old. But that’s nothing compared to the two millennia since the sieve of Eratosthenes (used to make tables of prime numbers) was first conceived. And yet, for a long time in the computer era, algorithms were mostly relegated to academia, with a few notable exceptions like Bell Labs, where between the 1950s and the 1990s their R&D teams produced great advancements in the field, such as (to name a few) dynamic programming, the Bellman-Ford algorithm, and convolutional neural networks for image recognition. Luckily, many things have changed since those days. In the new millennium, math- ematicians and computer scientists are increasingly sought by the largest software companies, new fields like machine learning have emerged, others like Artificial Intel- ligence (AI) and neural networks have regained interest after a long winter, and top experts in these fields are now among the best paid positions in the entire software engineering industry.
Page 20
PREFACExviii Personally, I became fascinated by algorithms in college—I had already studied search and sorting algorithms in high school—but it wasn’t until I learned about trees and graphs that I became aware of the difference they can make and how much I liked these topics. It was the first time I had a feeling that writing code that worked was not the only goal, nor the main goal. How it works, how efficiently it runs, and how clean it is can be just as important, if not more so. (Unfortunately, I still had to wait a couple more years to have the same epiphany about testing.) Writing this book was a lot of work, far more than I anticipated four years ago when I first pitched the idea to an editor. The story of how it came to be published is quite funny (well, at least in retrospect!), but I won’t bother you with it here. Just know that while writing this book I went through four years, three jobs (and a half!), two countries, and five different apartments! It took a great (team) effort, for sure, but it was also rewarding. First and foremost, writing a book means starting a growth path, because it doesn’t matter how long you’ve worked on a topic and how well you think you know it. To write about any topic, you’ll be forced to question all you know about it, delve into details you might have over- looked when you previously applied it, and spend a lot of time researching, digesting, and processing the concepts until you are confident enough to explain them to some- one who doesn’t know anything about the subject. Usually a good test is getting some- one in your family who doesn’t work in that field and forcing them to listen to you while you unravel your lecture. Just make sure you choose someone very patient.
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay

Every 10 yuan is 1 year of VIP; the remainder counts as months (5 yuan is 5 months, 100 yuan is 10 years). Signed-in users are enabled immediately and both you and the admin get an email. Guests receive an ID and are sent to register.

← Back to List