Remove Nth Node From End of List
Updated
Problem statement
You are given the head of a singly linked list and an integer n. Remove the n-th node from the end of the list and return the head of the changed list.
The last node is the 1st node from the end, the node before it is the 2nd, and so on. If you remove the only node, return null (an empty list).
Function
removeNthFromEnd(head: ListNode, n: int) → ListNodeExamples
Example 1
head = [3,8,1,5,6]n = 2return = [3,8,1,6]Removed
Moved or new
Counting from the end, 6 is 1st and 5 is 2nd. Removing the node with value 5 gives [3,8,1,6].
Example 2
head = [10]n = 1return = []The only node is the 1st from the end. Removing it leaves an empty list, so the function returns null, shown as [].
Example 3
head = [5,9,2]n = 3return = [9,2]Removed
Moved or new
The list has 3 nodes, so the 3rd node from the end is the head, 5. After removing it, the node with value 9 is the new head.
Constraints
- The number of nodes in the list is
L, where1 <= L <= 1000. 1 <= n <= L-1000 <= Node.val <= 1000
More Druva Onsite Interview questions
Similar questions at other companies
- Find the Entry of a Linked List CycleQualys · ONSITE INTERVIEWQualys interview questions
- Detect a Linked-List CyclePaytm · ONSITE INTERVIEWPaytm interview questions
- Detect a Linked-List CycleCapgemini · ONSITE INTERVIEWCapgemini interview questions
- Rearrange a Linked List from Alternating EndsConcentric AI · ONSITE INTERVIEWConcentric AI interview questions
- Palindrome Linked List with RestorationMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Linked List Cycle Entry NodeGoogle · ONSITE INTERVIEWGoogle interview questions
- Detect and Break a Linked-List CycleAmazon · ONSITE INTERVIEW
- Odd-Even Linked ListBloomberg LP · ONSITE INTERVIEWBloomberg LP interview questions
- Find the Entry of a Linked List CyclePeopleStrong · ONSITE INTERVIEWPeopleStrong interview questions
- Remove a Cycle from a Singly Linked ListExpedia · ONSITE INTERVIEWExpedia interview questions