![]() |
VOOZH | about |
Given an array arr[] of size n containing a permutation of the integers from 1 to n, and a binary array brr[] of size n − 1 in which you can swap two adjacent elements arr[i] and arr[i+1] only when brr[i] = 1 and brr[i+1] = 1.
Examples:
Input: arr[] = [1, 2, 5, 3, 4, 6], brr[] = [0, 1, 1, 1, 0]
Output: Yes
Explanation: As brr[2] = 1, we can swap arr[2] with arr[3] that rearranges the array to [1, 2, 3, 5, 4, 6]. Then as brr[3] = 1 as well, we can swap arr[3] with arr[4], to get the sorted array [1, 2, 3, 4, 5, 6].Input: arr[] = [2, 3, 1, 4, 5, 6], brr[] = [0, 1, 1, 1, 1]
Output: No
Explanation: Since arr[0] = 2 and arr[2] = 1, we must swap them to sort the array; however, brr[0] = 0 forbids swapping indices 0 and 1, so the array cannot be sorted.
Table of Content
The idea is to use the Boolean array
brrto partitionarrinto contiguous blocks within which any adjacent swaps are allowed, sort each block independently, and then verify that the entire array is sorted.
Follow the below given steps:
i from 0 to n–2:start = i.i < n–1 and brr[i] == 1, increment i.arr[start … i].j from 0 to n–1 and verify arr[j] == j+1.true if all match, otherwise false.Below is given the implementation:
Yes
A segment is a sequence that can be swapped or not.
The idea is to iterate through
arrin contiguous segments defined by consecutivebrr[i] == 1, compute the minimum and maximum of each segment (miniandmaxi), and ensure that each segment’s minimum is never less than the maximum of the previous segment (prevMax). If this condition holds for all segments, then the array can be sorted by the allowed swaps.
Follow the below given steps:
n = arr.size() and initialize prevMax = INT_MIN.i from 0 to n − 2:maxi = arr[i] and mini = arr[i].i < n − 1 and brr[i] == 1, increment i, update maxi = max(maxi, arr[i]) and mini = min(mini, arr[i]).prevMax > mini, return false.prevMax = maxi.true.Below is given the implementation:
Yes
Below is given the implementation: