How can I optimize this Python code for Codewars?
Question:
The task in CodeWars is:
You are given a node that is the beginning of a linked list. This list
contains a dangling piece and a loop. Your objective is to determine
the length of the loop.
The Codewars compiler throws the error "Execution Timed Out (12000 ms)", although the code works as intended. As I got it, some function or method that I use are too slow, or I should choose different algorithm in my code?
My code:
def loop_size(node):
#An array where I save all the elements not previously encountered
arr = []
currentElement = node
i = 0
#I check if I haven't met same element before
while currentElement not in arr:
arr.append(currentElement)
currentElement = currentElement.next
i += 1
#Here I count the size of loop
loopLength = i - arr.index(currentElement)
return loopLength
Answers:
This algorithm is better then prevous, because in the end, when we looking for element’s index, it’s faster to get it by using dictionary, because dictionary is a hash map, that search any item for time O(1). So all the problem in my previous solution, was the using arr.index(currentElement)
, and this method is really time-consuming.
def loop_size(node):
myDict = dict()
currentElement = node
i = 0
while currentElement not in myDict:
myDict[currentElement] = i
currentElement = currentElement.next
i += 1
loopSize = i - myDict.get(currentElement)
return loopSize
The task in CodeWars is:
You are given a node that is the beginning of a linked list. This list
contains a dangling piece and a loop. Your objective is to determine
the length of the loop.
The Codewars compiler throws the error "Execution Timed Out (12000 ms)", although the code works as intended. As I got it, some function or method that I use are too slow, or I should choose different algorithm in my code?
My code:
def loop_size(node):
#An array where I save all the elements not previously encountered
arr = []
currentElement = node
i = 0
#I check if I haven't met same element before
while currentElement not in arr:
arr.append(currentElement)
currentElement = currentElement.next
i += 1
#Here I count the size of loop
loopLength = i - arr.index(currentElement)
return loopLength
This algorithm is better then prevous, because in the end, when we looking for element’s index, it’s faster to get it by using dictionary, because dictionary is a hash map, that search any item for time O(1). So all the problem in my previous solution, was the using arr.index(currentElement)
, and this method is really time-consuming.
def loop_size(node):
myDict = dict()
currentElement = node
i = 0
while currentElement not in myDict:
myDict[currentElement] = i
currentElement = currentElement.next
i += 1
loopSize = i - myDict.get(currentElement)
return loopSize