6

This is the Daily Coding Problem:

“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.

The list is very long, so making more than one pass is prohibitively expensive.

Do this in constant space and in one pass.”

...

Here is my solution:

function removeKthFromEnd() {
    var previous = list.head;
    var kth = list.head;
    var end = list.head;
    for(var i = 0; i < k; i++){
        end = end.next;
    }
    while(end != null) {
        previous = kth;
        end = end.next;
        kth = kth.next;

    }
    previous.next = kth.next;
    kth = null;
}

I set kth, previous and end to the head of the list, traverse k items through the linked list so that space between kth and end = k, then increment kth and previous, waiting for end.next == null, at which point, kth will point to the kth from last element, and previous points to the one right before it. Then just stitch the list back by making previous.next = kth.next.

My question is:

Is this in Constant Space? Is it one pass?

Thanks.

TJWAM
  • 63
  • 5
  • What exactly is "Constant Space"? I've never heard of it before. – Blue Oct 21 '18 at 23:50
  • 5
    Yes, you're definitely doing it in one pass and not using any additional space. – slider Oct 22 '18 at 00:15
  • 2
    @FrankerZ It means that the *memory* (space) you use in your algorithm doesn't keep growing. – deceze Oct 22 '18 at 00:37
  • Good job. I suggest making your attempt an answer and garnering some upvotes so other people who come with the same question can see this correct answer. – Patrick87 Oct 22 '18 at 12:57

3 Answers3

1

Yes, there's only one loop traversing the list, so you're only making one pass. You allocate the same three variables no matter the size of the input, so you are also using constant space.

ubadub
  • 3,571
  • 21
  • 32
0

Python solution

class Node:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next


def kthLast(node, k):
    count = 0
    p0 = node
    current = node

    while current:
        count += 1
        if count > k:
            p0 = p0.next

        current = current.next

    return p0.val
Andrew L
  • 534
  • 1
  • 5
  • 9
0

Using std::forward_list:

using namespace std;

#include <forward_list>

void removeKthElementFromEnd(forward_list<int>& l, int k)
{
    forward_list<int>::iterator it, it_k;
    it_k = l.begin();
    for(it = l.begin(); it != l.end(); it++)
    {
        if (k < 0)
            it_k++;
        k--;
    }
    l.erase_after(it_k);
}

int main()
{
    forward_list<int> l;
    l.assign({ 1,2,3,4,5,6,7,8,9 });
    int k = 3;

    removeKthElementFromEnd(l, k);

    return 0;
}
RafaelJan
  • 3,118
  • 1
  • 28
  • 46