15% off all plans & roadmaps Use code

See plans

Remove Element

Updated

TL;DR: Remove every copy of a value from an array in place, then return how many values remain. The winning idea is a writer index that copies each kept value forward in one pass.

Problem

Given an integer array nums and an integer val, remove every occurrence of val from nums in place. The order of the remaining elements may change. Then return the number of elements in nums that are not equal to val.

Call that count k. To be accepted, you must do the following:

  • Rearrange nums so the first k elements are the values that are not equal to val. The rest of the array does not matter, and neither does its original size.
  • Return k.

The judge calls your function and checks that the returned value equals the expected count. It then sorts the first k elements and compares them with the expected values. If every check passes, the solution is accepted.

Example 1

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k.

Example 2

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. The five elements can be returned in any order. It does not matter what you leave beyond the returned k.

Constraints

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100

Constraints that matter

  • nums.length is at most 100, so an O(n^2) shift passes the limit. The interview bar still expects one linear pass, because the shift cost grows with the square of the length.
  • The problem requires in-place edits, so the first k cells must hold the kept values. Building a separate list breaks that rule, even though it returns the right count.
  • nums[i] is at most 50 and val can be up to 100. val may never appear, so k can equal the length of the array.
  • Length 0 is allowed. Any code that reads nums[0] before checking the length will fail on that input.

View on LeetCode

Hints

Hint 1

The output is a prefix of the array, and the order of the kept values does not matter.

Hint 2

Scan the array from the left.

Solution

Intuition

The output is a prefix of the array, and the order of the kept values does not matter. That means you never need to delete anything. You only need to decide which values survive and copy them to the front.

Picture a line of people where some must step out. The writer is the next open spot at the front, and the reader walks the line, moving each staying person into that spot.

This is the two pointers pattern with in-place array modification. One index, the reader, visits every value exactly once. A second index, the writer, marks the next free slot at the front of the array.

Each kept value is copied to the writer's slot. The writer never gets ahead of the reader, so a copy never overwrites a value you have not read yet. When the reader finishes, the writer equals the count of kept values.

Watch the pattern animation

Worked example

Input: nums = [0, 1, 2, 2, 3, 0, 4, 2], val = 2
Output: 5
Explanation: Three copies of 2 are removed. The kept values, in reading order, are 0, 1, 3, 0, 4, so the function returns 5. The first five cells then hold those values. Sorting the same five values gives 0, 0, 1, 3, 4, which is the form the judge compares against.

Approach 1: Brute force: shift left

Scan the array from the left. Each time you hit val, shift every later element one slot to the left and shrink the length. Then look at the same index again, because a new value has moved into it.

This works, but each removal moves the whole tail. A value that appears many times pays that cost many times over.

Steps

  1. Set n to the array length and i to 0.
  2. While i is less than n, read A[i].
  3. If A[i] equals elem, copy each element after i one slot left, then decrease n by 1. Do not advance i.
  4. Otherwise, increase i by 1.
  5. Return n.

Dry run

Start with [0, 1, 2, 2, 3, 0, 4, 2], n = 8, elem = 2.

  • i = 2 holds 2. Shift the tail left: [0, 1, 2, 3, 0, 4, 2, 2], n = 7.
  • i = 2 holds 2 again. Shift the tail left: [0, 1, 3, 0, 4, 2, 2, 2], n = 6.
  • i = 2 holds 3, i = 3 holds 0, i = 4 holds 4. Advance past each one.
  • i = 5 holds 2. Nothing sits after it to shift, so n becomes 5.
  • i = 5 is no longer below n, so the loop stops. Return 5. The first five cells are 0, 1, 3, 0, 4.

Complexity

TimeO(n^2)
SpaceO(1)

Let n be the length of the array. Each removal shifts at most n - 1 elements, and there are at most n removals, so the shifts cost at most n times (n - 1) steps. The scan adds n more steps, so the total is O(n^2). The only extra state is a few integers, so the extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def removeElement(self, A: List[int], elem: int) -> int:
        n = len(A)
        i = 0
        while i < n:
            if A[i] == elem:
                # shift the tail one slot left
                for j in range(i, n - 1):
                    A[j] = A[j + 1]
                n -= 1
            else:
                i += 1
        return n

Approach 2: Sort, then block removal

What is slow in the brute force is that every removed copy pays for a full shift. Sorting puts all copies of val into one contiguous block. One copy of the tail then removes the whole block at once.

Sorting changes the order of the values, which the problem allows. The block is found with two linear scans after the sort.

Steps

  1. Sort A in ascending order.
  2. Scan from the left to find lo, the first index whose value is not less than elem.
  3. From lo, advance while the values equal elem. The stopping index is hi, the first cell after the block.
  4. Copy A[hi] through A[n - 1] into the slots starting at lo, one at a time.
  5. Return lo + (n - hi), the number of slots written.

Dry run

Sorted array: [0, 0, 1, 2, 2, 2, 3, 4], elem = 2, n = 8.

  • The scan for lo stops at index 3, the first 2. So lo = 3.
  • The scan for hi moves past indexes 3, 4, 5. So hi = 6.
  • Copy A[6] = 3 into slot 3. The array becomes [0, 0, 1, 3, 2, 2, 3, 4].
  • Copy A[7] = 4 into slot 4. The array becomes [0, 0, 1, 3, 4, 2, 3, 4].
  • Return lo + (n - hi) = 3 + 2 = 5. The first five cells are 0, 0, 1, 3, 4.

Complexity

TimeO(n log n)
SpaceO(1) extra beyond the sort. The sort itself uses O(log n) to O(n) internal memory, depending on the language.

Let n be the length of the array. A comparison sort takes O(n log n) time. The scans for lo and hi each visit at most n cells, and the tail copy writes at most n cells, so those steps add only O(n). The total time is O(n log n). Beyond the sort, the scans and copy use a few integers of their own.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def removeElement(self, A: List[int], elem: int) -> int:
        A.sort()
        n = len(A)
        # lo is the first index holding a value not less than elem
        lo = 0
        while lo < n and A[lo] < elem:
            lo += 1
        # hi is the first index after the block of elem values
        hi = lo
        while hi < n and A[hi] == elem:
            hi += 1
        # copy the tail into the slots that start at lo
        k = lo
        for i in range(hi, n):
            A[k] = A[i]
            k += 1
        return k

The In-place Array Modification infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

In-place Array Modification

Part of Two Pointers

Approach 3: One-pass two pointers (writer and reader)OptimalIn-place Array Modification

What is slow in the sort is that it does more work than the task needs. The output only needs the kept values at the front, in any order, so reordering values the answer never uses is wasted effort.

A reader scans once and copies each kept value to the writer's slot. Each cell is read and written a constant number of times, so one pass is enough.

Steps

  1. Set writer to 0.
  2. Move reader from 0 to n - 1.
  3. If A[reader] is not elem, copy it to A[writer].
  4. Increase writer by 1 only after a copy.
  5. Return writer.

Dry run

Start with [0, 1, 2, 2, 3, 0, 4, 2], elem = 2, writer = 0.

StepreaderA[reader]actionwriter after steparray after step
100copy to slot 01[0, 1, 2, 2, 3, 0, 4, 2]
211copy to slot 12[0, 1, 2, 2, 3, 0, 4, 2]
322skip2[0, 1, 2, 2, 3, 0, 4, 2]
432skip2[0, 1, 2, 2, 3, 0, 4, 2]
543copy to slot 23[0, 1, 3, 2, 3, 0, 4, 2]
650copy to slot 34[0, 1, 3, 0, 3, 0, 4, 2]
764copy to slot 45[0, 1, 3, 0, 4, 0, 4, 2]
872skip5[0, 1, 3, 0, 4, 0, 4, 2]

The loop ends with writer = 5. Return 5. The first five cells are 0, 1, 3, 0, 4, which holds every kept value.

Complexity

TimeO(n)
SpaceO(1)

Let n be the length of the array. The reader loop runs n times, and each iteration does one comparison and at most one copy, so the time is O(n). Since the writer is never ahead of the reader, each write lands on a cell that has already been read. The only extra state is two integers, so the space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def removeElement(self, A: List[int], elem: int) -> int:
        writer = 0
        for reader in range(len(A)):
            # keep every value that is not elem
            if A[reader] != elem:
                A[writer] = A[reader]
                writer += 1
        return writer

Common mistakes

  • writer += 1 placed outside the if. Every index advances, so kept values leave gaps and the count is wrong. Increase writer only inside the branch that copies a value.
  • if A[reader] != A[writer] in place of if A[reader] != elem. The check compares two array cells instead of the target value. Compare the current value with elem.
  • return reader or return len(A) at the end. Both return the original length. Return writer, which counts the kept values.
  • A.remove(elem) or A.pop(i) inside a loop over A. Each call shifts the tail, which costs O(n), and the loop skips the value that moved into the current index. Use the writer pointer instead.
  • nums = [x for x in nums if x != val] in Python. This rebinds the local name to a new list, so the caller's list does not change. Write into the same list, or use slice assignment such as nums[:] = ....

Edge cases

  • Empty array [] with any val. The answer is 0, and the code must not touch index 0.
  • Every value equals val, such as [4, 4, 4] with val = 4. The answer is 0, and the array content beyond k does not matter.
  • No value equals val, such as [1, 2, 3] with val = 9. The answer is 3, and the array is unchanged.
  • The only match is the last cell, such as [1, 2, 3] with val = 3. The answer is 2, and the first two cells hold 1 and 2.
  • Kept values repeat, such as [2, 2, 3, 2] with val = 3. The answer is 3, and the first three cells hold 2, 2, 2. A solution that compares with the previous kept value would wrongly drop repeats here.

Follow-ups interviewers ask

What if the kept values must keep their original relative order?
The writer solution already keeps the order. The writer copies values from left to right and never passes the reader, so each kept value lands in the same relative position among the kept values.
What if removals are rare and you want fewer writes?
Use two indexes from the ends. Keep i at the front and end at the back. When A[i] equals elem, copy A[end - 1] into A[i] and decrease end, without advancing i. Each removal costs one write, and the loop still runs O(n) times. The order of the kept values changes, which the problem allows.
What if the array is already sorted?
The copies of val form one block, so you can find its two ends with binary search in O(log n) time. The tail still has to move left to fill the gap, so the copy costs O(n) time in the worst case. Binary search speeds up finding the block, but it does not remove the need to move the tail.

Remove Element FAQ

What is the time complexity of Remove Element?

The two pointers solution runs in O(n) time, because the reader visits each index once. The shift brute force runs in O(n^2) time, because each removal moves the tail of the array.

Why use two pointers for Remove Element?

Two pointers separate reading from writing. The reader finds each value to keep, and the writer marks the slot where that value belongs. One pass is enough, so no value needs to be examined twice.

Can Remove Element be solved in O(1) extra space?

Yes. The writer solution uses two integers and writes into the input array, so the extra space is O(1). The sort-based approach needs internal memory for the sort, which is O(log n) to O(n) in some languages.

Does Remove Element need to keep the original order?

No. The problem allows any order for the first k elements. The writer solution keeps the order anyway, because it copies values from left to right.

Why does my Python solution pass the example but the judge says the array is wrong?

You may have built a new list and returned its length. The judge reads the original list, so the first k cells must be changed in place. Write into nums directly or use slice assignment such as nums[:] = ....

Asked at

See which companies ask this — Pro

Practise it