Check if an array of pairs can be sorted by swapping pairs with different first elements
Last Updated :
23 Jul, 2025
Given an array arr[] consisting of N pairs, where each pair represents the value and ID respectively, the task is to check if it is possible to sort the array by the first element by swapping only pairs having different IDs. If it is possible to sort, then print "Yes". Otherwise, print "No".
Examples:
Input: arr[] = {{340000, 2}, {45000, 1}, {30000, 2}, {50000, 4}}
Output: Yes
Explanation:
One of the possible way to sort the array is to swap the array elements in the following order:
- Swap, arr[0] and arr[3], which modifies the array to arr[] = {{50000, 4}, {45000, 1}, {30000, 2}, {340000, 2}}.
- Swap, arr[0] and arr[2], which modifies the array to arr[] = {{30000, 2}, {45000, 1}, {50000, 4}, {340000, 2}}.
Therefore, after the above steps the given array is sorted by the first element..
Input: arr[] = {{15000, 2}, {34000, 2}, {10000, 2}}
Output: No
Approach: The given problem can be solved based on the observation that the array can be sorted if there exist any two array elements with different IDs. Follow the steps below to solve the problem:
- Initialize a variable, say X that stores the ID of the pair at index 0.
- Traverse the array arr[] and if there exists any pair whose ID is different from X, then print "Yes" and break out of the loop.
- After completing the above steps, if all the elements have the same IDs and if the array is already sorted then print "Yes". Otherwise, Print "No".
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if an
// array is sorted or not
bool isSorted(pair<int, int>* arr,
int N)
{
// Traverse the array arr[]
for (int i = 1; i < N; i++) {
if (arr[i].first
> arr[i - 1].first) {
return false;
}
}
// Return true
return true;
}
// Function to check if it is possible
// to sort the array w.r.t. first element
string isPossibleToSort(
pair<int, int>* arr, int N)
{
// Stores the ID of the first element
int group = arr[0].second;
// Traverse the array arr[]
for (int i = 1; i < N; i++) {
// If arr[i].second is not
// equal to that of the group
if (arr[i].second != group) {
return "Yes";
}
}
// If array is sorted
if (isSorted(arr, N)) {
return "Yes";
}
else {
return "No";
}
}
// Driver Code
int main()
{
pair<int, int> arr[]
= { { 340000, 2 }, { 45000, 1 },
{ 30000, 2 }, { 50000, 4 } };
int N = sizeof(arr) / sizeof(arr[0]);
cout << isPossibleToSort(arr, N);
return 0;
}
Java
// java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
public class GFG {
// Function to check if an
// array is sorted or not
static boolean isSorted(int[][] arr, int N)
{
// Traverse the array arr[]
for (int i = 1; i < N; i++) {
if (arr[i][0] > arr[i - 1][0]) {
return false;
}
}
// Return true
return true;
}
// Function to check if it is possible
// to sort the array w.r.t. first element
static String isPossibleToSort(int[][] arr, int N)
{
// Stores the ID of the first element
int group = arr[0][1];
// Traverse the array arr[]
for (int i = 1; i < N; i++) {
// If arr[i].second is not
// equal to that of the group
if (arr[i][1] != group) {
return "Yes";
}
}
// If array is sorted
if (isSorted(arr, N)) {
return "Yes";
}
else {
return "No";
}
}
// Driver Code
public static void main(String[] args)
{
int arr[][] = { { 340000, 2 },
{ 45000, 1 },
{ 30000, 2 },
{ 50000, 4 } };
int N = arr.length;
System.out.print(isPossibleToSort(arr, N));
}
}
// This code is contributed by Kingash.
Python3
# Python3 program for the above approach
# Function to check if an
# array is sorted or not
def isSorted(arr, N):
# Traverse the array arr[]
for i in range(1, N):
if (arr[i][0] > arr[i - 1][0]):
return False
# Return true
return True
# Function to check if it is possible
# to sort the array w.r.t. first element
def isPossibleToSort(arr, N):
# Stores the ID of the first element
group = arr[0][1]
# Traverse the array arr[]
for i in range(1, N):
# If arr[i][1] is not
# equal to that of the group
if (arr[i][1] != group):
return "Yes"
# If array is sorted
if (isSorted(arr, N)):
return "Yes"
else:
return "No"
# Driver Code
if __name__ == '__main__':
arr = [ [ 340000, 2 ], [ 45000, 1 ],[ 30000, 2 ], [ 50000, 4 ] ]
N = len(arr)
print (isPossibleToSort(arr, N))
# This code is contributed by mohit kumar 29.
C#
// C# program for the above approach
using System;
class GFG {
// Function to check if an
// array is sorted or not
static bool isSorted(int[, ] arr, int N)
{
// Traverse the array arr[]
for (int i = 1; i < N; i++) {
if (arr[i, 0] > arr[i - 1, 0]) {
return false;
}
}
// Return true
return true;
}
// Function to check if it is possible
// to sort the array w.r.t. first element
static string isPossibleToSort(int[, ] arr, int N)
{
// Stores the ID of the first element
int group = arr[0, 1];
// Traverse the array arr[]
for (int i = 1; i < N; i++) {
// If arr[i].second is not
// equal to that of the group
if (arr[i, 1] != group) {
return "Yes";
}
}
// If array is sorted
if (isSorted(arr, N)) {
return "Yes";
}
else {
return "No";
}
}
// Driver Code
public static void Main()
{
int[, ] arr = { { 340000, 2 },
{ 45000, 1 },
{ 30000, 2 },
{ 50000, 4 } };
int N = arr.GetLength(0);
Console.WriteLine(isPossibleToSort(arr, N));
}
}
// This code is contributed by ukasp.
JavaScript
<script>
// Javascript program for the above approach
// Function to check if an
// array is sorted or not
function isSorted(arr, N) {
// Traverse the array arr[]
for (let i = 1; i < N; i++) {
if (arr[i][0] > arr[i - 1][0]) {
return false;
}
}
// Return true
return true;
}
// Function to check if it is possible
// to sort the array w.r.t. first element
function isPossibleToSort(arr, N) {
// Stores the ID of the first element
let group = arr[0][1];
// Traverse the array arr[]
for (let i = 1; i < N; i++) {
// If arr[i].second is not
// equal to that of the group
if (arr[i][1] != group) {
return "Yes";
}
}
// If array is sorted
if (isSorted(arr, N)) {
return "Yes";
}
else {
return "No";
}
}
// Driver Code
let arr = [[340000, 2],
[15000, 2],
[34000, 2],
[10000, 2]];
let N = arr.length;
document.write(isPossibleToSort(arr, N));
// This code is contributed by Hritik
</script>
Time Complexity: O(N)
Auxiliary Space: O(1), since no extra space has been taken.
Approach 2: Sorting Technique:
Here's another approach to solve the problem:
- Sort the given array of pairs in descending order of the first element.
- Traverse the sorted array of pairs and check if the i-th element and (i+1)-th element belong to the same group. If not, return "Yes" as they need to be swapped to make the array sorted.
- If all pairs belong to the same group and the array is still not sorted, return "No".
- Time Complexity: O(n*log(n)) where n is the number of elements in the array.
- Space Complexity: O(1)
Here's the implementation of this approach in C++:
C++
#include <bits/stdc++.h>
using namespace std;
bool comparePairs(pair<int, int> a, pair<int, int> b) {
return a.first > b.first;
}
string isPossibleToSort(pair<int, int>* arr, int N) {
// Sort the given array in descending order of first element
sort(arr, arr + N, comparePairs);
// Check if array is already sorted
bool isSorted = true;
for (int i = 1; i < N; i++) {
if (arr[i].first > arr[i-1].first) {
isSorted = false;
break;
}
}
if (isSorted) {
return "Yes";
}
// Check if it is possible to sort the array by swapping
int group = arr[0].second;
for (int i = 1; i < N; i++) {
if (arr[i].second != group) {
return "Yes";
}
}
// If all pairs belong to the same group and array is not sorted
return "No";
}
int main() {
pair<int, int> arr[] = { { 340000, 2 }, { 45000, 1 }, { 30000, 2 }, { 50000, 4 } };
int N = sizeof(arr) / sizeof(arr[0]);
cout << isPossibleToSort(arr, N);
return 0;
}
Java
import java.util.*;
public class Main {
public static void main(String[] args) {
Pair[] arr = { new Pair(340000, 2), new Pair(45000, 1), new Pair(30000, 2), new Pair(50000, 4) };
int N = arr.length;
System.out.println(isPossibleToSort(arr, N));
}
static class Pair {
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
}
static boolean comparePairs(Pair a, Pair b) {
return a.first > b.first;
}
static String isPossibleToSort(Pair[] arr, int N) {
// Sort the given array in descending order of first element
Arrays.sort(arr, new Comparator<Pair>() {
public int compare(Pair a, Pair b) {
return comparePairs(a, b) ? -1 : 1;
}
});
// Check if array is already sorted
boolean isSorted = true;
for (int i = 1; i < N; i++) {
if (arr[i].first > arr[i-1].first) {
isSorted = false;
break;
}
}
if (isSorted) {
return "Yes";
}
// Check if it is possible to sort the array by swapping
int group = arr[0].second;
for (int i = 1; i < N; i++) {
if (arr[i].second != group) {
return "Yes";
}
}
// If all pairs belong to the same group and array is not sorted
return "No";
}
}
Python3
def compare_pairs(a, b):
return a[0] > b[0]
def is_possible_to_sort(arr):
# Sort the given list of pairs in descending order of the first element
arr.sort(key=lambda x: x[0], reverse=True)
# Check if the list is already sorted
is_sorted = all(arr[i][0] >= arr[i + 1][0] for i in range(len(arr) - 1))
if is_sorted:
return "Yes"
# Check if it is possible to sort the list by swapping
group = arr[0][1]
if all(arr[i][1] == group for i in range(1, len(arr))):
return "Yes"
# If all pairs belong to the same group and the list is not sorted
return "No"
arr = [(340000, 2), (45000, 1), (30000, 2), (50000, 4)]
print(is_possible_to_sort(arr))
# This code is contributed by akshitaguprzj3
C#
using System;
using System.Linq;
public class Program
{
// Custom comparison function to sort pairs in descending order of the first element
static int ComparePairs((int, int) a, (int, int) b)
{
return b.Item1.CompareTo(a.Item1);
}
// Function to check if it's possible to sort the array
static string IsPossibleToSort((int, int)[] arr)
{
// Sort the given array in descending order of the first element
Array.Sort(arr, ComparePairs);
// Check if the array is already sorted
bool isSorted = true;
for (int i = 1; i < arr.Length; i++)
{
if (arr[i].Item1 > arr[i - 1].Item1)
{
isSorted = false;
break;
}
}
if (isSorted)
{
return "Yes";
}
// Check if it is possible to sort the array by swapping
int group = arr[0].Item2;
for (int i = 1; i < arr.Length; i++)
{
if (arr[i].Item2 != group)
{
return "Yes";
}
}
// If all pairs belong to the same group and the array is not sorted
return "No";
}
public static void Main()
{
// Input array of pairs
var arr = new[] { (340000, 2), (45000, 1), (30000, 2), (50000, 4) };
Console.WriteLine(IsPossibleToSort(arr));
}
}
JavaScript
// Nikunj Sonigara
function comparePairs(a, b) {
return a.first > b.first;
}
function isPossibleToSort(arr) {
// Sort the given array in descending order of first element
arr.sort(comparePairs);
// Check if array is already sorted
let isSorted = true;
for (let i = 1; i < arr.length; i++) {
if (arr[i].first > arr[i - 1].first) {
isSorted = false;
break;
}
}
if (isSorted) {
return "Yes";
}
// Check if it is possible to sort the array by swapping
const group = arr[0].second;
for (let i = 1; i < arr.length; i++) {
if (arr[i].second !== group) {
return "Yes";
}
}
// If all pairs belong to the same group and array is not sorted
return "No";
}
const arr = [
{ first: 340000, second: 2 },
{ first: 45000, second: 1 },
{ first: 30000, second: 2 },
{ first: 50000, second: 4 }
];
console.log(isPossibleToSort(arr));
Output:
Yes
Time Complexity: O(n*log(n)) where n is the number of elements in the array.
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem