{ }codelper
counting with a maptwo pointersP0434

Songs played once in every k in a row

A radio station recorded the names of the n songs it played in one day, in the order they were played.
The first line of input gives n and k, separated by one space.
The second line of input gives the n song names in play order, separated by single spaces.
A song name is a string of 1 to 12 lowercase English letters (a-z), and the same name means the same song.
Take k songs played in a row as one window.
The windows are songs 1 to k, songs 2 to k+1, …, songs n−k+1 to n: n−k+1 windows in all.
For each window, find how many songs appear exactly once inside that window.
If every song in a window appears two or more times, that window's value is 0.
Print the n−k+1 numbers in window order on one line, separated by single spaces.

Input
1 ≤ k ≤ n ≤ 9,000, each song name has 1 to 12 lowercase letters (a-z)
Output
For each window, the number of songs that appear exactly once, in window order, n−k+1 numbers on one line separated by single spaces
Example 1 · stdin
7 3
rain sun rain moon moon sun rain
stdout
1 3 1 1 3
Example 2 · stdin
4 3
constructor apple constructor pie
stdout
1 3
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

This problem slides a window one step at a time while holding a dictionary of counts.
Instead of recounting each window from scratch, update only the counts of the song coming in and the song going out, and update the 'number of songs seen once' along with them.
Counting is Python counts.get(song, 0) + 1, JS/TS Map with (counts.get(s) ?? 0) + 1, Java getOrDefault(s, 0) + 1, C# GetValueOrDefault(s) + 1, C++ ++counts[s] (a missing key starts at 0), and Craykon Dict() with Contains.
C has no dictionary, so sort the names with qsort, drop duplicates, and use the position found by bsearch as the song number, counting in an int array.
Trap 1: in JS/TS, don't count with an object {}.
An object inherits names like constructor from the start, so counts["constructor"] || 0 is a function, and adding 1 gives the string "function Object() { [native code] }1".
Example 2 is that case: it prints 1 2 instead of 1 3.
A Map holds only the keys you put in.
Trap 2: handle all four ways a count can change.
Coming in, 0→1 adds one song seen once, and 1→2 removes one.
Going out, 1→0 removes one, and 2→1 makes the song seen-once again, adding one.
Forget the last case and the second window of example 1 becomes 2 instead of 3.
Trap 3: many languages stop when you read a missing key.
Python counts[song] += 1 raises KeyError, Java counts.get(s) + 1 unboxes null and throws NullPointerException, C# counts[s] throws KeyNotFoundException, and Craykon counts[song] stops with a missing-key error.
Only C++ counts[s] inserts a new 0.
Trap 4: the window edge.
When song i (counting from 0) comes in, song i − k must go out so the window always holds k songs.
Removing only when i > k never removes the first song, so from the second window on each window holds one song too many (example 1 becomes 1 2 …).
Output one number each time i ≥ k − 1, n − k + 1 numbers in all.

Pythonmain.py · 25 lines
n, k = map(int, input().split())songs = input().split()counts = {}once = 0  # 지금 구간에서 딱 한 번 나온 곡의 수out = []for i, song in enumerate(songs):    # 들어오는 곡: 0→1이면 하나 늘고, 1→2이면 하나 준다    c = counts.get(song, 0) + 1    counts[song] = c    if c == 1:        once += 1    elif c == 2:        once -= 1    if i >= k:        # 나가는 곡: 2→1이면 다시 한 번만 나온 곡이 되고, 1→0이면 빠진다        old = songs[i - k]        c = counts[old] - 1        counts[old] = c        if c == 1:            once += 1        elif c == 0:            once -= 1    if i >= k - 1:        out.append(once)print(" ".join(map(str, out)))
JavaScriptmain.js · 24 lines
const [nk, line] = require("fs").readFileSync(0, "utf8").split("\n");const [n, k] = nk.trim().split(" ").map(Number);const songs = line.trim().split(" ");// 객체 {}는 "constructor" 같은 이름을 이미 갖고 있다. Map은 넣은 열쇠만 갖는다const counts = new Map();let once = 0; // 지금 구간에서 딱 한 번 나온 곡의 수const out = [];for (let i = 0; i < n; i++) {  // 들어오는 곡: 0→1이면 하나 늘고, 1→2이면 하나 준다  const c = (counts.get(songs[i]) ?? 0) + 1;  counts.set(songs[i], c);  if (c === 1) once++;  else if (c === 2) once--;  if (i >= k) {    // 나가는 곡: 2→1이면 다시 한 번만 나온 곡이 되고, 1→0이면 빠진다    const old = songs[i - k];    const d = counts.get(old) - 1;    counts.set(old, d);    if (d === 1) once++;    else if (d === 0) once--;  }  if (i >= k - 1) out.push(once);}console.log(out.join(" "));
TypeScriptmain.ts · 25 lines
import { readFileSync } from "node:fs";const [nk, line] = readFileSync(0, "utf8").split("\n");const [n, k] = nk.trim().split(" ").map(Number);const songs: string[] = line.trim().split(" ");// 객체 {}는 "constructor" 같은 이름을 이미 갖고 있다. Map은 넣은 열쇠만 갖는다const counts = new Map<string, number>();let once = 0; // 지금 구간에서 딱 한 번 나온 곡의 수const out: number[] = [];for (let i = 0; i < n; i++) {  // 들어오는 곡: 0→1이면 하나 늘고, 1→2이면 하나 준다  const c = (counts.get(songs[i]) ?? 0) + 1;  counts.set(songs[i], c);  if (c === 1) once++;  else if (c === 2) once--;  if (i >= k) {    // 나가는 곡: 2→1이면 다시 한 번만 나온 곡이 되고, 1→0이면 빠진다    const old = songs[i - k];    const d = (counts.get(old) ?? 0) - 1;    counts.set(old, d);    if (d === 1) once++;    else if (d === 0) once--;  }  if (i >= k - 1) out.push(once);}console.log(out.join(" "));
JavaMain.java · 36 lines
import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.HashMap;import java.util.Map;import java.util.StringJoiner; public class Main {    public static void main(String[] args) throws Exception {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        String[] nk = br.readLine().trim().split(" ");        int n = Integer.parseInt(nk[0]);        int k = Integer.parseInt(nk[1]);        String[] songs = br.readLine().trim().split(" ");        // get은 없는 열쇠에 null을 돌려준다. getOrDefault로 0을 받는다        Map<String, Integer> counts = new HashMap<>();        int once = 0; // 지금 구간에서 딱 한 번 나온 곡의 수        StringJoiner out = new StringJoiner(" ");        for (int i = 0; i < n; i++) {            // 들어오는 곡: 0→1이면 하나 늘고, 1→2이면 하나 준다            int c = counts.getOrDefault(songs[i], 0) + 1;            counts.put(songs[i], c);            if (c == 1) once++;            else if (c == 2) once--;            if (i >= k) {                // 나가는 곡: 2→1이면 다시 한 번만 나온 곡이 되고, 1→0이면 빠진다                String old = songs[i - k];                int d = counts.get(old) - 1;                counts.put(old, d);                if (d == 1) once++;                else if (d == 0) once--;            }            if (i >= k - 1) out.add(Integer.toString(once));        }        System.out.println(out);    }}
C#Main.cs · 36 lines
using System;using System.Collections.Generic; class Program{    static void Main()    {        string[] nk = Console.ReadLine().Trim().Split(' ');        int n = int.Parse(nk[0]);        int k = int.Parse(nk[1]);        string[] songs = Console.ReadLine().Trim().Split(' ');        // counts[없는 열쇠]를 읽으면 KeyNotFoundException이 난다. GetValueOrDefault는 0을 준다        var counts = new Dictionary<string, int>();        int once = 0; // 지금 구간에서 딱 한 번 나온 곡의 수        var outList = new List<int>();        for (int i = 0; i < n; i++)        {            // 들어오는 곡: 0→1이면 하나 늘고, 1→2이면 하나 준다            int c = counts.GetValueOrDefault(songs[i]) + 1;            counts[songs[i]] = c;            if (c == 1) once++;            else if (c == 2) once--;            if (i >= k)            {                // 나가는 곡: 2→1이면 다시 한 번만 나온 곡이 되고, 1→0이면 빠진다                string old = songs[i - k];                int d = counts[old] - 1;                counts[old] = d;                if (d == 1) once++;                else if (d == 0) once--;            }            if (i >= k - 1) outList.Add(once);        }        Console.WriteLine(string.Join(" ", outList));    }}
C++main.cpp · 29 lines
#include <iostream>#include <string>#include <unordered_map>#include <vector> int main() {    std::ios::sync_with_stdio(false);    int n, k;    std::cin >> n >> k;    std::vector<std::string> songs(n);    for (auto& s : songs) std::cin >> s;    // counts[없는 열쇠]는 0으로 새로 생긴다    std::unordered_map<std::string, int> counts;    int once = 0;  // 지금 구간에서 딱 한 번 나온 곡의 수    for (int i = 0; i < n; i++) {        // 들어오는 곡: 0→1이면 하나 늘고, 1→2이면 하나 준다        int c = ++counts[songs[i]];        if (c == 1) once++;        else if (c == 2) once--;        if (i >= k) {            // 나가는 곡: 2→1이면 다시 한 번만 나온 곡이 되고, 1→0이면 빠진다            int d = --counts[songs[i - k]];            if (d == 1) once++;            else if (d == 0) once--;        }        if (i >= k - 1) std::cout << (i >= k ? " " : "") << once;    }    std::cout << "\n";}
Cmain.c · 53 lines
#include <stdio.h>#include <stdlib.h>#include <string.h> /* C에는 사전이 없다. 이름을 정렬해 겹친 것을 지우고, 이분 탐색으로 찾은 자리를 곡 번호로 쓴다 */#define MAXN 9000#define LEN 13 static char songs[MAXN][LEN];static char names[MAXN][LEN];static int id[MAXN];static int counts[MAXN]; static int cmp(const void* a, const void* b) {    return strcmp((const char*)a, (const char*)b);} int main(void) {    int n, k;    scanf("%d %d", &n, &k);    for (int i = 0; i < n; i++) {        scanf("%12s", songs[i]);        strcpy(names[i], songs[i]);    }    qsort(names, n, LEN, cmp);    int kinds = 0;    for (int i = 0; i < n; i++) {        if (kinds == 0 || strcmp(names[kinds - 1], names[i]) != 0) {            if (kinds != i) strcpy(names[kinds], names[i]);            kinds++;        }    }    for (int i = 0; i < n; i++) {        char* p = bsearch(songs[i], names, kinds, LEN, cmp);        id[i] = (int)((p - names[0]) / LEN);    }    int once = 0; /* 지금 구간에서 딱 한 번 나온 곡의 수 */    for (int i = 0; i < n; i++) {        /* 들어오는 곡: 0→1이면 하나 늘고, 1→2이면 하나 준다 */        int c = ++counts[id[i]];        if (c == 1) once++;        else if (c == 2) once--;        if (i >= k) {            /* 나가는 곡: 2→1이면 다시 한 번만 나온 곡이 되고, 1→0이면 빠진다 */            int d = --counts[id[i - k]];            if (d == 1) once++;            else if (d == 0) once--;        }        if (i >= k - 1) printf(i >= k ? " %d" : "%d", once);    }    printf("\n");    return 0;}
Craykonmain.cray · 45 lines
첫줄 = Console.ReadLine().Trim().Split(" ");n = 첫줄[0].ToNumber();k = 첫줄[1].ToNumber();songs = Console.ReadLine().Trim().Split(" ");// 사전에 없는 열쇠를 읽으면 멈춘다. 있나로 먼저 확인한다counts = Dict();once = 0; // 지금 구간에서 딱 한 번 나온 곡의 수out = [];for (i = 0; i < n; i = i + 1){    song = songs[i];    if (!counts.Contains(song))    {        counts[song] = 0;    }    // 들어오는 곡: 0→1이면 하나 늘고, 1→2이면 하나 준다    counts[song] = counts[song] + 1;    if (counts[song] == 1)    {        once = once + 1;    }    else if (counts[song] == 2)    {        once = once - 1;    }    if (i >= k)    {        // 나가는 곡: 2→1이면 다시 한 번만 나온 곡이 되고, 1→0이면 빠진다        old = songs[i - k];        counts[old] = counts[old] - 1;        if (counts[old] == 1)        {            once = once + 1;        }        else if (counts[old] == 0)        {            once = once - 1;        }    }    if (i >= k - 1)    {        out.Add(once);    }}Console.WriteLine(out.Join(" "));