Interview 150

Remove Duplicates from Sorted Array

Problem
LC 26
File
interview150_LC26RemoveDuplicates.java
Path
pkg5leetcode/interview150/interview150_LC26RemoveDuplicates.java
Package
pkg5leetcode.interview150
Command
java pkg5leetcode/interview150/interview150_LC26RemoveDuplicates.java
Approach
Two pointers; write unique values at slow index.
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_LC26RemoveDuplicates.java
1package pkg5leetcode.interview150;2 3/*4 * Remove Duplicates from Sorted Array | LC 265 * APPROACH: Two pointers; write unique values at slow index.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class interview150_LC26RemoveDuplicates {9    static int removeDuplicates(int[] nums) {10        if (nums.length == 0) return 0;11        int k = 1;12        for (int i = 1; i < nums.length; i++)13            if (nums[i] != nums[k - 1]) nums[k++] = nums[i];14        return k;15    }16 17    public static void main(String[] args) {18        int[] a = {1, 1, 2};19        check(removeDuplicates(a) == 2 && a[0] == 1 && a[1] == 2, "case1");20        int[] b = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4};21        check(removeDuplicates(b) == 5, "case2");22        System.out.println("all tests passed");23    }24 25    static void check(boolean cond, String name) {26        if (!cond) throw new AssertionError("FAILED: " + name);27        System.out.println("  PASS " + name);28    }29}