VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sort-1-n-swapping-adjacent-elements/

⇱ Sort 1 to N by swapping adjacent elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort 1 to N by swapping adjacent elements

Last Updated : 28 Apr, 2025

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.

[Naive Approach] - Using Sorting - O(n2 * log n) Time and O(1) Space

The idea is to use the Boolean array brr to partition arr into 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:

  • Loop i from 0 to n–2:
    • Set start = i.
    • While i < n–1 and brr[i] == 1, increment i.
    • Sort arr[start … i].
  • Loop j from 0 to n–1 and verify arr[j] == j+1.
  • Return true if all match, otherwise false.

Below is given the implementation:


Output
Yes

[Expected Approach] - Max and Min of Every Segment - O(n) Time and O(1) Space

A segment is a sequence that can be swapped or not.

The idea is to iterate through arr in contiguous segments defined by consecutive brr[i] == 1, compute the minimum and maximum of each segment (mini and maxi), 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:

  • Let n = arr.size() and initialize prevMax = INT_MIN.
  • Loop i from 0 to n − 2:
    • Set maxi = arr[i] and mini = arr[i].
    • While i < n − 1 and brr[i] == 1, increment i, update maxi = max(maxi, arr[i]) and mini = min(mini, arr[i]).
    • If prevMax > mini, return false.
    • Update prevMax = maxi.
  • After the loop, return true.

Below is given the implementation:


Output
Yes

Below is given the implementation:

Comment
Article Tags: