MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to Rearrange Without Adjacent Equals with Explanation

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

Problem Statement

Rearrange the string so that no two adjacent characters are the same. If not possible, print IMPOSSIBLE.

Input Format

One line string s (lowercase letters).

Output Format

Rearranged string or IMPOSSIBLE.

Constraints

|s|

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; $freq=[]; for($i=0,$n=strlen($inputText);$i<$n;$i++){ $ch=$inputText[$i]; if(!isset($freq[$ch])) $freq[$ch]=0; $freq[$ch]++; } $max=0; foreach($freq as $c) if($c>$max) $max=$c; if($max > intdiv(strlen($inputText)+1,2)) { echo 'IMPOSSIBLE'; exit; } function pickChar($freq,$exclude){ $best=null; $bestCnt=-1; foreach($freq as $ch=>$cnt){ if($cnt<=0) continue; if($exclude!==null && $ch===$exclude) continue; if($cnt>$bestCnt){ $bestCnt=$cnt; $best=$ch; } } return $best; } $out=''; $prev=null; for($pos=0,$n=strlen($inputText);$pos<$n;$pos++){ $ch=pickChar($freq,$prev); if($ch===null){ echo 'IMPOSSIBLE'; exit; } $out.=$ch; $freq[$ch]--; $prev=$ch; } echo $out; ?>

Output Example

Input:
aaabbc
Output:
ababac

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