Practice Problem

Remove Element

Difficulty: Easy

Remove all occurrences of a given value from an array in-place and return the new length.

Remove Element

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

After your function returns a value k, the first k elements of nums should contain the elements that are not equal to val. The remaining elements beyond index k do not matter.

Examples

Example 1:

Input: nums = [3, 2, 2, 3], val = 3
Output: 2, nums = [2, 2, ...]
Explanation: The function returns k = 2, with the first 2 elements of nums being 2.

Example 2:

Input: nums = [0, 1, 2, 2, 3, 0, 4, 2], val = 2
Output: 5, nums = [0, 1, 3, 0, 4, ...]
Explanation: The function returns k = 5, with the first 5 elements containing 0, 1, 3, 0, and 4 (order may vary).

Constraints

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

Expected Complexity

  • Time: O(n)
  • Space: O(1)
EASY
Arrays
Two Pointers
In-Place
Beginner

0 views

Solution

Hints

Hint 1
Hint 2
Premium
Hint 3
Premium