Page
1
(This page has no text content)
Page
2
(This page has no text content)
Page
3
Early Praise for A Common-Sense Guide to Data Structures and Algorithms, Second Edition If you—like me—got into coding without the benefit of a “traditional” computer science education, this book is a fantastic way to pick up the basics of how to think about algorithms, as well as how to use and implement a range of common data structures. All that, presented in plain language with a minimum of jargon, and a fun, pleasant tone! A great read for folks looking to pick up foundational programming knowledge. ➤ John Anderson VP, Technology, Infinity Interactive I’ve been coding for well over 30 years and one thing I’ve learned is to ALWAYS return to basics. A Common-Sense Guide to Data Structures and Algorithms has been a great way for me to re-assert all the assumptions I’ve made in the past, and re-cement my understanding of the core skills I’ll use in the future. Don’t buy this book if you think it’ll help you on whiteboarding tests. Those tests suck anyway. Buy this book to continue a path to real algorithmic thinking. Whether you’re early in your career or further along like me, you want a full toolbox of data structures and the common (and not so common) algorithms that complement them. Even better, you’ll learn how, when, and why to optimize your code. You’ll make it work, make it fast, then make it elegant—and learn the trade-offs along the way. ➤ Scott Hanselman Microsoft Programmer, Professor, Blogger, Podcast
Page
4
Despite being a software professional for fifteen years, I’ve learnt a great deal from this updated edition. This is also the book I wish I’d had twenty years ago, when learning these concepts as an undergraduate. It’s like I have a new superpower tuning me in to the opportunities hash tables can provide to improve the Big O of code. Forget what it looks like, forget what it feels like, forget what you think it is, forget what habits you’ve accumulated: forget all that stuff; it won’t give you the most efficient Big O! ➤ Nigel Lowry Principal Consultant, Lemmata The second edition of this book includes many worthy additions to an already excellent resource for learning data structures and algorithms. Additional common- sense explanations of topics like dynamic programming, and questions to check your understanding at the end of each chapter, make this book invaluable to developers with or without a computer science background. ➤ Jason Pike Senior Software Engineer, KEYSYS Consulting The perfect introduction to algorithms and structures for beginners. Highly recommended! ➤ Brian Schau Lead Developer, Schau Consulting
Page
5
A Common-Sense Guide to Data Structures and Algorithms, Second Edition Level Up Your Core Programming Skills Jay Wengrow The Pragmatic Bookshelf Raleigh, North Carolina
Page
6
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade- marks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. Our Pragmatic books, screencasts, and audio books can help you and your team create better software and have more fun. Visit us at https://pragprog.com. The team that produced this book includes: Publisher: Andy Hunt VP of Operations: Janet Furlow Executive Editor: Dave Rankin Development Editor: Brian MacDonald Copy Editor: Katharine Dvorak Indexing: Potomac Indexing, LLC Layout: Gilson Graphics For sales, volume licensing, and support, please contact support@pragprog.com. For international rights, please contact rights@pragprog.com. Copyright © 2020 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. ISBN-13: 978-1-68050-722-5 Encoded using the finest acid-free high-entropy binary digits. Book version: P1.0—August 2020
Page
7
Contents Preface . . . . . . . . . . . . . . xiii 1. Why Data Structures Matter . . . . . . . . . 1 Data Structures 2 The Array: The Foundational Data Structure 3 Measuring Speed 4 Reading 5 Searching 8 Insertion 11 Deletion 13 Sets: How a Single Rule Can Affect Efficiency 15 Wrapping Up 18 Exercises 19 2. Why Algorithms Matter . . . . . . . . . . 21 Ordered Arrays 22 Searching an Ordered Array 24 Binary Search 26 Binary Search vs. Linear Search 31 Wrapping Up 34 Exercises 34 3. O Yes! Big O Notation . . . . . . . . . . 35 Big O: How Many Steps Relative to N Elements? 36 The Soul of Big O 37 An Algorithm of the Third Kind 40 Logarithms 41 O(log N) Explained 42 Practical Examples 43
Page
8
Wrapping Up 45 Exercises 45 4. Speeding Up Your Code with Big O . . . . . . . 47 Bubble Sort 47 Bubble Sort in Action 48 The Efficiency of Bubble Sort 53 A Quadratic Problem 56 A Linear Solution 58 Wrapping Up 60 Exercises 60 5. Optimizing Code with and Without Big O . . . . . . 63 Selection Sort 63 Selection Sort in Action 64 The Efficiency of Selection Sort 70 Ignoring Constants 71 Big O Categories 72 Wrapping Up 76 Exercises 76 6. Optimizing for Optimistic Scenarios . . . . . . . 79 Insertion Sort 79 Insertion Sort in Action 80 The Efficiency of Insertion Sort 86 The Average Case 88 A Practical Example 91 Wrapping Up 93 Exercises 93 7. Big O in Everyday Code . . . . . . . . . . 95 Mean Average of Even Numbers 95 Word Builder 97 Array Sample 99 Average Celsius Reading 100 Clothing Labels 101 Count the Ones 102 Palindrome Checker 102 Get All the Products 103 Password Cracker 107 Contents • vi
Page
9
Wrapping Up 109 Exercises 109 8. Blazing Fast Lookup with Hash Tables . . . . . . 113 Hash Tables 113 Hashing with Hash Functions 114 Building a Thesaurus for Fun and Profit, but Mainly Profit 115 Hash Table Lookups 117 Dealing with Collisions 119 Making an Efficient Hash Table 122 Hash Tables for Organization 124 Hash Tables for Speed 125 Wrapping Up 130 Exercises 131 9. Crafting Elegant Code with Stacks and Queues . . . . 133 Stacks 133 Abstract Data Types 136 Stacks in Action 137 The Importance of Constrained Data Structures 143 Queues 144 Queues in Action 146 Wrapping Up 147 Exercises 148 10. Recursively Recurse with Recursion . . . . . . 149 Recurse Instead of Loop 149 The Base Case 151 Reading Recursive Code 151 Recursion in the Eyes of the Computer 154 Filesystem Traversal 156 Wrapping Up 159 Exercises 159 11. Learning to Write in Recursive . . . . . . . . 161 Recursive Category: Repeatedly Execute 161 Recursive Category: Calculations 166 Top-Down Recursion: A New Way of Thinking 168 The Staircase Problem 173 Anagram Generation 177 Contents • vii
Page
10
Wrapping Up 181 Exercises 181 12. Dynamic Programming . . . . . . . . . . 183 Unnecessary Recursive Calls 183 The Little Fix for Big O 187 The Efficiency of Recursion 188 Overlapping Subproblems 189 Dynamic Programming through Memoization 191 Dynamic Programming through Going Bottom-Up 194 Wrapping Up 196 Exercises 197 13. Recursive Algorithms for Speed . . . . . . . 199 Partitioning 199 Quicksort 205 The Efficiency of Quicksort 211 Quicksort in the Worst-Case Scenario 216 Quickselect 218 Sorting as a Key to Other Algorithms 222 Wrapping Up 223 Exercises 224 14. Node-Based Data Structures . . . . . . . . 225 Linked Lists 225 Implementing a Linked List 227 Reading 229 Searching 231 Insertion 232 Deletion 236 Efficiency of Linked List Operations 238 Linked Lists in Action 239 Doubly Linked Lists 240 Queues as Doubly Linked Lists 242 Wrapping Up 244 Exercises 244 15. Speeding Up All the Things with Binary Search Trees . . 247 Trees 248 Binary Search Trees 250 Searching 251 Contents • viii
Page
11
Insertion 256 Deletion 260 Binary Search Trees in Action 271 Binary Search Tree Traversal 272 Wrapping Up 276 Exercises 276 16. Keeping Your Priorities Straight with Heaps . . . . 279 Priority Queues 279 Heaps 281 Heap Properties 284 Heap Insertion 285 Looking for the Last Node 287 Heap Deletion 288 Heaps vs. Ordered Arrays 292 The Problem of the Last Node…Again 293 Arrays as Heaps 295 Heaps as Priority Queues 302 Wrapping Up 302 Exercises 303 17. It Doesn’t Hurt to Trie . . . . . . . . . . 305 Tries 306 Storing Words 307 Trie Search 311 The Efficiency of Trie Search 315 Trie Insertion 316 Building Autocomplete 320 Completing Autocomplete 326 Tries with Values: A Better Autocomplete 327 Wrapping Up 328 Exercises 329 18. Connecting Everything with Graphs . . . . . . 331 Graphs 332 Directed Graphs 334 Object-Oriented Graph Implementation 334 Graph Search 337 Depth-First Search 339 Breadth-First Search 348 The Efficiency of Graph Search 361 Contents • ix
Page
12
Weighted Graphs 364 Dijkstra’s Algorithm 367 Wrapping Up 384 Exercises 384 19. Dealing with Space Constraints . . . . . . . . 387 Big O of Space Complexity 387 Trade-Offs Between Time and Space 390 The Hidden Cost of Recursion 393 Wrapping Up 395 Exercises 395 20. Techniques for Code Optimization . . . . . . . 397 Prerequisite: Determine Your Current Big O 397 Start Here: The Best-Imaginable Big O 397 Magical Lookups 399 Recognizing Patterns 406 Greedy Algorithms 414 Change the Data Structure 427 Wrapping Up 433 Parting Thoughts 433 Exercises 434 A1. Exercise Solutions . . . . . . . . . . . 439 Chapter 1 439 Chapter 2 440 Chapter 3 440 Chapter 4 441 Chapter 5 442 Chapter 6 442 Chapter 7 443 Chapter 8 444 Chapter 9 446 Chapter 10 447 Chapter 11 448 Chapter 12 450 Chapter 13 451 Chapter 14 453 Chapter 15 456 Chapter 16 458 Chapter 17 459 Contents • x
Page
13
Chapter 18 461 Chapter 19 464 Chapter 20 465 Index . . . . . . . . . . . . . . 475 Contents • xi
Page
14
Preface Data structures and algorithms are more than abstract concepts. Mastering them enables you to write code that is efficient, leading to software that runs faster and consumes less memory. This is a big deal for today’s software applications, which exist on increasingly mobile platforms and handle increasingly greater amounts of data. The problem with most resources on these subjects, though, is that they are...well...obtuse. Most texts go heavy on the math jargon, and if you are not a mathematician, it can be difficult to grasp what on Earth is going on. Even books that claim to make algorithms “easy” seem to assume that the reader has an advanced math degree. Because of this, too many people shy away from these concepts, feeling that they are not “smart” enough to understand them. The truth, though, is that everything about data structures and algorithms boils down to common sense. Mathematical notation itself is simply a particular language, and everything in math can also be explained with common-sense terminology. In this book, I use that common-sense language (plus a lot of diagrams!) to explain these concepts in simple, and dare I say, enjoyable ways. Once you understand these concepts, you will be equipped to write code that is efficient, fast, and elegant. You will be able to weigh the pros and cons of various code alternatives, and be able to make educated decisions as to which code is best for the given situation. In this book, I go out of my way to make these concepts real and practical with ideas that you can make use of today. Sure, you’ll learn some really cool computer science along the way. But this book is about taking that seemingly abstract stuff and making it directly practical. You’ll be writing better code and faster software by the time you’re done reading this book. report erratum • discuss
Page
15
Who Is This Book For? This book is ideal for several audiences: • You are a computer science student who wants a text that explains data structures and algorithms in plain English. This book can serve as a supplement to whatever “classic” textbook you happen to be using. • You are a beginning developer who knows basic programming, but wants to learn the fundamentals of computer science to write better code and increase your programming knowledge and skills. • You are a self-taught developer who has never studied formal computer science (or a developer who did but forgot everything!) and wants to leverage the power of data structures and algorithms to write more scalable and elegant code. Whoever you may be, I tried to write this book so it can be accessed and enjoyed by people of all skill levels. What’s New in the Second Edition Why a second edition? In the few years since the original edition was pub- lished, I’ve had the opportunity to teach these topics to various audiences. Over time, I continued to refine my explanations as well as discover additional topics that I thought were exciting and important. There was also quite a bit of demand for hands-on exercises that would help people gain practice with these concepts. Accordingly, the second edition has the following new features: 1. Revised material. I’ve made significant revisions to the original chapters for the sake of clarity. While I thought that the first edition did a pretty good job in making these complex topics easy to understand, I found that there was room to make certain areas even clearer. Many sections of the original chapters have been entirely rewritten, and I’ve added brand-new sections as well. I feel that these revisions alone have enhanced the book to make it worthy of a new edition. 2. New chapters and topics. The second edition contains six new chapters that cover topics I’m particularly excited about. The book has always blended practice with theory, but I added even more material that you can take straight to the bank. The chapters Big O in Everyday Code and Techniques for Code Optimization focus exclusively Preface • xiv report erratum • discuss
Page
16
on day-to-day code, and how knowledge of data structures and algorithms can help you write more efficient software. I went all out when it came to recursion. While the previous edition con- tained a chapter on this topic, I devoted an entirely new chapter, Learning to Write in Recursive, to teach you how to write recursive code, which can be confusing for beginners. I haven’t seen this explained anywhere else, and I think it’s a unique and valuable addition. I also added the chapter, Dynamic Programming, which is a popular subject, and one critical to making recursive code more efficient. There are many data structures out there, and it’s difficult to select which to include and which to leave out. However, there’s been increased demand to learn about heaps and tries, and I’ve found them to be fascinating as well. Hence the chapters, Keeping Your Priorities Straight with Heaps and It Doesn't Hurt to Trie. 3. Exercises and solutions. Each chapter now has a number of exercises that allow you to gain hands-on practice with each topic within the book. I also added detailed solutions, which are available in an appendix at the back of the book. This is a significant enhancement that transforms the book into a more complete learning experience. What’s in This Book? As you may have guessed, this book talks quite a bit about data structures and algorithms. More specifically, the book is laid out as follows: In Why Data Structures Matter and Why Algorithms Matter, I explain what data structures and algorithms are and explore the concept of time complex- ity—which is used to determine how fast an algorithm is. In the process, I also talk a great deal about arrays, sets, and binary search. In O Yes! Big O Notation, I unveil Big O Notation and explain it in terms that are easy to understand. We use this notation throughout the book, so this chapter is pretty important. In Speeding Up Your Code with Big O, Optimizing Code with and Without Big O, and Optimizing for Optimistic Scenarios, we delve further into Big O Notation and use it to make our day-to-day code faster. Along the way, I cover various sorting algorithms, including Bubble Sort, Selection Sort, and Insertion Sort. In Big O in Everyday Code, you apply all that you learned about Big O Notation and analyze the efficiency of code from the real world. report erratum • discuss What’s in This Book? • xv
Page
17
In Blazing Fast Lookup with Hash Tables and Crafting Elegant Code, I discuss a few additional data structures, including hash tables, stacks, and queues. I show how they impact the speed and elegance of our code and how we can use them to solve real-world problems. Recursively Recurse with Recursion introduces recursion, an anchor concept in the world of computer science. We break it down in this chapter and see how it can be a great tool for certain situations. Learning to Write in Recursive teaches you how to write recursive code, which can otherwise be quite confusing. Dynamic Programming shows you how to optimize recursive code and prevent it from spiraling out of control. And Recursive Algorithms for Speed shows you how to use recursion as the foundation for turbo-fast algorithms like Quicksort and Quickselect, and takes your algorithm-development skills up a few notches. The following chapters, Node-Based Data Structures, Speeding Up All the Things, Keeping Your Priorities Straight with Heaps, It Doesn't Hurt to Trie, and Connecting Everything with Graphs, explore node-based data structures including the linked list, the binary tree, the heap, the trie, and the graph, and show how each is ideal for various applications. Dealing with Space Constraints explores space complexity, which is important when programming for devices with relatively small amounts of disk space, or when dealing with big data. The final chapter, Techniques for Code Optimization, walks you through various practical techniques for optimizing the efficiency of code, and gives you new ideas for improving the code you write every day. How to Read This Book You’ve got to read this book in order. There are books out there where you can read each chapter independently and skip around a bit, but this isn’t one of them. Each chapter assumes you’ve read the previous ones, and the book is carefully constructed so you can ramp up your understanding as you proceed. That being said, there are certain chapters in the latter half of the book that don’t depend entirely on each other. The diagram on page xvii depicts which chapters are prerequisites for other chapters. For example, you could technically skip from Chapter 10 to Chapter 13 if you wanted to. (Oh! And this diagram is based on a data structure called a tree. You’re going to learn about it in Chapter 15.) Preface • xvi report erratum • discuss
Page
18
Another important note: to make this book easy to understand, I don’t always reveal everything about a particular concept when I first introduce it. Some- times, the best way to break down a complex concept is to reveal a small piece of it, and only reveal the next piece when the first piece has sunken in. If I report erratum • discuss How to Read This Book • xvii
Page
19
define a particular term as such-and-such, don’t take that as the textbook definition until you’ve completed the entire section on that topic. It’s a trade-off: to make the book digestible, I’ve chosen to oversimplify certain concepts at first and clarify them over time, rather than ensure that every sentence is completely, academically, accurate. But don’t worry too much, because by the end, you’ll see the entire accurate picture. Code Examples The concepts in this book aren’t specific to one particular programming lan- guage. Because of this, I chose to use a variety of languages to demo the examples in this book. The examples are written in Ruby, Python, and Java- Script, so having a basic understanding of these languages would be helpful. That being said, I’ve tried to write the examples in such a way that even if you’re not familiar with the language of a given example, you should be able to follow along. To help with this, I don’t always follow the popular idioms for each language where I feel that an idiom may confuse someone new to that particular language. I understand that having the book switch languages frequently can come with a certain mental switching cost. However, I felt that it was important to keep the book language-agnostic. And again, I’ve tried to keep the code in all lan- guages easy to read and straightforward. There are some longer code snippets under the headings that read “Code Implementation.” I certainly encourage you to study these code samples, but you don’t necessarily have to understand every last line in order to proceed to the next section of the book. If these long pieces of code are bogging you down, just skip (or skim) them for now. Finally, it’s important to note that not every code snippet is “production ready.” My greatest focus has been to clarify the concept at hand, and while I did also try to make the code generally complete, I may not have accounted for every edge case. There’s certainly room for you to optimize the code further—so feel free to go crazy with that! Online Resources This book has its own web page1 on which you can find more information about the book and help improve it by reporting errata, including content suggestions and typos. 1. https://pragprog.com/titles/jwdsal2 Preface • xviii report erratum • discuss
Page
20
Acknowledgments While the task of writing a book may seem like a solitary one, this book simply could not have happened without the many people who have supported me in my journey writing it. I’d like to personally thank all of you. To my wonderful wife, Rena—thank you for the time and emotional support you’ve given to me. You took care of everything while I hunkered down like a recluse and wrote. To my adorable kids, Tuvi, Leah, Shaya, and Rami— thank you for your patience as I wrote my book on “algorizms.” And yes—it’s finally done. To my parents, Mr. and Mrs. Howard and Debbie Wengrow—thank you for initially sparking my interest in computer programming and helping me pursue it. Little did you know that getting me a computer tutor for my ninth birthday would set the foundation for my career—and now this book. To my wife’s parents, Mr. and Mrs. Paul and Kreindel Pinkus—thank you for your continued support of my family and me. Your wisdom and warmth mean so much to me. When I first submitted my manuscript to the Pragmatic Bookshelf, I thought it was good. However, through the expertise, suggestions, and demands of all the wonderful people who work there, the book has become something much, much better than I could have written on my own. To my editor, Brian MacDonald— you’ve shown me how a book should be written, and your insights have sharp- ened each chapter; this book has your imprint all over it. To the original man- aging editor, Susannah Pfalzer and executive editor, Dave Rankin—you’ve given me the vision for what this book could be, taking my theory-based manuscript and transforming it into a book that can be applied to the everyday programmer. To the publishers, Andy Hunt and Dave Thomas—thank you for believing in this book and making the Pragmatic Bookshelf the most wonderful publishing company to write for. To the extremely talented software developer and artist, Colleen McGuckin— thank you for taking my chicken scratch and transforming it into beautiful digital imagery. This book would be nothing without the spectacular visuals that you’ve created with such skill and attention to detail. I’ve been fortunate that so many experts have reviewed this book. Your feed- back has been extremely helpful and has made sure that this book can be as accurate as possible. I’d like to thank all of you for your contributions. report erratum • discuss Acknowledgments • xix