Gcd Ordering

Given an array of integers A, find and return the lexicographically greatest arrangement of A
which follows the below rules:

  1. If the size of A is less than 3 it is always possible to rearrange A.

  2. A[i] = A[i-1] + GCD(A[i-1], A[i-2]) for all i > 2, where GCD(x, y) is
    greatest common factor of x and y.

Return the lexicographically greatest arrangement of A which follows the above rules,
if it is not possible to rearrange A according to the above rules return -1.

Note: Lexicographically means in dictionary order, i.e. if two arrangemnets are compared based
on dictionary position the arrangements which comes afterwards is said to be Lexicographically greater.



Input Format

The only argument given is the integer array A.

Output Format

Return the lexicographically greatest arrangement of A  which follows the above rules, 
if it is not possible to rearrange A according to the given rules return -1.

Constraints

1 <= length of the array <= 100000
0 <= A[i] <= 10^5

For Example

Input 1:
    A = [4, 6, 2, 5, 3]
Output 1:
     [2, 3, 4, 5, 6]

Input 2:
    A = [3, 8, 5]
Output 2:
    -1
NOTE: You only need to implement the given function. Do not read input, instead use the arguments to the function. Do not print the output, instead return values as specified. Still have a doubt? Checkout Sample Codes for more details.
Start solving Gcd Ordering on Interview Code Editor
Sign Up
to access hints and editorial solutions for Gcd Ordering

Discussion


Loading...
Click here to start solving coding interview questions