Given the head of a linked list and the number k, Your task is to find the kth node from the end. If k is more than the number of nodes, then the output should be -1.
Examples
Example 1
Example 1
Input: LinkedList = 1 ->2 ->3 ->4 ->5 , k = 2
Output: 4
Explanation: The given linked list is 1->2->3->4->5. The 2nd node from end is 4.
Example 2
Example 2
Input: LinkedList = 12 ->9 ->5 ->4 ->2 , k= 1
Output: 2
Explanation: The given linked list is 1->2->3->4->5. The 2nd node from end is 4
Hints
Hint 1
Expected Time Complexity: O(n)
Hint 2
Expected Space Complexity: O(1)
Constraints
1 <= number of nodes <= 10^6
1 <= node->data , x <= 10^6
1 <= k <= 10^6
Companies
AmazonSamsungFlipkartQualcomm
Topics
Linked List
Track your submissions
Please log in to review your progress and explore code submissions from other participants.
Unlock the full solution
Please log in to access detailed answers and explanations.
Join the discussion
Please log in to join conversations with other participants.
Solution.csC#JavaPythonC++Javascript
1
2
3
4
5
6
7
8
9
10
Unlock the code editor
Sign in to write, run, and submit your solution against the full test suite.