Skip to content
Problem 27 · LeetCode 27(opens in a new tab)

Remove Element

EasyArrays

You get a list of whole numbers, nums, and one number, val. Take every copy of val out of the list, working inside nums itself rather than building a new list.

Return k, how many values are left. The first k cells of nums must hold exactly those values, in any order. Whatever sits after the first k cells is ignored.

Example 1

Input:  nums = [5, 1, 5, 4, 5], val = 5
Output: 2, nums = [1, 4, _, _, _]
Why:    only 1 and 4 are not 5
2 more examples and the constraints

Example 2

Input:  nums = [7, 7], val = 7
Output: 0, nums = [_, _]
Why:    every value matches, nothing is left

Example 3

Input:  nums = [2, 6, 3], val = 9
Output: 3, nums = [2, 6, 3]
Why:    9 never appears, so all three stay

Constraints

  • nums holds between 0 and 100 numbers
  • Each number in nums is from 0 to 50
  • val is from 0 to 100

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Delete and shiftO(n²)
  2. Read pointer, write pointerO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100 numbers, mostly valVerdict
Delete and shiftO(n²)
Correct, but moves the tail every time
Read pointer, write pointerO(n)
Best; one pass, in place

n = length of nums.

Edge cases to test

  • Empty list. [] gives k = 0.
  • Everything matches. [7, 7] with val 7 gives k = 0.
  • Nothing matches. [2, 6, 3] with val 9 keeps all three, so k = 3.
  • Matches next to each other. In [3, 3, 1], deleting the first 3 slides another 3 into the same cell; it must be checked too.

Common mistakes

  • Returning the new list instead of the count k.
  • In the shift version, moving i forward after a delete and so skipping the value that slid into place.
  • Building a second list and forgetting to copy it back into nums.

How to talk through it

  1. 1Clarify. Does the order of the kept values matter? Is anything past the first k cells checked?
  2. 2Give the simple version. Delete each match by shifting the tail; say it is O(n²) in the worst case.
  3. 3Notice nothing has to move back. Only the front k cells count, so copy keepers forward instead of deleting.
  4. 4Code the two pointers. One reads every value, k writes keepers. Explain why k can never overwrite an unread value.
  5. 5Test out loud. Run the empty list, all matches and no matches before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?