I have a list of some arbitrary objects, for the purpose of the example assume they’re (integer, something-else) pairs, but they may be essentially anything:
[(5, a), (3, c), (2, f), (3, a), (4, c), (1, d), (5, b), (5, d)]
I want to group these objects based on one of their properties so that elements sharing the same value of said property are adjacent in the resulting list. For instance, the above list grouped by the integer values:
[(3, a), (3, c), (1, d), (4, c), (2, f), (5, b), (5, a), (5, d)]
As you see, no kind of order is necessary, nor is the operation required to be stable.
The naïve way would be to sort the list. This has the advantages of being well-known, well-tested and fast enough.
I’m being curious, though: is there an algorithm for this that doesn’t involve sorting, while being competitive in terms of complexity (O(n) time with O(n) space or O(n log n) time with O(1) space)?
Consider the problem of removing non-unique entries from an integer array. This problem can be solved by means of the solution to your problem (in linear time and constant space), so your problem cannot be solved simpler than that.
Unfortunately, I cannot find a good question with a good answer to this problem, but this one is definitely more general and well-known, I’m sure you’ll prove the best solution for that one.