0% completed
Why not just recurse through with a hashmap? Is space complexity that important?
Douglas McDonald
Jul 4, 2024
I understand how a two-pointer solution to this would work, but I don't understand why it's considered optimal over a hashmap recursion approach. Here's my understanding:
HASHMAP:
Create an empty hashmap. Call a function to check next happy number. If result == 1, return true. Else if result exists in hashmap, return false. Else, push result to hashmap and recurse with result.
Ultimately, this should loop through every "node" in the "linked list" exactly once and the hashmap will contain every unique "node" in the linked list. Therefore, where n = # of "nodes", Time complexity = O(n), space complexity = O(n)
TWO-POINTER:
Create two "pointers" and assign initial value for both While they don't equal each other and fastpointer doesn't equal 1, call a function to check next happy number once on slowpointer and twice on fastpointer. If they equal each other, return false. Else if fastpointer equals 1, return true.
This might take less than n "loops" but this will still run the function for 'check next happy number' at least n times for fastpointer + n/2 times for the slow pointer in the best case scenario (happy number found OR loop is immediately caught as soon as fastpointer enters it).
While time complexity of 1.5n calls is still O(n), surely this is less efficient timewise than the hashmap approach which is guaranteed to be exactly n calls? From what I can tell, the main benefit of this approach is that the space complexity is 0. How do you balance time complexity against space complexity in these cases?
0
0
Comments
lejafilip a year ago
I also thought about hashmap solution but it has O(n) space complexity, which can be problematic.
On this page