Anagram Check

Anagram Check

Medium PHP PHP Strings 36 views
Explanation Complexity

Problem Statement

Given two strings, check if they are anagrams (ignore spaces, case-insensitive).

Input Format

Two lines a and b.

Output Format

YES or NO.

Example

listen
silent
YES

Constraints

Total chars

Input / Output Format

Input Format
Two lines a and b.
Output Format
YES or NO.
Constraints
Total chars

Examples

Input:
listen silent
Output:
YES

Example Solution (Public)

PHP
<?php
$inputText=rtrim(stream_get_contents(STDIN));
if($inputText==='') exit;
$inputLines=preg_split('/\\R/', $inputText);
$a=strtolower(str_replace(' ','',$inputLines[0] ?? ''));
$b=strtolower(str_replace(' ','',$inputLines[1] ?? ''));
if(strlen($a)!==strlen($b)){ echo 'NO'; exit; }
$fa=[]; $fb=[];
for($i=0,$n=strlen($a);$i<$n;$i++){
  $ca=$a[$i]; $cb=$b[$i];
  if(!isset($fa[$ca])) $fa[$ca]=0;
  if(!isset($fb[$cb])) $fb[$cb]=0;
  $fa[$ca]++; $fb[$cb]++;
}
ksort($fa); ksort($fb);
echo ($fa==$fb) ? 'YES' : 'NO';
?>

Official Solution Code

<?php
$inputText=rtrim(stream_get_contents(STDIN));
if($inputText==='') exit;
$inputLines=preg_split('/\\R/', $inputText);
$a=strtolower(str_replace(' ','',$inputLines[0] ?? ''));
$b=strtolower(str_replace(' ','',$inputLines[1] ?? ''));
if(strlen($a)!==strlen($b)){ echo 'NO'; exit; }
$fa=[]; $fb=[];
for($i=0,$n=strlen($a);$i<$n;$i++){
  $ca=$a[$i]; $cb=$b[$i];
  if(!isset($fa[$ca])) $fa[$ca]=0;
  if(!isset($fb[$cb])) $fb[$cb]=0;
  $fa[$ca]++; $fb[$cb]++;
}
ksort($fa); ksort($fb);
echo ($fa==$fb) ? 'YES' : 'NO';
?>
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.