Each sort algorithm will be the job, but it’s a OVERKILL.
For input like:
aa
cc
aa
bb
dd
bb
cc
I just need something like:
aa
aa
cc
cc
bb
bb
dd
The order of each pattern is not required.
Is there such an algorithm for this kind of job?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You simply want to use a hashtable here, or more abstractly an associative array. Iterate over the input, adding it to the hashtable with value (tag, if you prefer) of 1 if it hasn’t yet been seen, or incrementing the count by one if it already exists in the hashtable.
The algorithm is thus O(n) in both time and space, which is as good as you could reasonably expect. I recommend some reading up on hashtables, as it is a highly useful data structure that appears in all sorts of places in algorithm and software design.