# Why my python code is Time Limit exceed?

``````    if head ==None:
return None
return None;
preNode = ListNode(-1)
currentNode = ListNode(-1)
while currentNode != None:
if currentNode.val == val:
preNode = currentNode.next
else:
preNode = currentNode
currentNode = currentNode.next

• Check the line
current = currentNode.next

See if it is working for both if and else conditions. This is the most possible place where things can go wrong here to give you TLE.

• Last executed input: [1,1], 1
TLE for [1,1] , 1 Can you help me dear?

• Your currentNode does not reach the end of the list.

Let's call it [1a,1b],1 (a and b to distinguish the first and second 1 in the list)

Before while loop:

preNode = 1a
currentNode = 1a

if condition satisfied because currentNode,1a == 1

After first iteration of while:

preNode = 1b
currentNode = 1a <----- This is your error (if my python syntax is not rusty, haven't been on python for a while.. but check this out)

if condition satisfied because currentNode,1a == 1

After second iteration of while:

preNode = 1b
currentNode = 1a

• You can try understanding the flow from my code.

Notice that you cannot return the old head because it will give you a wrong result if you were supposed to remove the head node.

Here's my accepted solution in Python. Analyze the flow, draw a linked list on paper and iterate through each statement in the while loop, and mark pointer positions after every iteration and see how it works.

This technique would help you solve many of the linked list problems. Feel free to reach out to me by replying to this post if you have further questions.

``````    if head == None:
return None;
p = None;
nH = None;
while c != None:
if c.val != val:
if nH == None:
nH = c;
else:
p.next = c;
p = c;
c = c.next;
if p != None:
p.next = None;
return nH``````

• 3Q very much my friend!

• 3Q u are hot mind, Thank u very much

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.