Given a Linked List and a number k, find the value at the kth node from the end of the Linked List. If there is no Nth node from the end, print -1.
Examples:
Input: head=1 -> 2 -> 3 -> 4, k= 3
Output: 2
Explanation: Node 2 is the third node from the end of the linked list.Input: head=35 -> 15 -> 4 -> 20, k = 5
Output: -1
Explanation: length of linked list is less then k so -1.
Table of Content
[Naive Approach] Length-Based Traversal - O(n) Time and O(1) Space
The idea is to count the number of nodes in linked list in the first pass, say len. In the second pass, return the (len - k + 1)th nodes from beginning of the Linked List.
#include <iostream>
using namespace std;
// Link list node
struct Node {
int data;
Node* next;
// Constructor to initialize a new node with data
Node(int new_data) {
data = new_data;
next = nullptr;
}
};
// Function to find the kth node from the last of a linked list
int findKthFromLast(Node* head, int k) {
int len = 0, i;
// Pointer to store the copy of head
Node* temp = head;
// Count the number of nodes in Linked List
while (temp != NULL) {
temp = temp->next;
len++;
}
// Check if value of k is not more than length of the linked list
if (len < k)
return -1;
temp = head;
// Get the (len - k + 1)th node from the beginning
for (i = 1; i < len - k + 1; i++)
temp = temp->next;
return temp->data;
}
int main() {
// Create a hard-coded linked list: 35 -> 15 -> 4 -> 20
Node* head = new Node(35);
head->next = new Node(15);
head->next->next = new Node(4);
head->next->next->next = new Node(20);
// Function Call to find the 4th node from end
cout << findKthFromLast(head, 4);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
// Link list node
struct Node {
int data;
struct Node* next;
};
// Function to create a new node with given data
struct Node* newNode(int new_data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = new_data;
node->next = NULL;
return node;
}
// Function to find the kth node from the last of a linked list
int findKthFromLast(struct Node* head, int k) {
int len = 0, i;
// Pointer to store the copy of head
struct Node* temp = head;
// Count the number of nodes in Linked List
while (temp != NULL) {
temp = temp->next;
len++;
}
// Check if value of k is not more than length of the linked list
if (len < k)
return -1;
temp = head;
// Get the (len - k + 1)th node from the beginning
for (i = 1; i < len - k + 1; i++)
temp = temp->next;
return temp->data;
}
int main() {
// Create a hard-coded linked list: 35 -> 15 -> 4 -> 20
struct Node* head = newNode(35);
head->next = newNode(15);
head->next->next = newNode(4);
head->next->next->next = newNode(20);
// Function Call to find the 4th node from end
printf("%d\n", findKthFromLast(head, 4));
return 0;
}
class Node {
int data;
Node next;
// Constructor to initialize a new node with data
Node(int new_data) {
data = new_data;
next = null;
}
}
public class Main {
// Function to find the kth node from the last of a linked list
static int findKthFromLast(Node head, int k) {
int len = 0;
// Pointer to store the copy of head
Node temp = head;
// Count the number of nodes in Linked List
while (temp != null) {
temp = temp.next;
len++;
}
// Check if value of k is not more than length of the linked list
if (len < k)
return -1;
temp = head;
// Get the (len - k + 1)th node from the beginning
for (int i = 1; i < len - k + 1; i++)
temp = temp.next;
return temp.data;
}
public static void main(String[] args) {
// Create a hard-coded linked list: 35 -> 15 -> 4 -> 20
Node head = new Node(35);
head.next = new Node(15);
head.next.next = new Node(4);
head.next.next.next = new Node(20);
// Function Call to find the 4th node from end
System.out.println(findKthFromLast(head, 4));
}
}
class Node:
def __init__(self, new_data):
self.data = new_data
self.next = None
# Function to find the kth node from the last of a linked list
def findKthFromLast(head, k):
length = 0
temp = head
# Count the number of nodes in Linked List
while temp:
temp = temp.next
length += 1
# Check if value of k is not more than length of the linked list
if length < k:
return -1
temp = head
# Get the (len - k + 1)th node from the beginning
for _ in range(1, length - k + 1):
temp = temp.next
return temp.data
if __name__=="__main__":
# Create a hard-coded linked list: 35 -> 15 -> 4 -> 20
head = Node(35)
head.next = Node(15)
head.next.next = Node(4)
head.next.next.next = Node(20)
# Function Call to find the 4th node from end
print(findKthFromLast(head, 4))
using System;
class Node {
public int data;
public Node next;
// Constructor to initialize a new node with data
public Node(int new_data) {
data = new_data;
next = null;
}
}
class Program {
// Function to find the kth node from the last of a linked list
static int findKthFromLast(Node head, int k) {
int len = 0;
// Pointer to store the copy of head
Node temp = head;
// Count the number of nodes in Linked List
while (temp != null) {
temp = temp.next;
len++;
}
// Check if value of k is not more than length of the linked list
if (len < k)
return -1;
temp = head;
// Get the (len - k + 1)th node from the beginning
for (int i = 1; i < len - k + 1; i++)
temp = temp.next;
return temp.data;
}
static void Main(string[] args) {
// Create a hard-coded linked list: 35 -> 15 -> 4 -> 20
Node head = new Node(35);
head.next = new Node(15);
head.next.next = new Node(4);
head.next.next.next = new Node(20);
// Function Call to find the 4th node from end
Console.WriteLine(findKthFromLast(head, 4));
}
}
class Node {
constructor(new_data) {
this.data = new_data;
this.next = null;
}
}
// Function to find the kth node from the last of a linked list
function findKthFromLast(head, k) {
let len = 0;
let temp = head;
// Count the number of nodes in Linked List
while (temp !== null) {
temp = temp.next;
len++;
}
// Check if value of k is not more than length of the linked list
if (len < k) return -1;
temp = head;
// Get the (len - k + 1)th node from the beginning
for (let i = 1; i < len - k + 1; i++)
temp = temp.next;
return temp.data;
}
// Driver Code
// Create a hard-coded linked list: 35 -> 15 -> 4 -> 20
let head = new Node(35);
head.next = new Node(15);
head.next.next = new Node(4);
head.next.next.next = new Node(20);
// Function Call to find the 4th node from end
console.log(findKthFromLast(head, 4));
Output
35
Time complexity: O(n) where n is number of nodes in the linked list
Auxiliary Space: O(1)
[Expected Approach] Using Two Pointers(Slow and fast) - One Pass - O(n) Time and O(1) Space
The idea is to maintain two pointers, say main_ptr and ref_ptr point to the head of Linked List and move ref_ptr to the Nth node from the head to ensure that the distance between main_ptr and ref_ptr is (k - 1). Now, move both the pointers simultaneously until ref_ptr reaches the last node. Since the distance between main_ptr and ref_ptr is (k - 1), so when ref_ptr will reach the last node, main_ptr will reach kth node from the end of Linked List. Return the value of node pointed by main_ptr.
Below image is a dry run of the above approach:
Follow the given steps to solve the problem:
- Maintain two pointers main_ptr and ref_ptr
- Move ref_ptr to the kth node from the start
- Now move both main_ptr and ref_ptr, until the ref_ptr reaches the last node
- Now return the data of the main_ptr, as it is at the kth node from the end
#include <iostream>
using namespace std;
// Link list node
struct Node {
int data;
Node* next;
// Constructor to initialize a new node with data
Node(int new_data) {
data = new_data;
next = nullptr;
}
};
// Function to find kth node from the end of linked list
int kthFromEnd(Node* head, int k) {
// Create two pointers main_ptr and ref_ptr
// initially pointing to head.
Node* main_ptr = head;
Node* ref_ptr = head;
// Move ref_ptr to the k-th node from beginning.
for (int i = 1; i < k; i++) {
ref_ptr = ref_ptr->next;
// If the ref_ptr reaches NULL, then it means
// k > length of linked list
if (ref_ptr == NULL) {
return -1;
}
}
// Move ref_ptr and main_ptr by one node until
// ref_ptr reaches last node of the list.
while (ref_ptr->next != NULL) {
ref_ptr = ref_ptr->next;
main_ptr = main_ptr->next;
}
return main_ptr->data;
}
int main() {
// Create a hard-coded linked list:
// 35 -> 15 -> 4 -> 20
Node* head = new Node(35);
head->next = new Node(15);
head->next->next = new Node(4);
head->next->next->next = new Node(20);
// Function Call to find the 4th node from end
cout << kthFromEnd(head, 4);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
// Link list node
struct Node {
int data;
struct Node* next;
};
// Function to create a new node with given data
struct Node* newNode(int new_data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = new_data;
node->next = NULL;
return node;
}
// Function to find kth node from the end of linked list
int kthFromEnd(struct Node* head, int k) {
// Create two pointers main_ptr and ref_ptr
// initially pointing to head.
struct Node* main_ptr = head;
struct Node* ref_ptr = head;
// Move ref_ptr to the k-th node from beginning.
for (int i = 1; i < k; i++) {
ref_ptr = ref_ptr->next;
// If the ref_ptr reaches NULL, then it means
// k > length of linked list
if (ref_ptr == NULL) {
return -1;
}
}
// Move ref_ptr and main_ptr by one node until
// ref_ptr reaches last node of the list.
while (ref_ptr->next != NULL) {
ref_ptr = ref_ptr->next;
main_ptr = main_ptr->next;
}
return main_ptr->data;
}
int main() {
// Create a hard-coded linked list:
// 35 -> 15 -> 4 -> 20
struct Node* head = newNode(35);
head->next = newNode(15);
head->next->next = newNode(4);
head->next->next->next = newNode(20);
// Function Call to find the 4th node from end
printf("%d\n", kthFromEnd(head, 4));
return 0;
}
class Node {
int data;
Node next;
// Constructor to initialize a new node with data
Node(int new_data) {
data = new_data;
next = null;
}
}
public class Main {
// Function to find kth node from the end of linked list
static int kthFromEnd(Node head, int k) {
// Create two pointers main_ptr and ref_ptr
// initially pointing to head.
Node main_ptr = head;
Node ref_ptr = head;
// Move ref_ptr to the k-th node from beginning.
for (int i = 1; i < k; i++) {
ref_ptr = ref_ptr.next;
// If the ref_ptr reaches NULL, then it means
// k > length of linked list
if (ref_ptr == null) {
return -1;
}
}
// Move ref_ptr and main_ptr by one node until
// ref_ptr reaches last node of the list.
while (ref_ptr.next != null) {
ref_ptr = ref_ptr.next;
main_ptr = main_ptr.next;
}
return main_ptr.data;
}
public static void main(String[] args) {
// Create a hard-coded linked list:
// 35 -> 15 -> 4 -> 20
Node head = new Node(35);
head.next = new Node(15);
head.next.next = new Node(4);
head.next.next.next = new Node(20);
// Function Call to find the 4th node from end
System.out.println(kthFromEnd(head, 4));
}
}
class Node:
def __init__(self, new_data):
self.data = new_data
self.next = None
# Function to find kth node from the end of linked list
def kthFromEnd(head, k):
# Create two pointers main_ptr and ref_ptr
# initially pointing to head.
main_ptr = head
ref_ptr = head
# Move ref_ptr to the k-th node from beginning.
for _ in range(1, k):
ref_ptr = ref_ptr.next
# If the ref_ptr reaches None, then it means
# k > length of linked list
if ref_ptr is None:
return -1
# Move ref_ptr and main_ptr by one node until
# ref_ptr reaches last node of the list.
while ref_ptr.next is not None:
ref_ptr = ref_ptr.next
main_ptr = main_ptr.next
return main_ptr.data
if __name__ == "__main__":
# Create a hard-coded linked list:
# 35 -> 15 -> 4 -> 20
head = Node(35)
head.next = Node(15)
head.next.next = Node(4)
head.next.next.next = Node(20)
# Function Call to find the 4th node from end
print(kthFromEnd(head, 4))
using System;
class Node {
public int data;
public Node next;
// Constructor to initialize a new node with data
public Node(int new_data) {
data = new_data;
next = null;
}
}
class Program {
// Function to find kth node from the end of linked list
static int KthFromEnd(Node head, int k) {
// Create two pointers main_ptr and ref_ptr
// initially pointing to head.
Node main_ptr = head;
Node ref_ptr = head;
// Move ref_ptr to the k-th node from beginning.
for (int i = 1; i < k; i++) {
ref_ptr = ref_ptr.next;
// If the ref_ptr reaches NULL, then it means
// k > length of linked list
if (ref_ptr == null) {
return -1;
}
}
// Move ref_ptr and main_ptr by one node until
// ref_ptr reaches last node of the list.
while (ref_ptr.next != null) {
ref_ptr = ref_ptr.next;
main_ptr = main_ptr.next;
}
return main_ptr.data;
}
static void Main() {
// Create a hard-coded linked list:
// 35 -> 15 -> 4 -> 20
Node head = new Node(35);
head.next = new Node(15);
head.next.next = new Node(4);
head.next.next.next = new Node(20);
// Function Call to find the 4th node from end
Console.WriteLine(KthFromEnd(head, 4));
}
}
class Node {
constructor(new_data) {
this.data = new_data;
this.next = null;
}
}
// Function to find kth node from the end of linked list
function kthFromEnd(head, k) {
// Create two pointers main_ptr and ref_ptr
// initially pointing to head.
let main_ptr = head;
let ref_ptr = head;
// Move ref_ptr to the k-th node from beginning.
for (let i = 1; i < k; i++) {
ref_ptr = ref_ptr.next;
// If the ref_ptr reaches null, then it means
// k > length of linked list
if (ref_ptr === null) {
return -1;
}
}
// Move ref_ptr and main_ptr by one node until
// ref_ptr reaches last node of the list.
while (ref_ptr.next !== null) {
ref_ptr = ref_ptr.next;
main_ptr = main_ptr.next;
}
return main_ptr.data;
}
// Create a hard-coded linked list:
// 35 -> 15 -> 4 -> 20
let head = new Node(35);
head.next = new Node(15);
head.next.next = new Node(4);
head.next.next.next = new Node(20);
// Function Call to find the 4th node from end
console.log(kthFromEnd(head, 4));
Output
35
Time Complexity: O(n) where n is number of nodes the linked list
Auxiliary Space: O(1)