Group Students by City
JavaScript
Medium
3 views
Problem Description
Given a list of students with name and city, group them by city and print each city with names in input order.
Input Format
First line n. Next n lines: name city.
Output Format
Each city on new line as: City: name1,name2
Sample Test Case
Input:
5
Ravi Pune
Neha Delhi
Aman Pune
Zara Delhi
Isha Pune
Output:
Pune: Ravi,Aman,Isha
Delhi: Neha,Zara
Official Solution
const fs=require('fs');const lines=fs.readFileSync(0,'utf8').trim().split(/\
?\
/);if(!lines[0])process.exit(0);const n=Number(lines[0].trim());const map=new Map();for(let i=1;i<=n;i++){const [name,city]=lines[i].trim().split(/\\s+/);if(!map.has(city))map.set(city,[]);map.get(city).push(name);}const out=[];for(const [city,names] of map.entries()){out.push(city+': '+names.join(','));}process.stdout.write(out.join('\
'));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!