Trade-Offs Between Time and Space
Here’s a function that accepts an array and returns whether it contains any duplicate values (you may recognize this function from Chapter 4, Speeding Up Your Code with Big O):
| function hasDuplicateValue(array) { |
| for(let i = 0; i < array.length; i++) { |
| for(let j = 0; j < array.length; j++) { |
| if(i !== j && array[i] === array[j]) { |
| return true; |
| } |
| } |
| } |
| return false; |
| } |
This algorithm uses nested loops and has a time complexity of O(N2). We’ll call this implementation Version #1.
Here’s a second implementation, Version #2, that employs a hash table and just a single loop:
| function hasDuplicateValue(array) { |
| let existingValues = {}; |
| for(let i = 0; i < array.length; ... |
Get A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.