I have written this algorithm here and I am trying to evaluate its time and space complexity in terms of Big-O notation. The algorithm determines if two given strings are anagrams.
def anagram(str1, str2)
str1.each_char do |char|
selected_index = str2.index(char)
return false if !selected_index #to handle nil index
str2.slice!(selected_index)
end
str2.empty?
end
The time complexity of this function is O(n^2)
, and the space complexity is O(1)
? I believe I may be mistaken for the space complexity (could be O(n)
) because the selected_index
variable is repeatedly re-assigned which takes up memory relative to how long the each_char
loop runs for.
If someone could please throw some guidance that would be great :)