Pages

Monday 17 April 2017

HACKEREARTH: Permutation Swaps

Link:- https://www.hackerearth.com/practice/algorithms/graphs/breadth-first-search/practice-problems/algorithm/permutation-swaps/

Summary:
Given P and Q be two permutation of numbers 1 to N. Given some pair of indexes (ai , bi).
Your task is to find Q from P by swapping (Pai , Pbi).
Print YES if it possible else print NO.

For Example:
Input:
2
4 1
1 3 2 4
1 4 2 3
3 4
4 1
1 3 2 4
1 4 2 3
2 4

Output:
NO
YES

Logic:
Use Breadth First Search(BFS) to find connected components of indexes.
Then check for indexes in each connected component if P and Q are same or not.

To View My Solution:
https://github.com/shivam04/codes/blob/master/hackerearth/algo/graph/medium/permutation-swaps.cpp

No comments:

Post a Comment