I've written a function that takes a string as an input and hands over a dictionary that indicates the most occurring elements/characters.
Part 1 - Just finding the most occurring character
def mostoccur(arr):
n = len(arr)
dict={}
# filling the dictionary with itesm and their frequency using dict.get()
for i in range(n):
dict[arr[i]] = dict.get(arr[i],0) + 1
return dict
string = "aabbccdddddddd"
# turning the string into a list, so it's iterable
ls = list(string)
ans = mostoccur(ls)
print("The dictionary of all the characters and their frequency: \n",ans)
maximum = max(ans)
print("\nThe most occuring character is:",maximum)
But then I got more curious, and I wanted to print the most occurring and second most occurring element in the dictionary. Thus, I've written something like this:
Part 2 - Alright, now let's find the second most occurring character
# defining a dictionary to store the most and second most occurring element
biggest = {'most-occuring':0, 'second-most-occuring':0}
# nested loops to go through all values in the dictionary
for a in ans.items(): # O(N)
for b in ans.items(): # O(N)
if a < b:
a,b = b,a
biggest['most-occuring'] = a
biggest['second-most-occuring']= b
# Total = O(N^2)
print(biggest)
Big O
I've written the Big O of each operation next to it, and when I look at it, I really don't like what I've written. I mean, O(N^2) sounds too expensive and inefficient.
Would you be willing to illuminate me on better ways of writing this?
Please bear in mind that I'm not looking for a method that utilizes any libraries.