Group Words by First Letter
PHP
Hard
5 views
Problem Description
Given n words, group them by first letter (a-z) and print counts per letter present in sorted order.
Input Format
First n. Next line n words.
Output Format
Lines: letter count.
Sample Test Case
Input:
6
apple ant ball bat cat car
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$tokens=preg_split('/\\s+/', $inputText);
$i=0; $n=intval($tokens[$i++] ?? 0);
$mp=[];
for($k=0;$k<$n;$k++){
$w=$tokens[$i++] ?? '';
if($w==='') continue;
$ch=strtolower($w[0]);
if(!isset($mp[$ch])) $mp[$ch]=0;
$mp[$ch]++;
}
ksort($mp);
$output=[];
foreach($mp as $ch=>$cnt) $output[] = $ch.' '.$cnt;
echo implode(PHP_EOL,$output);
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!