VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-array-b-from-a-according-to-the-given-conditions/

⇱ Find the array B[] from A[] according to the given conditions - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the array B[] from A[] according to the given conditions

Last Updated : 11 Jan, 2024

Given an array X[] of length N, having all elements less than or equal to M, the task is to print an array let's say Y[] of the same length following the given conditions:

  • Prefix GCD till index i in Y[] must be equal to ith element of X[] for all i (0 <= i <= N-1)
  • The output array must be lexographically largest.
  • The upper bound for all elements of Y[] is M. Formally, elements of Y[] must be less than or equal to M.

Examples:

Input: N = 4, M = 5, X[] = {2, 2, 2, 2}
Output: Y[] = {2, 4, 4, 4}
Explanation:

  • Till index 0: GCD(2) = X[0] = 2.
  • Till index 1: GCD(2, 4) = X[1] = 2.
  • Till index 2: GCD(2, 4, 4) = X[2] = 2.
  • Till index 3: GCD(2, 4, 4, 4) = X[3] = 2.

It can be verified that all the elements of Y[] are also less than or equal to M along with this Y[] is lexographically large as possible. Thus, Y[] follows all the given conditions.

Input: N = 6, M = 7, X[] = {3, 6, 1, 4, 3, 6}
Output: Y[] = {3, 0, 7, 0, 0, 0}
Explanation: It can be verified that the Y[] is lexographically largest possible following all the given conditions.

Approach:

The problem is based on the Number Theory and can be solve using some observations. Let us discuss the observations and approach to solve out this problem.

Here, by reading the problem, First observation that comes to mind is that, If first element of Y[i] will be equal to X[i]. Only then, GCD(Y[0] = X[0]. Therefore, we know that Y[0] must be equal to X[0].

For remaining terms, We need to find the largest number let say num, that is less than or equal to M , such that GCD (num, X[i-1]) = X[i]. So we find the maximum number which is <=M and is a multiple of X[i] in next step of approach.

For doing so, we will iterate from it to back, to find the number which satisfy our condition. If we get the number which satisfy our conditions we assign it to Y[i] and break.

Step-by-step approach:

  • First, initialize array Y[] with all elements as 0 and set Y[0] equal to X[0].
  • For each element X[i] from i = 1 to N-1, We have calculate the maximum multiple of X[i] that is less than or equal to M. This is done by dividing M by X[i] and multiplying the result by X[i].
  • Starting from this maximum multiple, it checks each multiple of X[i] in decreasing order to find a value that, when combined with X[i-1], gives a GCD equal to X[i]. This is done using the GCD function in Java (BigInteger.valueOf(j).gcd(BigInteger.valueOf(X[i-1]))). The first such value found is assigned to Y[i].
  • Finally, it prints out the elements of array Y.

Below is the implementation of the above approach:


Output
2 4 4 4 

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

Comment