MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to Generate Permutation by Swaps with Explanation

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

Problem Statement

Given n and a list of swaps (i j), start with [1..n]. Apply swaps and print the final array.

Input Format

First line n q. Next q lines i j (1-based).

Output Format

One line n integers.

Constraints

n,q

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); $first=preg_split('/\\s+/', trim($inputLines[0] ?? '')); $n=intval($first[0] ?? 0); $q=intval($first[1] ?? 0); $a=[]; for($i=1;$i<=$n;$i++) $a[]=$i; for($k=0;$k<$q;$k++){ $tokens=preg_split('/\\s+/', trim($inputLines[$k+1] ?? '')); $i=intval($tokens[0] ?? 1)-1; $j=intval($tokens[1] ?? 1)-1; $tmp=$a[$i]; $a[$i]=$a[$j]; $a[$j]=$tmp; } echo implode(' ',array_map('strval',$a)); ?>

Output Example

Input:
5 3 1 5 2 4 3 4
Output:
5 4 2 3 1

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