I'm trying to solve this kata Find the K-th last element of a singly linked list:
Write a function that given the head of singly linked list, and an index (0 based) counted from the end of the list, returns the element corresponding to that index.
The function must return a falsy value for invalid input values, like an out of range index.
So for the list
66 -> 42 -> 13 -> 666, getKthLastElement() with index 2 should return the Node (predefined object for list nodes) corresponding to 42.
I don't understand why I get undefined instead of number in my return. I tried this code in a codepen, and everything worked fine, and the result is number, but in CodeWars it's undefined.
function getKthLastElement(head, k) {
let arr = [];
while(head){
arr.push(head.data);
head = head.next
}
if(k == 0) k = 1
let result = arr.splice(-k, 1)
return +result
}
When you read the code challenge, you see it asks to return the kth element, the Node instance, not the value.
So you shouldn't collect head.data, but head. And not return +result, but result[0].
Another issue is that you treat k as 1 when it has value 0, but this is not what it says in the description. A value of 0 has a different meaning than a value of 1. Instead you should always increase k with 1.
Then there is the requirement to return a falsy value when the value of k is out of range. You did not provide code for that case.
So here is the corrected code:
function getKthLastElement(head, k) {
let arr = [];
while(head){
arr.push(head); // Collect the node, not the value
head = head.next;
}
if (k < 0 || k >= arr.length) return; // Out of range
let result = arr.splice(-(k+1), 1); // Always add 1 to k
return result[0]; // Return the node.
}
This works, but it is not memory efficient. By turning the whole list into an array, you allocated O(n) auxiliary memory. You should try to do it without such an array.
Here is a spoiler which I hope you don't need:
function getKthLastElement(head, k) { let lead = head; let lag = head; if (k < 0) return; // k is out of range for (let i = 0; i <= k; i++) { if (!lead) return; // k is out of range lead = lead.next; } while(lead) { lead = lead.next; lag = lag.next; } return lag; }