ExamAdda Logo

Remove Elements

Easy

Given an integer array nums and an integer val, remove all occurrences of val in-place.

The relative order of the remaining elements may be changed.

Return the number of elements remaining after removing all occurrences of val.

The first k elements of the array should contain the remaining elements, where k is the returned value.

Example 1

Input

4
3 2 2 3
3

Output

2
2 2

Explanation

After removing all occurrences of 3, the remaining elements are 2 and 2.

The function returns 2, which is the number of remaining elements.

Example 2

Input

8
0 1 2 2 3 0 4 2
2

Output

5
0 1 3 0 4

Explanation

All occurrences of 2 are removed.

The remaining five elements occupy the first five positions of the array.

Constraints

0 ≤ n ≤ 10⁵
-10⁹ ≤ nums[i] ≤ 10⁹
-10⁹ ≤ val ≤ 10⁹

Hints:

Hint 1

Use one pointer to iterate through the array and another pointer to keep track of the next position where a valid element should be placed.

Hint 2

Whenever the current element is not equal to val, copy it to the write pointer and move the write pointer forward.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Jul 29, 2026

Last updated

Aug 6, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output