Woodstock Blog

a tech blog for general algorithmic interview questions

[LeetCode 27] Remove Element

Question

link

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Stats

Frequency 4
Diffficulty 1
Adjusted Difficulty 1
Time to use ----------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Solution

Similar to the question [LeetCode 26] Remove Duplicates From Sorted Array. Use 2 pointers.

Let’s play a game

The code I gave is 21 lines. It’s too long. Can we solve this problem with less code?

Sure we can! I have a 10-line version:

public class Solution {
    public int removeElement(int[] A, int elem) {
        int left = 0, right = 0;
        while (right < A.length) {
            if (A[right] == elem) right++;
            else A[left++] = A[right++];
        }
        return left;
    }
}

Now for a moment I thought the above code is the most concise, until I read this blog. The code is:

public class Solution {
    public int removeElement(int[] A, int elem) {
        int p = 0;
        for (int i = 0; i < A.length; i++)
            if (A[i] != elem) A[p++] = A[i];
        return p;
    }
}

OK game over. Look at the standard answer below. Happy Leetcoding!

My code

public class Solution {
    public int removeElement(int[] A, int elem) {
        if (A == null || A.length == 0) {
            return 0;
        }
        int len = A.length;
        int left = 0;
        int right = 0;
        while (right < len) {
            // skip all instances of elem 
            while (right < len && A[right] == elem) {
                right++;
            }
            if (right == len) {
                break;
            }
            A[left++] = A[right++];
        }
        return left;
    }
}