A line of lowercase English words separated by single spaces is given. Group the words that share the same first letter. For each first letter that appears, in alphabetical order (a first), print one line "letter: word word …". Within a group, write the words in the order they appear in the input, and if the same word appears several times, write it every time.
Input
1 to 1000 words, each 1 to 12 lowercase English letters
Output
one line per first letter that appears: the letter, a colon (:), then each word preceded by one space
Example 1 · stdin
banana apple cherry avocado blueberry apple
stdout
a: apple avocado apple
b: banana blueberry
c: cherry
main.py
Error List00F8 ↓ · ⇧F8 ↑
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
Grouping means "if the key is missing, put in an empty list, then add to that list". Each language has its own one-liner: Python defaultdict(list) or groups.setdefault(c, []).append(w), Java computeIfAbsent(c, k -> new ArrayList<>()).add(w), C# TryGetValue and insert a new List if missing, C++ groups[c].push_back(w) ([] creates the empty vector for you), JS a Map with has then set(c, []). Trap: Python groups.get(c, []).append(w), JS (groups.get(c) ?? []).push(w) and Java getOrDefault(c, new ArrayList<>()).add(w) add to a new list without storing it in the map, so the groups stay empty. The second trap is output order: Python dict and JS Map iterate in first-seen order and Java HashMap guarantees no order, so sort the keys or use TreeMap, SortedDictionary or std::map. C has no map, but there are only 26 first letters, so a fixed table with one slot per letter (head[26]) is enough, and looping from a gives alphabetical order for free. Craykon stores lists as the values of a Dict() (if (!groups.Contains(c)) { groups[c] = []; } then groups[c].Add(w)) and fixes the order with letters = groups.Keys; letters.Sort();.
Pythonmain.py · 7 lines
from collections import defaultdictgroups = defaultdict(list)for w in input().split(): groups[w[0]].append(w)for letter in sorted(groups): print(f"{letter}: {' '.join(groups[letter])}")
JavaScriptmain.js · 8 lines
const words = require("fs").readFileSync(0, "utf8").trim().split(/\s+/);const groups = new Map();for (const w of words) { if (!groups.has(w[0])) groups.set(w[0], []); groups.get(w[0]).push(w);}const letters = [...groups.keys()].sort();console.log(letters.map((c) => `${c}: ${groups.get(c).join(" ")}`).join("\n"));
TypeScriptmain.ts · 9 lines
import { readFileSync } from "node:fs";const words: string[] = readFileSync(0, "utf8").trim().split(/\s+/);const groups = new Map<string, string[]>();for (const w of words) { if (!groups.has(w[0])) groups.set(w[0], []); groups.get(w[0])!.push(w);}const letters: string[] = [...groups.keys()].sort();console.log(letters.map((c) => `${c}: ${groups.get(c)!.join(" ")}`).join("\n"));
JavaMain.java · 20 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.TreeMap;public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); Map<Character, List<String>> groups = new TreeMap<>(); for (String w : in.readLine().trim().split(" ")) groups.computeIfAbsent(w.charAt(0), k -> new ArrayList<>()).add(w); StringBuilder out = new StringBuilder(); for (Map.Entry<Character, List<String>> e : groups.entrySet()) out.append(e.getKey()).append(": ").append(String.join(" ", e.getValue())).append('\n'); System.out.print(out); }}
C#Main.cs · 20 lines
using System;using System.Collections.Generic;class Program{ static void Main() { var groups = new SortedDictionary<char, List<string>>(); foreach (string w in Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries)) { if (!groups.TryGetValue(w[0], out var list)) { list = new List<string>(); groups[w[0]] = list; } list.Add(w); } foreach (var kv in groups) Console.WriteLine($"{kv.Key}: {string.Join(" ", kv.Value)}"); }}
C++main.cpp · 15 lines
#include <iostream>#include <map>#include <string>#include <vector>int main() { std::map<char, std::vector<std::string>> groups; std::string w; while (std::cin >> w) groups[w[0]].push_back(w); // 없는 열쇠는 빈 vector가 생긴다 for (const auto& [letter, list] : groups) { std::cout << letter << ':'; for (const auto& x : list) std::cout << ' ' << x; std::cout << '\n'; }}
Cmain.c · 26 lines
#include <stdio.h>/* C에는 사전이 없다: 첫 글자가 a~z 26가지뿐이니 글자마다 칸이 있는 고정 표를 쓴다 */static char words[1000][13];static int next_in_group[1000];int main(void) { int head[26], tail[26]; for (int c = 0; c < 26; c++) head[c] = tail[c] = -1; int n = 0; while (scanf("%12s", words[n]) == 1) { int c = words[n][0] - 'a'; next_in_group[n] = -1; if (head[c] < 0) head[c] = n; else next_in_group[tail[c]] = n; tail[c] = n; n++; } for (int c = 0; c < 26; c++) { if (head[c] < 0) continue; printf("%c:", 'a' + c); for (int i = head[c]; i >= 0; i = next_in_group[i]) printf(" %s", words[i]); printf("\n"); } return 0;}
Craykonmain.cray · 17 lines
words = Console.ReadLine().Trim().Split();groups = Dict();foreach (w in words){ c = w[0]; if (!groups.Contains(c)) { groups[c] = []; } groups[c].Add(w);}letters = groups.Keys;letters.Sort();foreach (c in letters){ Console.WriteLine(c + ": " + groups[c].Join(" "));}