|
| 1 | +Daily Coding Problem #26 |
| 2 | +Problem |
| 3 | +This problem was asked by Google. |
| 4 | + |
| 5 | +Given a singly linked list and an integer k, remove the kth last element from the list. k is guaranteed to be smaller than the length of the list. |
| 6 | + |
| 7 | +The list is very long, so making more than one pass is prohibitively expensive. |
| 8 | + |
| 9 | +Do this in constant space and in one pass. |
| 10 | + |
| 11 | +Solution |
| 12 | +If we didn't have the constraint of needing only to make one pass, this problem would be trivial to implement. We could simply iterate over the whole list to find out the total length N of the list, and then restart from the beginning and iterate N - k steps and remove the node there. That would take constant space as well. |
| 13 | + |
| 14 | +However, given that we have the constraint of needing to make only one pass, we have to find some way of getting the N - kth node in the list in one shot. |
| 15 | + |
| 16 | +What we can do, then, is this: |
| 17 | + |
| 18 | +Set up two pointers at the head of the list (let's call them fast and slow) |
| 19 | +Move fast up by k |
| 20 | +Move both fast and slow together until fast reaches the end of the list |
| 21 | +Now slow is at the N - kth node, remove it |
| 22 | +That only makes one pass and is constant time. The code should look something like this: |
| 23 | + |
| 24 | +class Node: |
| 25 | + def __init__(self, val, next=None): |
| 26 | + self.val = val |
| 27 | + self.next = next |
| 28 | + |
| 29 | + def __str__(self): |
| 30 | + current_node = self |
| 31 | + result = [] |
| 32 | + while current_node: |
| 33 | + result.append(current_node.val) |
| 34 | + current_node = current_node.next |
| 35 | + return str(result) |
| 36 | + |
| 37 | +def remove_kth_from_linked_list(head, k): |
| 38 | + slow, fast = head, head |
| 39 | + for i in range(k): |
| 40 | + fast = fast.next |
| 41 | + |
| 42 | + prev = None |
| 43 | + while fast: |
| 44 | + prev = slow |
| 45 | + slow = slow.next |
| 46 | + fast = fast.next |
| 47 | + |
| 48 | + prev.next = slow.next |
| 49 | + |
| 50 | +head = Node(1, Node(2, Node(3, Node(4, Node(5))))) |
| 51 | +print(head) |
| 52 | +remove_kth_from_linked_list(head, 3) |
| 53 | +print(head) |
0 commit comments