{ }codelper
removingP0058

Remove every match

The first line gives the count n, the second line n integers, and the third line an integer x.
Remove every value equal to x from the list.
Print the number of remaining values on the first line, and the remaining values in their original order, separated by single spaces, on the second line.
If nothing remains, print 0 and leave the second line empty.
If x is not in the list, the list stays as it is.

Input
1 ≤ n ≤ 10,000; every value and x is an integer from -1,000 to 1,000
Output
Two lines: the remaining count, then the remaining values (an empty line if none)
Example 1 · stdin
8
2 2 1 2 2 2 3 2
2
stdout
2
1 3
Example 2 · stdin
3
4 4 4
4
stdout
0

main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

The most common trap is removing while walking forward.
Removing an item shifts the rest left by one, but the index still moves on, so in "2 2" the second 2 is skipped.
Python for v in a: a.remove(v) skips for the same reason.
Two fixes: collect what you keep into a new list (Python [v for v in a if v != x], JavaScript/TypeScript a.filter(v => v !== x)), or remove from the back.
Tools that remove all at once: Java list.removeIf(v -> v == x), C# list.RemoveAll(v => v == x), C++20 std::erase(a, x) (before that, the erase-remove idiom), and in C a write index that copies kept values forward.
Two more traps: JavaScript a.splice(a.indexOf(x), 1) removes only one, and when x is missing indexOf is -1 so it removes the last item.
Passing an int to remove(x) on a Java List<Integer> removes position x, not the value (remove(Integer.valueOf(x)) removes the value).
The Craykon solution removes from the back with a.RemoveAt(i) (a.Remove(x) removes only one).

Pythonmain.py · 6 lines
n = int(input())a = list(map(int, input().split()))x = int(input())rest = [v for v in a if v != x]print(len(rest))print(*rest)
JavaScriptmain.js · 5 lines
const [n, ...rest] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const a = rest.slice(0, n);const x = rest[n];const left = a.filter((v) => v !== x);console.log(left.length + "\n" + left.join(" "));
TypeScriptmain.ts · 6 lines
import { readFileSync } from "node:fs";const [n, ...rest]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const a: number[] = rest.slice(0, n);const x: number = rest[n];const left: number[] = a.filter((v) => v !== x);console.log(left.length + "\n" + left.join(" "));
JavaMain.java · 19 lines
import java.util.ArrayList;import java.util.List;import java.util.Scanner;import java.util.StringJoiner; public class Main {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int n = sc.nextInt();        List<Integer> a = new ArrayList<>();        for (int i = 0; i < n; i++) a.add(sc.nextInt());        int x = sc.nextInt();        a.removeIf(v -> v == x);        StringJoiner out = new StringJoiner(" ");        for (int v : a) out.add(String.valueOf(v));        System.out.println(a.size());        System.out.println(out);    }}
C#Main.cs · 16 lines
using System;using System.Collections.Generic;using System.Linq; class Program{    static void Main()    {        Console.ReadLine();        List<int> a = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();        int x = int.Parse(Console.ReadLine());        a.RemoveAll(v => v == x);        Console.WriteLine(a.Count);        Console.WriteLine(string.Join(" ", a));    }}
C++main.cpp · 14 lines
#include <iostream>#include <vector> int main() {    int n, x;    std::cin >> n;    std::vector<int> a(n);    for (int& v : a) std::cin >> v;    std::cin >> x;    std::erase(a, x);  // C++20. 그 전에는 a.erase(std::remove(a.begin(), a.end(), x), a.end());    std::cout << a.size() << "\n";    for (size_t i = 0; i < a.size(); i++) std::cout << (i ? " " : "") << a[i];    std::cout << "\n";}
Cmain.c · 16 lines
#include <stdio.h> int main(void) {    static int a[10000];    int n, x, m = 0;    scanf("%d", &n);    for (int i = 0; i < n; i++) scanf("%d", &a[i]);    scanf("%d", &x);    /* 남길 것만 앞으로 당겨 쓴다: m은 다음에 쓸 자리 */    for (int i = 0; i < n; i++)        if (a[i] != x) a[m++] = a[i];    printf("%d\n", m);    for (int i = 0; i < m; i++) printf(i ? " %d" : "%d", a[i]);    putchar('\n');    return 0;}
Craykonmain.cray · 13 lines
n = Console.ReadLine().ToNumber();a = Console.ReadNumbers();x = Console.ReadLine().ToNumber();// 뒤에서부터 지우면 지운 뒤 당겨지는 칸을 건너뛰지 않는다for (i = a.Count - 1; i >= 0; i--){    if (a[i] == x)    {        a.RemoveAt(i);    }}Console.WriteLine(a.Count);Console.WriteLine(a);