Open In App

Find an array B with at least arr[i] elements in B not equal to the B[i]

Last Updated : 15 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N, the task is to find an array of size N, such that for every ith element of the array arr[], the output array should contain at least arr[i] elements that are not equal to the ith element of the output array. If there exists no such array, then print “Impossible“.

Examples:

Input: N = 5, arr[] = {4, 4, 4, 4, 4}
Output: 1 2 3 4 5

Input: N = 10, arr[] = {7, 7, 7, 7, 7, 9, 8, 8, 7, 9}
Output: 4 4 4 5 5 1 3 3 5 2

Approach: The given problem can be solved based on the observation that there should be a maximum of N-arr[i] elements that are equal to the ith element of the output array. Follow the steps below to solve the problem: 

  • Initialize an array, say res[] of size N+5, to store the output array.
  • Also, initialize an array of pairs, say V of size N+5, where V[i] stores the pair of the count of elements equal to res[i], and the index i.
  • Iterate in the range [1, N] using the variable i, and in each iteration assign the value of the pair {N-arr[i], i} to V[i].
  • Sort the array of pairs in ascending order.
  • Initialize two variables, say l and r as 0 to traverse the array.
  • Iterate over the range [0, N-1] using the variable l  and perform the following steps: 
    • Iterate over the range [l, N-1] using the variable r and do the following:
      • If V[r + 1].first is not equal to V[r]. first, then break the loop.
    • If the count of the same elements i.e (r-l+1) is not divisible by V[l].first then print “Impossible” and return.
    • Initialize a variable, say X, as 1 to assign the values to array res[].
    • Iterate over the range [l, r] using the variable i and perform the following steps:
      • Iterate over the range [i, i+V[l].first] using the variable j and then in each iteration assign X to res[V[j].second].
      • Increment i by V[l].first and X by 1.
    • Update the value of l to r+1.
  • Finally, after completing the above steps, print the array, res[].

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the possible
// output array
void findPossibleArray(int N, int arr[])
{
    pair<int, int> V[N + 5];
 
    // Stores the output array
    int res[N + 5];
 
    int cnt = 0;
    // Iterate over the range [1, N]
    for (int i = 0; i < N; i++) {
        // Update V[i]
        V[i].first = N - arr[i];
        V[i].second = i;
    }
 
    // Sort the array
    sort(V, V + N);
 
    // Iterate in the range [1, N]
    for (int l = 0, r = 0; l < N; l = r + 1) {
 
        // Iterate until r is less than N
        for (r = l; r < N - 1; ++r) {
 
            // If V[i+1].first is equal to
            // V[r].first
            if (V[r + 1].first != V[r].first) {
                break;
            }
        }
 
        // If r-l+1 is divisible by V[i].first
        if ((r - l + 1) % V[l].first) {
            cout << "Impossible" << endl;
            return;
        }
 
        // Otherwise,
        for (int i = l; i <= r; i += V[l].first) {
            cnt++;
            // Traverse the array over the range
            // [i, i+V[l].second]
            for (int j = i; j < i + V[l].first && j < N;
                 ++j)
                res[V[j].second] = cnt;
        }
    }
 
    // Print the array res[]
    for (int i = 0; i < N; i++)
        cout << res[i] << ' ';
}
 
// Driver Code
int main()
{
 
    int arr[] = { 4, 4, 4, 4, 4 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    findPossibleArray(N, arr);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.Arrays;
 
class GFG {
 
    // Function to find the possible
    // output array
    public static void findPossibleArray(int N, int arr[]) {
        int[][] V = new int[N][2];
 
        // Stores the output array
        int[] res = new int[N + 5];
 
        int cnt = 0;
        // Iterate over the range [1, N]
        for (int i = 0; i < N; i++) {
            // Update V[i]
            V[i][0] = N - arr[i];
            V[i][1] = i;
        }
 
        // Sort the array
        Arrays.sort(V, (a, b) -> a[0] - b[0]);
 
        // Iterate in the range [1, N]
        for (int l = 0, r = 0; l < N; l = r + 1) {
 
            // Iterate until r is less than N
            for (r = l; r < N - 1; ++r) {
 
                // If V[i+1][0] is equal to
                // V[r][0]
                if (V[r + 1][0] != V[r][0]) {
                    break;
                }
            }
 
 
            // If r-l+1 is divisible by V[i][0]
            if (V[l][0] == 0 || ((r - l + 1) % V[l][0]) > 0) {
                System.out.println("Impossible");
                return;
            }
 
            // Otherwise,
            for (int i = l; i <= r; i += V[l][0]) {
                cnt++;
                // Traverse the array over the range
                // [i, i+V[l][1]]
                for (int j = i; j < i + V[l][0] && j < N; ++j)
                    res[V[j][1]] = cnt;
            }
        }
 
        // Print the array res[]
        for (int i : res) {
            if (i > 0) {
                System.out.print(i + " ");
            }
        }
    }
 
    // Driver Code
    public static void main(String args[]) {
 
        int arr[] = { 4, 4, 4, 4, 4 };
        int N = arr.length;
 
        findPossibleArray(N, arr);
    }
}
 
//This code is contributed by saurabh_jaiswal.


Python3




import bisect
 
def findPossibleArray(N, arr):
    V = [[0, 0] for i in range(N)]
 
    # Stores the output array
    res = [0 for i in range(N + 5)]
 
    cnt = 0
    # Iterate over the range [1, N]
    for i in range(N):
        # Update V[i]
        V[i][0] = N - arr[i]
        V[i][1] = i
 
    # Sort the array
    V.sort(key=lambda x: x[0])
 
    # Iterate in the range [1, N]
    l = 0
    while l < N:
        # Find the range r that satisfies V[i+1][0] == V[r][0]
        r = l
        while r < N - 1 and V[r + 1][0] == V[r][0]:
            r += 1
 
        # If r-l+1 is not divisible by V[i][0]
        if V[l][0] == 0 or ((r - l + 1) % V[l][0]) > 0:
            print("Impossible")
            return
 
        # Otherwise,
        for i in range(l, r + 1, V[l][0]):
            cnt += 1
            # Traverse the array over the range
            # [i, i+V[l][1]]
            for j in range(i, min(i + V[l][0], N)):
                res[V[j][1]] = cnt
         
        l = r + 1
 
    # Print the array res[]
    for i in res:
        if i > 0:
            print(i, end=' ')
    print()
 
# Driver Code
arr = [4, 4, 4, 4, 4]
N = len(arr)
 
findPossibleArray(N, arr)


C#




using System;
using System.Collections;
using System.Collections.Generic;
 
// C# program for the above approach
class GFG {
 
  // Custom sort function
  private static void Sort<T>(T[][] data, int col)
  {
    Comparer<T> comparer = Comparer<T>.Default;
    Array.Sort<T[]>(data, (x,y) => comparer.Compare(x[col],y[col]));
  }
 
 
  // Function to find the possible
  // output array
  public static void findPossibleArray(int N, int[] arr)
  {
    int[][] V = new int[N][];
    for(int i = 0; i < N; i++){
      V[i] = new int[2];
    }
 
    // Stores the output array
    int[] res = new int[N];
 
 
    int cnt = 0;
    // Iterate over the range [1, N]
    for (int i = 0; i < N; i++) {
      // Update V[i]
      V[i][0] = N - arr[i];
      V[i][1] = i;
      // Console.WriteLine(V[i][0] + " " + V[i][1]);
    }
 
 
    // Sort the array
    Sort<int>(V, 0);
    for (int i = 0; i < N; i++) {
      // Update V[i]
      V[i][0] = N - arr[i];
      V[i][1] = i;
    }
 
    // Iterate in the range [1, N]
    for (int l = 0, r = 0; l < N; l = r + 1) {
 
      // Iterate until r is less than N
      for (r = l; r < N - 1; ++r) {
 
        // If V[i+1].first is equal to
        // V[r].first
        if (V[r + 1][0] != V[r][0]) {
          break;
        }
      }
 
      // If r-l+1 is divisible by V[i].first
      if (((r - l + 1) % V[l][0]) != 0) {
        Console.WriteLine("Impossible");
        return;
      }
 
      // Otherwise,
      for (int i = l; i <= r; i += V[l][0]) {
        cnt++;
        // Traverse the array over the range
        // [i, i+V[l].second]
        for (int j = i; j < i + V[l][0] && j < N; ++j)
          res[V[j][1]] = cnt;
      }
    }
 
    // Print the array res[]
    for (int i = 0; i < N; i++)
      Console.Write(res[i] + " ");
  }
 
  static void Main() {
 
    int[] arr = { 4, 4, 4, 4, 4 };
    int N = arr.Length;
    findPossibleArray(N, arr);
  }
}
 
// The code is contributed by Nidhi goel.


Javascript




<script>
// Javascript program for the above approach
 
// Function to find the possible
// output array
function findPossibleArray(N, arr)
{
    let V = new Array(N + 5).fill(0).map(() => new Array(2));
 
    // Stores the output array
    let res = new Array(N + 5);
 
    let cnt = 0;
     
    // Iterate over the range [1, N]
    for (let i = 0; i < N; i++)
    {
     
        // Update V[i]
        V[i][0] = N - arr[i];
        V[i][1] = i;
    }
 
    // Sort the array
    V.sort((a, b) => a[0] - b[0]);
 
    // Iterate in the range [1, N]
    for (let l = 0, r = 0; l < N; l = r + 1) {
 
        // Iterate until r is less than N
        for (r = l; r < N - 1; ++r) {
 
            // If V[i+1][0] is equal to
            // V[r][0]
            if (V[r + 1][0] != V[r][0]) {
                break;
            }
        }
 
        // If r-l+1 is divisible by V[i][0]
        if ((r - l + 1) % V[l][0]) {
            document.write("Impossible" + "<br>");
            return;
        }
 
        // Otherwise,
        for (let i = l; i <= r; i += V[l][0]) {
            cnt++;
            // Traverse the array over the range
            // [i, i+V[l][1]]
            for (let j = i; j < i + V[l][0] && j < N; ++j)
                res[V[j][1]] = cnt;
        }
    }
 
    // Print the array res[]
    for (let i = 0; i < N; i++)
        document.write(res[i] + ' ');
}
 
// Driver Code
let arr = [4, 4, 4, 4, 4];
let N = arr.length
 
findPossibleArray(N, arr);
 
// This code is contributed by _saurabh_jaiswal.
</script>


Output

1 2 3 4 5 

Time Complexity: O(N*log(N))
Auxiliary Space: O(N)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads