Hi I've been thinking of how to implement this for days.
I'm trying to implement a programme that reads a dictionary into a list and sorts it in O(N) time.After that, I have to search for the anagrams in the list given an input from the user in O(log N) time.I can sort each word by letter and sort the list alphabetically in O(N).
Since I'm trying to search in O(logN) time, I tried to use binary search by sorting every letter in each word and using that as a key to identify the anagrams. For example 'act' is the key for anagram group 'act,'cat','tac'.
arr=['act','cat','tac','bad','fad']
After sorting
[['act', 'act'], ['cat', 'act'], ['tac', 'act'], ['bad', 'abd'], ['fad', 'adf']]
But binary search only finds ONE target so it will only return 'tac' for anagram group under 'act'.My binary search code:
def binarySearch(arr, lower, upper, target):
anagramList=[]
if upper >= lower:
mid = lower + ((upper - lower) // 2)
if areAnagrams(arr[mid][1],target):
anagramList.append(arr[mid])
elif arr[mid] > target:
return binarySearch(arr, lower, mid - 1, target)
else:
return binarySearch(arr, mid + 1, upper, target)
return anagramList
I tried to group them like this
[['act','act','cat','tac'],['bad','abd'],['fad','daf]]
but it takes O(N^2) complexity which is larger than O(N)?Can anyone suggest how I should go about this?Thanks.
Edit: For example, if the query string is alppe, the output will consist of the words appel, and apple.