U

30. Remove All Occurrences of Value in Place

Easy

Problem Description

Remove all occurrences of integer valval from an array of NN integers in-place. Preserve the relative order of the remaining elements.

Input Format

  • •Line 1: Two space-separated integers NN and valval (1≤N≤1051 \le N \le 10^5).
  • •Line 2: NN space-separated integers A1,…,ANA_1, \dots, A_N.

Output Format

  • •Line 1: An integer KK, the new logical size.
  • •Line 2: The KK remaining space-separated integers, or EMPTY if K=0K = 0.
Example 1:
Input:
6 3
3 2 2 3 4 3
Output:
3
2 2 4
Explanation: Removing all 3s leaves 2, 2, 4 with new size 3.
Example 2:
Input:
4 1
1 1 1 1
Output:
0
EMPTY
Explanation: All elements equal 1, leaving size 0 and EMPTY.
Example 3:
Input:
3 5
1 2 3
Output:
3
1 2 3
Explanation: Value 5 does not appear in array; array unchanged.
Constraints:
  • Standard integer bounds: 32-bit signed integer or input range [1, 10^5].
  • Time complexity target: O(N) or O(N log N) where applicable.
  • Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online