Sort 1 to N by swapping adjacent elements (original) (raw)

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.

Table of Content

[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:

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 &arr, vector &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 arr = {1, 2, 5, 3, 4, 6}; vector 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:

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 &arr, vector &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 arr = {1, 2, 5, 3, 4, 6}; vector 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: