Suppose we have an array called nums with unique values from range [0, n – 1]. This array is unsorted. We also have another array of pairs where each pair contains indices where the elements of the array can be swapped. We can swap multiple number of times. We have to check whether we can arrange the array in sorted order using these swaps or not.
So, if the input is like nums = [6,1,7,3,0,5,4,2] pairs = [(0,4),(6,0),(2,7)], then the output will be True, as we can swap index (2,7) array will be [6,1,2,3,0,5,4,7], then swap (6,0), array will be [4,1,2,3,0,5,6,7], then swap (0,4) to get [0,1,2,3,4,5,6,7].
To solve this, we will follow these steps −
- N := size of nums, P := number of pairs in pairs array
- v := a list with N number of sublists
- visited := a new set
- for i in range 0 to P, do
- insert second index of pairs[i] into v[first index of pairs[i]]
- insert first index of pairs[i] into v[second index of pairs[i]]
- for i in range 0 to N, do
- if i is not visited, then
- que := a double ended queue
- arr_first := a new list
- arr_second := a new list
- mark i as visited
- insert i at the end of que
- while que is not empty, do
- u := front element of que and delete front element of que
- insert u at the end of arr_first
- insert nums[u] at the end of arr_second
- for each s in v[u], do
- if s is not visited, then
- mark s as visited
- insert s at the end of que
- if s is not visited, then
- arr_first := sort the list arr_first
- arr_second := sort the list arr_second
- if arr_first is not same as arr_second, then
- return False
- if i is not visited, then
- return True
Let us see the following implementation to get better understanding −
Example Code
from collections import deque def solve(nums, pairs): N = len(nums) P = len(pairs) v = [[] for i in range(N)] visited = set() for i in range(P): v[pairs[i][0]].append(pairs[i][1]) v[pairs[i][1]].append(pairs[i][0]) for i in range(N): if i not in visited: que = deque() arr_first = [] arr_second = [] visited.add(i) que.append(i) while len(que) > 0: u = que.popleft() arr_first.append(u) arr_second.append(nums[u]) for s in v[u]: if s not in visited: visited.add(s) que.append(s) arr_first = sorted(arr_first) arr_second = sorted(arr_second) if arr_first != arr_second: return False return True nums = [6,1,7,3,0,5,4,2] pairs = [(0,4),(6,0),(2,7)] print(solve(nums, pairs))
Input
[6,1,7,3,0,5,4,2], [(0,4),(6,0),(2,7)]
Output
True