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:
C++
#include <bits/stdc++.h>
using namespace std;
// Return true if array can be
// sorted otherwise false
bool sortedAfterSwap(vector<int> &arr, vector<int> &brr) {
int n = arr.size();
// sort all continuous segments
// that can be swapped
for (int i = 0; i < n - 1; i++) {
int start = i;
while (i < n - 1 && brr[i] == 1) {
i++;
}
// sort the segment
sort(arr.begin() + start, arr.begin() + i + 1);
}
// Check if array is sorted or not
for (int i = 0; i < n; i++) {
if (arr[i] != i + 1)
return false;
}
return true;
}
int main() {
vector<int> arr = {1, 2, 5, 3, 4, 6};
vector<int> brr = {0, 1, 1, 1, 0};
if (sortedAfterSwap(arr, brr)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}
Java
import java.util.*;
public class GfG {
// Return true if array can be
// sorted otherwise false
public static boolean sortedAfterSwap(
List<Integer> arr, List<Integer> brr) {
int n = arr.size();
// sort all continuous segments
// that can be swapped
for (int i = 0; i < n - 1; i++) {
int start = i;
while (i < n - 1 && brr.get(i) == 1) {
i++;
}
// sort the segment
Collections.sort(arr.subList(start, i + 1));
}
// Check if array is sorted or not
for (int i = 0; i < n; i++) {
if (arr.get(i) != i + 1)
return false;
}
return true;
}
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>
(Arrays.asList(1, 2, 5, 3, 4, 6));
List<Integer> brr = new ArrayList<>
(Arrays.asList(0, 1, 1, 1, 0));
if (sortedAfterSwap(arr, brr)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
Python
# Return true if array can be
# sorted otherwise false
def sortedAfterSwap(arr, brr):
n = len(arr)
# sort all continuous segments
# that can be swapped
for i in range(n - 1):
start = i
while i < n - 1 and brr[i] == 1:
i += 1
# sort the segment
arr[start:i+1] = sorted(arr[start:i+1])
# Check if array is sorted or not
for i in range(n):
if arr[i] != i + 1:
return False
return True
if __name__ == "__main__":
arr = [1, 2, 5, 3, 4, 6]
brr = [0, 1, 1, 1, 0]
if sortedAfterSwap(arr, brr):
print("Yes")
else:
print("No")
C#
using System;
using System.Collections.Generic;
class GfG
{
// Return true if array can be
// sorted otherwise false
public static bool sortedAfterSwap(List<int> arr, List<int> brr)
{
int n = arr.Count;
// sort all continuous segments
// that can be swapped
for (int i = 0; i < n - 1; i++)
{
int start = i;
while (i < n - 1 && brr[i] == 1)
{
i++;
}
// sort the segment
arr.Sort(start, i - start + 1, null);
}
// Check if array is sorted or not
for (int i = 0; i < n; i++)
{
if (arr[i] != i + 1)
return false;
}
return true;
}
static void Main()
{
List<int> arr = new List<int> { 1, 2, 5, 3, 4, 6 };
List<int> brr = new List<int> { 0, 1, 1, 1, 0 };
if (sortedAfterSwap(arr, brr))
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
JavaScript
// Return true if array can be
// sorted otherwise false
function sortedAfterSwap(arr, brr) {
const n = arr.length;
// sort all continuous segments
// that can be swapped
for (let i = 0; i < n - 1; i++) {
let start = i;
while (i < n - 1 && brr[i] === 1) {
i++;
}
// sort the segment
arr.splice(start, i - start + 1, ...arr.slice(start, i + 1).sort((a, b) => a - b));
}
// Check if array is sorted or not
for (let i = 0; i < n; i++) {
if (arr[i] !== i + 1)
return false;
}
return true;
}
const arr = [1, 2, 5, 3, 4, 6];
const brr = [0, 1, 1, 1, 0];
if (sortedAfterSwap(arr, brr)) {
console.log("Yes");
} else {
console.log("No");
}
[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:
C++
#include <bits/stdc++.h>
using namespace std;
// Return true if array can be
// sorted otherwise false
bool sortedAfterSwap(vector<int> &arr, vector<int> &brr) {
int n = arr.size();
// to store the max element
// of previous segment
int prevMax = INT_MIN;
// find min and max of all continuous
// segments that can be swapped
for (int i = 0; i < n - 1; i++) {
// to store max and min elements
int maxi = arr[i], mini = arr[i];
while (i < n - 1 && brr[i] == 1) {
i++;
maxi = max(maxi, arr[i]);
mini = min(mini, arr[i]);
}
// if the previous segment's max is
// greater than the current segment's min
if (prevMax > mini) {
return false;
}
// update the previous segment's max
prevMax = maxi;
}
return true;
}
int main() {
vector<int> arr = {1, 2, 5, 3, 4, 6};
vector<int> brr = {0, 1, 1, 1, 0};
if (sortedAfterSwap(arr, brr)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}
Java
import java.util.*;
public class GfG {
// Return true if array can be
// sorted otherwise false
public static boolean sortedAfterSwap(List<Integer> arr, List<Integer> brr) {
int n = arr.size();
// to store the max element
// of previous segment
int prevMax = Integer.MIN_VALUE;
// find min and max of all continuous
// segments that can be swapped
for (int i = 0; i < n - 1; i++) {
// to store max and min elements
int maxi = arr.get(i), mini = arr.get(i);
while (i < n - 1 && brr.get(i) == 1) {
i++;
maxi = Math.max(maxi, arr.get(i));
mini = Math.min(mini, arr.get(i));
}
// if the previous segment's max is
// greater than the current segment's min
if (prevMax > mini) {
return false;
}
// update the previous segment's max
prevMax = maxi;
}
return true;
}
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>(Arrays.asList(1, 2, 5, 3, 4, 6));
List<Integer> brr = new ArrayList<>(Arrays.asList(0, 1, 1, 1, 0));
if (sortedAfterSwap(arr, brr)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
Python
# Return true if array can be
# sorted otherwise false
def sortedAfterSwap(arr, brr):
n = len(arr)
# to store the max element
# of previous segment
prevMax = 0
# find min and max of all continuous
# segments that can be swapped
i = 0
while i < n - 1:
# to store max and min elements
maxi = arr[i]
mini = arr[i]
while i < n - 1 and brr[i] == 1:
i += 1
maxi = max(maxi, arr[i])
mini = min(mini, arr[i])
# if the previous segment's max is
# greater than the current segment's min
if prevMax > mini:
return False
# update the previous segment's max
prevMax = maxi
i += 1
return True
if __name__ == "__main__":
arr = [1, 2, 5, 3, 4, 6]
brr = [0, 1, 1, 1, 0]
if sortedAfterSwap(arr, brr):
print("Yes")
else:
print("No")
C#
using System;
using System.Collections.Generic;
class GfG
{
// Return true if array can be
// sorted otherwise false
public static bool sortedAfterSwap(List<int> arr, List<int> brr)
{
int n = arr.Count;
// to store the max element
// of previous segment
int prevMax = int.MinValue;
// find min and max of all continuous
// segments that can be swapped
for (int i = 0; i < n - 1; i++)
{
// to store max and min elements
int maxi = arr[i], mini = arr[i];
while (i < n - 1 && brr[i] == 1)
{
i++;
maxi = Math.Max(maxi, arr[i]);
mini = Math.Min(mini, arr[i]);
}
// if the previous segment's max is
// greater than the current segment's min
if (prevMax > mini)
{
return false;
}
// update the previous segment's max
prevMax = maxi;
}
return true;
}
static void Main()
{
List<int> arr = new List<int> { 1, 2, 5, 3, 4, 6 };
List<int> brr = new List<int> { 0, 1, 1, 1, 0 };
if (sortedAfterSwap(arr, brr))
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
JavaScript
// Return true if array can be
// sorted otherwise false
function sortedAfterSwap(arr, brr) {
const n = arr.length;
// to store the max element
// of previous segment
let prevMax = -Infinity;
// find min and max of all continuous
// segments that can be swapped
for (let i = 0; i < n - 1; i++) {
// to store max and min elements
let maxi = arr[i], mini = arr[i];
while (i < n - 1 && brr[i] === 1) {
i++;
maxi = Math.max(maxi, arr[i]);
mini = Math.min(mini, arr[i]);
}
// if the previous segment's max is
// greater than the current segment's min
if (prevMax > mini) {
return false;
}
// update the previous segment's max
prevMax = maxi;
}
return true;
}
const arr = [1, 2, 5, 3, 4, 6];
const brr = [0, 1, 1, 1, 0];
if (sortedAfterSwap(arr, brr)) {
console.log("Yes");
} else {
console.log("No");
}
Below is given the implementation:
Similar Reads
Insertion Sort by Swapping Elements Insertion Sort is suitable for arrays of small size. It also achieves the best-case complexity of O(n) if the arrays are already sorted. We have discussed both Iterative Insertion Sort and Recursive Insertion Sort. In this article, slightly different implementations for both iterative and recursive
11 min read
Sort an array with swapping only with a special element is allowed Given an array of length n + 1, containing elements 1 through n and a space, Requires the use of a given swap (index i, index j) function to sort the array, You can only swap the gap and a number, in the end, put the gap at the end. There will be a number 999 in the array as a gap or space. Examples
10 min read
Number of swaps to sort when only adjacent swapping allowed Given an array arr[] of non negative integers. We can perform a swap operation on any two adjacent elements in the array. Find the minimum number of swaps needed to sort the array in ascending order. Examples : Input : arr[] = {3, 2, 1}Output : 3We need to do following swaps (3, 2), (3, 1) and (1, 2
13 min read
Check if it is possible to sort the array without swapping adjacent elements Given an array arr[] of size N, check if it is possible to sort arr[] without swapping adjacent elements. In other words, check if it is possible to sort arr[] by swapping elements but swapping two consecutive element is not allowed. Examples: Input: N = 4, arr[] = {2, 3, 1, 4}Output: YESExplanation
5 min read
Shuffle the position of each Array element by swapping adjacent elements Given an array arr[], the task is to rearrange the array elements by swapping adjacent elements such that no element remains at the same position after swapping. Examples: Input: arr[] = { 1, 2, 3, 4, 5 } Output: 2 1 5 3 4 Explanation: Adjacent elements are swapped as follows: (1, 2 -> 2, 1) (3,
10 min read