Longest Common Prefix

Longest Common Prefix

Hard PHP PHP Strings 34 views
Explanation Complexity

Problem Statement

Given n strings, print their longest common prefix (or empty).

Input Format

First n. Next n lines strings.

Output Format

One line prefix.

Example

3
flower
flow
flight
fl

Constraints

Total chars

Input / Output Format

Input Format
First n. Next n lines strings.
Output Format
One line prefix.
Constraints
Total chars

Examples

Input:
3 flower flow flight
Output:
fl

Example Solution (Public)

PHP
<?php
$inputText=rtrim(stream_get_contents(STDIN));
if($inputText==='') exit;
$inputLines=preg_split('/\\R/', $inputText);
$n=intval(trim($inputLines[0] ?? '0'));
if($n<=0){ echo ''; exit; }
$pref=$inputLines[1] ?? '';
for($i=2;$i<=$n;$i++){
  $s=$inputLines[$i] ?? '';
  $j=0;
  $lim=min(strlen($pref),strlen($s));
  while($j<$lim && $pref[$j]===$s[$j]) $j++;
  $pref=substr($pref,0,$j);
  if($pref==='') break;
}
echo $pref;
?>

Official Solution Code

<?php
$inputText=rtrim(stream_get_contents(STDIN));
if($inputText==='') exit;
$inputLines=preg_split('/\\R/', $inputText);
$n=intval(trim($inputLines[0] ?? '0'));
if($n<=0){ echo ''; exit; }
$pref=$inputLines[1] ?? '';
for($i=2;$i<=$n;$i++){
  $s=$inputLines[$i] ?? '';
  $j=0;
  $lim=min(strlen($pref),strlen($s));
  while($j<$lim && $pref[$j]===$s[$j]) $j++;
  $pref=substr($pref,0,$j);
  if($pref==='') break;
}
echo $pref;
?>
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.