CodingNodes / Arrays & Hashing / Remove Element System design Space play · ←→ step · R restart

Problem

Given an array nums and a number val, remove every occurrence of val in place. You may not build a second array.

Let k be the number of items that are not val. Rearrange nums so that its first k items are exactly those items, then return k. The order of the kept items does not matter, and whatever sits after position k is ignored.

Constraints

  • 0 ≤ nums.length ≤ 100
  • 0 ≤ nums[i] ≤ 50
  • 0 ≤ val ≤ 100

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: The read index i visits each item once.

Space: Only the indexes i and k are stored.

Read with i, write with k. Every item that is not val is copied to nums[k] and k moves on. Items equal to val are simply never copied. Because k never gets ahead of i, nothing is overwritten before it has been read. The kept items also stay in their original order.