Open In App

Check if Array can be sorted by changing elements to Absolute difference with j

Last Updated : 01 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of positive numbers arr[] of size n, the task is to check if we can make the array sorted in non-decreasing order by choosing any positive integer j and changing all elements of the array 
a[i] to abs(a[i]-j).

Examples:

Input: arr = { 3, 3, 1 }
Output: Yes 
Explanation: We can make array sorted in non-decreasing order by choosing an integer 2.

Input: arr = { 5, 3, 4, 5 }
Output: No
Explanation: It is impossible to make array sorted in non-decreasing order by choosing any integer value.

Approach: To solve the problem follow the below idea:

The idea is to take two integers l = 0 and r = 109 such that if we choose integer j such that l ≤ j ≤ r for every j, the array will be sorted till index current index i by performing this operation and we will assign l and r by taking overlap of previous and current range. After iterating the whole array, if l ≤ r, then it is possible to make array sorted in non-decreasing order and print “Yes”, else print “No”.

Below are the steps for the above approach:

  • Initialize the range from l to r, assign l to 0, and r = 109.
  • Iterate the array and check,
    • If x is less than y, we update the right endpoint r of the range as the minimum of the previous value of r and (x + y) / 2.
    • If x is greater than y, we update the left endpoint l of the range as the maximum of the previous value of l and (x + y + 1) / 2.
  • After iterating the whole array, check if l <= r, print “Yes” else, print “No”.

Below is the implementation for the above approach:

C++




// C++ code of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find if we can make array
// sorted in non-decreasing order by
// choosing any positive integer
// and perform operation
bool makesorted(int* arr, int n)
{
 
    // Assign l and r initially because
    // we can choose any positive integer
    int l = 0, r = 1e9;
 
    // Iterate the array
    for (int i = 0; i + 1 < n; i++) {
 
        // Current element
        int x = arr[i];
 
        // Next element
        int y = arr[i + 1];
 
        int l1 = (x + y) / 2;
        int r1 = (x + y + 1) / 2;
 
        // Taking intersection of range
        // l to r and range l1 to r1
        if (x < y) {
            r = min(r, l1);
        }
        if (x > y) {
            l = max(l, r1);
        }
    }
 
    // After iterating whole array,
    // if l <= r
    if (l <= r) {
 
        // Return true
        return true;
    }
 
    // Else return false
    return false;
}
 
// Drive Code
int main()
{
    int arr[] = { 3, 3, 1 };
    int n = sizeof(arr) / sizeof(int);
 
    // Function call
    if (makesorted(arr, n)) {
        cout << "Yes" << endl;
    }
    else {
        cout << "No" << endl;
    }
 
    return 0;
}


Java




// Jaava code for the above approach:
 
import java.io.*;
 
class GFG {
 
    // Function to find if we can make array sorted in
    // non-decreasing order by choosing any positive integer
    // and perform operation
    static boolean makesorted(int[] arr, int n)
    {
        // Assign l and r initially because we can choose
        // any positive integer
        int l = 0, r = (int)1e9;
 
        // iterate the array
        for (int i = 0; i + 1 < n; i++) {
            // Current element
            int x = arr[i];
 
            // Next element
            int y = arr[i + 1];
 
            int l1 = (x + y) / 2;
            int r1 = (x + y + 1) / 2;
 
            // Taking intersection of range l to r and range
            // l1 to r1
            if (x < y) {
                r = Math.min(r, l1);
            }
            if (x > y) {
                l = Math.min(l, r1);
            }
        }
 
        // After iterating whole array, if l<=r
        if (l <= r) {
            // return true
            return true;
        }
        // else, return false
        return false;
    }
 
    public static void main(String[] args)
    {
        int[] arr = { 3, 3, 1 };
        int n = arr.length;
 
        // Function call
        if (makesorted(arr, n)) {
            System.out.println("Yes");
        }
        else {
            System.out.println("No");
        }
    }
}
 
// This code is contributed by karthik.


Python3




def makesorted(arr, n):
    # Assign l and r initially because
    # we can choose any positive integer
    l, r = 0, int(1e9)
 
    # Iterate the array
    for i in range(n - 1):
        # Current element
        x = arr[i]
 
        # Next element
        y = arr[i + 1]
 
        l1 = (x + y) // 2
        r1 = (x + y + 1) // 2
 
        # Taking intersection of range
        # l to r and range l1 to r1
        if x < y:
            r = min(r, l1)
        if x > y:
            l = max(l, r1)
 
    # After iterating whole array,
    # if l <= r
    if l <= r:
        # Return true
        return True
 
    # Else return false
    return False
 
# Drive code
arr = [3, 3, 1]
n = len(arr)
 
# Function call
if makesorted(arr, n):
    print("Yes")
else:
    print("No")
# This code is contributed By Shivam Tiwari


C#




using System;
 
public class Program
{
    public static bool MakeSorted(int[] arr, int n)
    {
        // Assign l and r initially because
        // we can choose any positive integer
        int l = 0;
        int r = (int)1e9;
 
        // Iterate the array
        for (int i = 0; i < n - 1; i++)
        {
            // Current element
            int x = arr[i];
 
            // Next element
            int y = arr[i + 1];
 
            int l1 = (x + y) / 2;
            int r1 = (x + y + 1) / 2;
 
            // Taking intersection of range
            // l to r and range l1 to r1
            if (x < y)
            {
                r = Math.Min(r, l1);
            }
            if (x > y)
            {
                l = Math.Max(l, r1);
            }
        }
 
        // After iterating the whole array,
        // if l <= r
        if (l <= r)
        {
            // Return true
            return true;
        }
 
        // Else return false
        return false;
    }
 
    public static void Main(string[] args)
    {
        int[] arr = { 3, 3, 1 };
        int n = arr.Length;
 
        // Function call
        if (MakeSorted(arr, n))
        {
            Console.WriteLine("Yes");
        }
        else
        {
            Console.WriteLine("No");
        }
    }
}
// This code is contributed by codearcade


Javascript




// JavaScript code of the above approach
function makesorted(arr) {
// Assign l and r initially because
// we can choose any positive integer
let l = 0, r = 1e9;
 
// Iterate the array
for (let i = 0; i + 1 < arr.length; i++) {
 
    // Current element
    let x = arr[i];
 
    // Next element
    let y = arr[i + 1];
 
    let l1 = Math.floor((x + y) / 2);
    let r1 = Math.floor((x + y + 1) / 2);
 
    // Taking intersection of range
    // l to r and range l1 to r1
    if (x < y) {
        r = Math.min(r, l1);
    }
    if (x > y) {
        l = Math.max(l, r1);
    }
}
 
// After iterating whole array,
// if l <= r
if (l <= r) {
 
    // Return true
    return true;
}
 
// Else return false
return false;
}
 
// Drive Code
let arr = [3, 3, 1];
 
// Function call
if (makesorted(arr)) {
console.log("Yes");
}
else {
console.log("No");
}


Output

Yes

Time Complexity: O(N)
Auxiliary Space: O(1)



Similar Reads

Check if two sorted arrays can be merged to form a sorted array with no adjacent pair from the same array
Given two sorted arrays A[] and B[] of size N, the task is to check if it is possible to merge two given sorted arrays into a new sorted array such that no two consecutive elements are from the same array. Examples: Input: A[] = {3, 5, 8}, B[] = {2, 4, 6}Output: Yes Explanation: Merged array = {B[0], A[0], B[1], A[1], B[2], A[2]} Since the resultan
16 min read
Check if the array can be sorted only if the elements on given positions can be swapped
Given an array arr[] of length N and another array P[] containing {a1, a2, ... ak} which represents the positions of the given array arr[], the task is to check if the array can be sorted by only swapping the elements' arr[ai], arr[ai+1] where 'i' is some element in the array P[].Examples: Input: arr[] = {3, 2, 1}, P[] = {1, 2} Output: Yes Explanat
8 min read
Check if matrix A can be converted to B by changing parity of corner elements of any submatrix
Given two binary matrices, A[][] and B[][] of N×M. In a single operation, one can choose a sub-matrix (min of 2 rows and 2c columns) and change the parity of the corner elements i.e. 1 can be changed to a 0, and 0 can be changed to a 1. The task is to check if matrix A can be converted to B using any number of operations. Examples: Input: A[][] = {
8 min read
Maximize Array sum by subtracting absolute of odd and adding absolute of even elements
Given an array arr[] of size N, the task is to maximize the array sum by subtracting the absolute values of all odd and adding and absolute values of all even elements, with only at most one exceptional even-odd pair, i.e., only one even value can be subtracted and one odd element can be added. Examples: Input: arr[] = {-5, -4, -3, -2, -1, 0, 1, 2,
7 min read
Check if an Array can be Sorted by picking only the corner Array elements
Given an array arr[] consisting of N elements, the task is to check if the given array can be sorted by picking only corner elements i.e., elements either from left or right side of the array can be chosen. Examples: Input: arr[] = {2, 3, 4, 10, 4, 3, 1} Output: Yes Explanation: The order of picking elements from the array and placing in the sorted
5 min read
Check if an array can be sorted by swapping pairs from indices consisting of unequal elements in another array
Given an array A[] of size N and a binary array B[] of size N, the task is to check if the array A[] can be converted into a sorted array by swapping pairs (A[i], A[j]) if B[i] is not equal to B[j]. If the array A[] can be sorted, then print "Yes". Otherwise, print "No". Examples: Input: A[] = {3, 1, 2}, B[] = {0, 1, 1}Output: YesExplanation:Swap e
15 min read
Check if array can be divided into two sub-arrays such that their absolute difference is K
Given an array arr[] and an integer K, the task is to find whether the array can be divided into two sub-arrays such that the absolute difference of the sum of the elements of both the sub-arrays is K. Examples: Input: arr[] = {2, 4, 5, 1}, K = 0 Output: Yes {2, 4} and {5, 1} are the two possible sub-arrays. |(2 + 4) - (5 + 1)| = |6 - 6| = 0 Input:
6 min read
Smallest number that can replace all -1s in an array such that maximum absolute difference between any pair of adjacent elements is minimum
Given an array arr[] consisting of N positive integers and some elements as -1, the task is to find the smallest number, say K, such that replacing all -1s in the array by K minimizes the maximum absolute difference between any pair of adjacent elements. Examples: Input: arr[] = {-1, 10, -1, 12, -1}Output: 11Explanation:Consider the value of K as 1
8 min read
Sort given Array which is already Sorted based on absolute values of elements
Given an array arr[] of size N, sorted based on the absolute value of its elements. The task is to sort this array based on the actual values of the elements. Examples: Input: arr[] = {5, -7, 10, -11, 18}Output: -11, -7, 5, 10, 18Explanation: When the array is sorted the negative values will come at the beginning of the array. Input: arr[] = {1, -2
7 min read
Count number of common elements between a sorted array and a reverse sorted array
Given two arrays consisting of N distinct integers such that the array A[] and B[] are sorted in ascending and descending order respectively, the task is to find the number of values common in both arrays. Examples: Input: A[] = {1, 10, 100}, B[] = {200, 20, 2}Output: 0 Input: A[] = {2, 4, 5, 8, 12, 13, 17, 18, 20, 22, 309, 999}, B[] = {109, 99, 68
17 min read
Article Tags :
Practice Tags :