Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Kth from End of Linked List

Medium Acceptance 47.30% Points 30.00

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
Amazon Samsung Flipkart Qualcomm
Topics
Linked List
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions