by johnthuss · 4y ago · 0 comments
I would consider this an assumed skill for any developer with a college degree. It’s basically the point of the entire Data Structures class, which is a degree requirement.
For example:
1. When n is small, an array is almost always better. Arrays have very little overhead compared to even a hash map.
2. Algorithms with the same O() may still have significant differences at runtime and might be balanced differently between insert and search times. AVL trees take longer than Red Black trees to insert, but might be 1 level better in height. That means one less access. Useful for a routing table, for example.
So, in summary, if your looking at other people’s code and see lots of arrays don’t get too smug…n is usually small.
weirdly, in all my recent algorithm work, only the big-O has mattered (or it's all just NP-hard or even EXPTIME.)
Me: “why don’t you just use a hash table here? That array you’re iterating through each time has like 200,000 entries”
Him: “I can’t. I need to be able to get both the key and the value and hash tables don’t store the key”
Me: “…sigh, school has failed us again”
Now I'm wondering about something like:
MutableHashMap<MutableKey<T1>, Value<T2>>
You could probably have they key be a container object and allow changing its internal value, which would then communicate to the hash map that it belongs to, that it should do some internal changes: Entry<MutableKey<String>, Value<SomeEntity>> entry = mutableHashMap.getEntryByKey("myKey");
entry.setKey("myNewKey");
That logic could take an internal hash map, remove the element by the old key and add it with the new key. So, to an outside user it would seem like you can change the keys.The only problem would be that depending on the language you're using, you wouldn't change the objects directly, but would use those containers and it would essentially just be some boilerplate around a regular hash map. For example, Java has MutableInt and similar classes, which here would be hooked up to the MutableHashMap that they belong to.
Then again, I can't come up with many cases where something like that would be nice to have, since if you want to "change" a key, you can just do the following manually:
var ourValue = myHashMap.get("myKey");
myHashMap.remove("myKey");
myHashMap.put("myNewKey", ourValue);> Him: “I can’t. I need to be able to get both the key and the value and hash tables don’t store the key”
How could he do well in the data structures class? This is the definition of a hash map or hashed dictionary, so this is basic knowledge of data structures that is taught in this class and central to know to even have a chance of passing the exam.
In practice it's not the case, but very technically from a purely theoretical standpoint, I think he's right.
EDIT: untrue on any finite sized array, due to collisions. See below, and sorry for the brain fart!
Knowing the theory doesn't mean people apply it in practice.