LeetCode 26 – Remove Element

Posted on January 7, 2014

Last updated on January 7, 2014

Solution to LeetCode Remove Element problem.

The idea is to look for elem from the left, and swap into its place something from the right of the array, so that all elems are at the end of the array. Java code:

public int removeElement(int[] A, int elem) {
  int oldLength = A.length;
  int removed = 0;
  int lastValidIndex = A.length-1;

  int i = 0;
  while(i <= lastValidIndex){
    if(A[i] == elem){
      A[i] = A[lastValidIndex];
  return oldLength - removed;
Remove Element
Markdown SHA1: 945d110554ec6c19b573214891132211c81cd7d9