Interview 150

Remove Duplicates from Sorted List

Problem
LC 83
File
interview150_LC83RemoveDuplicatesFromSortedList.java
Path
pkg5leetcode/interview150/interview150_LC83RemoveDuplicatesFromSortedList.java
Package
pkg5leetcode.interview150
Command
java pkg5leetcode/interview150/interview150_LC83RemoveDuplicatesFromSortedList.java
Approach
Skip nodes where next has same value.
Complexity
Time O(n), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/interview150/interview150_LC83RemoveDuplicatesFromSortedList.java
1package pkg5leetcode.interview150;2 3/*4 * Remove Duplicates from Sorted List | LC 835 * APPROACH: Skip nodes where next has same value.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class interview150_LC83RemoveDuplicatesFromSortedList {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 deleteDuplicates(ListNode head) {18        ListNode cur = head;19        while (cur != null && cur.next != null) {20            if (cur.val == cur.next.val) cur.next = cur.next.next;21            else cur = cur.next;22        }23        return head;24    }25 26    static ListNode of(int... vals) {27        ListNode dummy = new ListNode(0), cur = dummy;28        for (int v : vals) { cur.next = new ListNode(v); cur = cur.next; }29        return dummy.next;30    }31 32    static int[] toArray(ListNode head) {33        java.util.List<Integer> list = new java.util.ArrayList<>();34        while (head != null) { list.add(head.val); head = head.next; }35        return list.stream().mapToInt(Integer::intValue).toArray();36    }37 38    public static void main(String[] args) {39        check(java.util.Arrays.equals(toArray(deleteDuplicates(of(1, 1, 2))), new int[]{1, 2}), "case1");40        check(java.util.Arrays.equals(toArray(deleteDuplicates(of(1, 1, 2, 3, 3))), new int[]{1, 2, 3}), "case2");41        System.out.println("all tests passed");42    }43 44    static void check(boolean cond, String name) {45        if (!cond) throw new AssertionError("FAILED: " + name);46        System.out.println("  PASS " + name);47    }48}