Blind 75
Remove Nth Node From End of List
- Problem
- LC 19
- Category
- Linked List
- File
- blind75_LC19RemoveNthNodeFromEnd.java
- Path
- pkg5leetcode/blind75/blind75_LC19RemoveNthNodeFromEnd.java
- Package
- pkg5leetcode.blind75
- Command
- java pkg5leetcode/blind75/blind75_LC19RemoveNthNodeFromEnd.java
- Approach
- Two pointers n+1 apart; delete node after slow.
- Complexity
- Time O(n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.blind75;2 3/*4 * Remove Nth Node From End of List | LC 195 * APPROACH: Two pointers n+1 apart; delete node after slow.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class blind75_LC19RemoveNthNodeFromEnd {9 /** Same shape as pkg5leetcode/common/ListNode.java (nested for single-file runs). */10 11 static class ListNode {12 int val;13 ListNode next;14 ListNode(int val) { this.val = val; }15 }16 17 static ListNode removeNthFromEnd(ListNode head, int n) {18 ListNode dummy = new ListNode(0);19 dummy.next = head;20 ListNode fast = dummy, slow = dummy;21 for (int i = 0; i <= n; i++) fast = fast.next;22 while (fast != null) { fast = fast.next; slow = slow.next; }23 slow.next = slow.next.next;24 return dummy.next;25 }26 27 static ListNode of(int... vals) {28 ListNode dummy = new ListNode(0), cur = dummy;29 for (int v : vals) { cur.next = new ListNode(v); cur = cur.next; }30 return dummy.next;31 }32 33 static int[] toArray(ListNode head) {34 java.util.List<Integer> list = new java.util.ArrayList<>();35 while (head != null) { list.add(head.val); head = head.next; }36 return list.stream().mapToInt(Integer::intValue).toArray();37 }38 39 public static void main(String[] args) {40 check(java.util.Arrays.equals(toArray(removeNthFromEnd(of(1, 2, 3, 4, 5), 2)), new int[]{1, 2, 3, 5}), "case1");41 check(java.util.Arrays.equals(toArray(removeNthFromEnd(of(1), 1)), new int[]{}), "case2");42 System.out.println("all tests passed");43 }44 45 static void check(boolean cond, String name) {46 if (!cond) throw new AssertionError("FAILED: " + name);47 System.out.println(" PASS " + name);48 }49}