6 ms·
Hey Usama. Nice walkthrough for the uninitiated. It may be worth discussing the pros and cons of this implementation, however. The algorithm you have described
by jmts 9y ago
Hey Usama. Nice walkthrough for the uninitiated. It may be worth discussing the pros and cons of this implementation, however.
The algorithm you have described runs in O(n^2), or quadratic time. This means that if your array has length n, you perform n actions for every item in the array. This is fine for small arrays (9 actions for 3 items), but becomes problematic for larger arrays (100,000,000 actions for 10,000 items).
Compare that with the algorithm described in the first article you've mentioned [1]. This uses a map/hash/dictionary to store information about each unique item in the array and retrieve it (typically) in constant O(1) time instead of needing the inside loop to count matching items again. As a result, it is only necessary to perform one action for each item in the array, achieving O(n), or linear time. Now we perform 3 actions for an array of length 3, and 10,000 actions for an array of length 10,000 (10,000x times faster!).
Of course, this depends on how long each 'action' takes. For example, if we simplify the algorithm in your article, we might just be incrementing a variable. Consider that to be 1 time unit. The algorithm in [1] may need to perform some kind of hash on the array object taking 10 time units before also incrementing a variable, so each action in [1] might be considered to take 11 time units. For small arrays this might actually take more time. An array length of 3 gives 3 time units for your algorithm, and 33 for the algorithm in [1]. Once the array is large enough however, the algorithm in [1] will be superior, taking only 110,000 time units (10,000 * 11) for an array of length 10,000 compared to the 100,000,000 units for the algorithm in your article.
[1] http://stackoverflow.com/questions/1053843/get-the-element-with-the-highest-occurrence-in-an-array http://stackoverflow.com/questions/1053843/get-the-element-w...