Skip to Content
A Common-Sense Guide to Data Structures and Algorithms
book

A Common-Sense Guide to Data Structures and Algorithms

by Jay Wengrow
August 2017
Intermediate to advanced
222 pages
5h 3m
English
Pragmatic Bookshelf
Content preview from A Common-Sense Guide to Data Structures and Algorithms

A Linear Solution

Below is another implementation of the hasDuplicateValue function that doesn’t rely upon nested loops. Let’s analyze it and see if it’s any more efficient than our first implementation.

 function​ hasDuplicateValue(array) {
 var​ existingNumbers = [];
 for​(​var​ i = 0; i < array.length; i++) {
 if​(existingNumbers[array[i]] === ​undefined​) {
  existingNumbers[array[i]] = 1;
  } ​else​ {
 return​ ​true​;
  }
  }
 return​ ​false​;
 }

This implementation uses a single loop, and keeps track of which numbers it has already encountered using an array called existingNumbers. It uses this array in an interesting way: every time the code encounters a new number, it stores the value 1 inside the index of the existingNumbers ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition

A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition

Jay Wengrow

Publisher Resources

ISBN: 9781680502794Errata Page