Remove Element

Remove Element

August 20, 2023

example java arrays interviewing

Remove Element is a Leetcode problem that presents this challenge:

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

If you ignore the in-place requirement, you could do this with an ArrayList:

ArrayList<Integer> list = new ArrayList<>();
for(int i = 0; i < nums.length; i++){

int removed = 0;

for(int i = 0; i < list.size(); i++){
  nums[i] = list.get(i);

return nums.length - removed;

To do it in-place (without creating any other data structures), you might loop over each element. When you find a match to be removed, you can use another for loop to shift every subsequent element left by one:

int notEqualCount = 0;
for (int i = 0; i < nums.length; i++) {

  int element = nums[i];

  if(element != val){
  } else {
    // Shift every subsequent element left by one
    for(int j = i; j < nums.length - 1; j++) {
      nums[j] = nums[j+1];
    // Keep i at the same index to avoid skipping shifted elements

return notEqualCount;

This works, but it’s inefficient (O(n^2)) because it shifts the entire array left every time it finds a match.

Instead, you can use two pointers to process the array in a single pass:

class Solution {
  public int removeElement(int[] nums, int val) {

    int leftIndex = 0;

    for (int rightIndex = 0; rightIndex < nums.length; rightIndex++) {
      int rightElement = nums[rightIndex];
      if (rightElement != val) {
        nums[leftIndex] = rightElement;

    return leftIndex;

Using two pointers is a common approach for processing arrays or strings, so make sure it’s in your back pocket for problems like this.

Arrays and Strings Examples


Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!

Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!