Remove the Nth Node from the End
Updated
Problem statement
Given the head of a singly linked list and an integer n, remove the nth node from the end and return the resulting head.
Count from the end starting at 1: n = 1 removes the tail. The input is nonempty and acyclic, and n is valid for its length.
Reuse the remaining nodes and preserve their order. Exactly one node is removed even when values repeat. Removing the only node returns an empty list. Lists are displayed as arrays of node values.
Function
removeNthFromEnd(head: ListNode, n: int) → ListNodeExamples
Example 1
head = [4,7,2,9,6]n = 2return = [4,7,2,6]Removed
Moved or new
From the end, 6 is first and 9 is second, so the node with value 9 is removed.
Example 2
head = [8]n = 1return = []The only node is also the first from the end. The resulting head is null.
Constraints
- The list length
Lsatisfies1 <= L <= 1000. 1 <= n <= L.- Each node value is an integer in
[-10^6, 10^6]. - The list contains no cycle.
More Mygate Phone Screen questions
- Employees Earning More Than Their ManagerPHONE SCREEN · Seen Sep 2026
- Maximum Subarray SumPHONE SCREEN · Seen Sep 2026
- Reverse a Linked ListPHONE SCREEN · Seen Sep 2026
- Users Active in Both January and FebruaryPHONE SCREEN · Seen Sep 2026
- Elements Occurring More Than n/3 TimesPHONE SCREEN · Seen Jan 2025
- Frog Jump: Minimum EnergyPHONE SCREEN · Seen Jan 2025
- Left View of a Binary TreePHONE SCREEN · Seen Jan 2025
- Two SumPHONE SCREEN · Seen Aug 2024
- Minimum in a Rotated Sorted ArrayPHONE SCREEN · Seen Jul 2024
- Minimum Subarray SumPHONE SCREEN · Seen Sep 2023
Similar questions at other companies
- Unique Target-Sum Pairs in a Sorted Doubly Linked ListArista Networks · PHONE SCREENArista Networks interview questions
- Remove Nth Node From EndBloomberg LP · PHONE SCREENBloomberg LP interview questions
- Merge Two Sorted ListsLinkedIn · PHONE SCREENLinkedIn interview questions
- Middle of a Linked ListCisco · PHONE SCREENCisco interview questions
- Merge Two Sorted ListsIBM · PHONE SCREENIBM interview questions
- Count Nodes in a ChainApple · PHONE SCREENApple interview questions
- Detect a Cycle in a Linked ListSalesforce · PHONE SCREENSalesforce interview questions
- Find the Intersection Node of Two Linked ListsVisa · PHONE SCREENVisa interview questions
- Linked List Palindrome in Constant SpaceNVIDIA · PHONE SCREENNVIDIA interview questions
- Reverse Linked-List Nodes in Groups of KPeopleStrong · OA · PHONE SCREENPeopleStrong interview questions