Remove Element

IF
AlgoAxiomStaff Engineers
JSTS
Easy20 mins

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place and return the new length. The order of the elements may be changed. It does not matter what you leave beyond the new length.

Examples

Example 1:

Input: nums = [3, 2, 2, 3], val = 3

Output: 2

Explanation: The function returns 2, with the first two elements of nums being [2, 2]. The value 3 has been removed.

Example 2:

Input: nums = [0, 1, 2, 2, 3, 0, 4, 2], val = 2

Output: 5

Explanation: The function returns 5, with the first five elements of nums being [0, 1, 3, 0, 4]. All occurrences of 2 have been removed.

Example 3:

Input: nums = [1, 1, 1], val = 1

Output: 0

Explanation: All elements equal val, so the new length is 0.

Constraints

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100
Source: Two Pointers pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle