MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to Find All Anagram Starts with Explanation

PHP Hard PHP Strings 25 views
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around all, anagram, start. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Given s and p (lowercase), print all start indices where an anagram of p begins.

Input Format

Two lines: s then p.

Output Format

One line indices (space-separated).

Constraints

|s|,|p|

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php $inputText=rtrim(stream_get_contents(STDIN)); if($inputText==='') exit; $inputLines=preg_split('/\\R/', $inputText); $s=$inputLines[0] ?? ''; $p=$inputLines[1] ?? ''; $n=strlen($s); $m=strlen($p); if($m===0 || $m>$n){ echo ''; exit; } $need=array_fill(0,26,0); $win=array_fill(0,26,0); for($i=0;$i<$m;$i++) $need[ord($p[$i])-97]++; for($i=0;$i<$m;$i++) $win[ord($s[$i])-97]++; $ans=[]; function sameCount($a,$b){ for($i=0;$i<26;$i++) if($a[$i]!==$b[$i]) return false; return true; } if(sameCount($need,$win)) $ans[]='0'; for($i=$m;$i<$n;$i++){ $win[ord($s[$i-$m])-97]--; $win[ord($s[$i])-97]++; if(sameCount($need,$win)) $ans[] = strval($i-$m+1); } echo implode(' ',$ans); ?>

Output Example

Input:
cbaebabacd abc
Output:
0 6

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next