Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using values as keys in arrays to reduce complexity when searching for items

Tags:

arrays

php

Here is sometime I do a lot in PHP. Searching for a needle in a haystack.

$names = [
    'Mike',
    'John',
    'Dave',
    'Tony'
];

$gotDave = in_array('Dave', $names);

The runtime of in_array is O(n) where n is the number of elements.

I often setup my lookup data structure to look like this.

$names = [
    'Mike' => true,
    'John' => true,
    'Dave' => true,
    'Tony' => true
];

$gotDave = isset($names['Dave']);

The runtime is O(1) because in php the associative array is a hashmap.

Some questions:

  • should I do this? is this good practice?
  • is there a better value for the right hand ride
like image 920
Yada Avatar asked Jun 15 '15 13:06

Yada


1 Answers

Yes, that's a great solution. In fact, that is how Sets are implemented in the core libraries of most programming languages - Off the top of my head, Python, Ruby, and Java do them this way. The Go language doesn't provide a Set, and just tells you to do what you've done.

I can't think of any reason to use any value other than true ```true``. It just makes sense.

like image 118
Daniel Von Fange Avatar answered Oct 20 '22 00:10

Daniel Von Fange