# Lexicographically largest permutation of the array such that a[i] = a[i-1] + gcd(a[i-1], a[i-2])

Given an array arr[] of size N (N > 2). The task is to find lexicographically largest permutation of the array such that arr[i] = arr[i – 1] + gcd(arr[i – 1], arr[i – 2]). If it is not possible to find such arrangement then print -1.

Examples:

Input: arr[] = {4, 6, 2, 5, 3}
Output: 2 3 4 5 6
4 = 3 + gcd(2, 3)
5 = 4 + gcd(3, 4)
6 = 5 + gcd(4, 5)

Input: arr[] = {1, 6, 8}
Output: -1

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: If you are thinking about a solution that would involve sorting the array and then checking if the gcd condition holds. You are partly right, the numbers have to be in increasing sequence but except for one case where there could be a number that could appear at the start of the permutation. For Example, arr[] = {2, 4, 6, 8, 8} in this case, 8 can be placed at the starting of the array to get the permutation {8, 2, 4, 6, 8}.
Corner cases:

• You couldn’t have more than two elements whose freq was more than 1.
• If you had two zeros in the array, the only possible permutation possible was all 0’s

Below is the implementation of the above approach:

## C++

 `// C++ implementation of the approach ` `#include ` `using` `namespace` `std; ` ` `  `// Function to find elements of vector ` `void` `Print(vector<``int``>& ans) ` `{ ` `    ``for` `(``auto` `i : ans) ` `        ``cout << i << ``" "``; ` `} ` ` `  `// Function to find the lexicographically largest ` `// permutation that satisfies the given condition ` `void` `Permutation(``int` `a[], ``int` `n) ` `{ ` `    ``int` `flag = 0, pos; ` ` `  `    ``// To store the required ans ` `    ``vector<``int``> ans; ` ` `  `    ``// Sort the array ` `    ``sort(a, a + n); ` ` `  `    ``for` `(``int` `i = 2; i < n; i++) { ` ` `  `        ``// If need to make arranagement ` `        ``if` `(a[i] != a[i - 1] + __gcd(a[i - 1], a[i - 2])) { ` `            ``flag = 1; ` `            ``pos = i; ` `            ``break``; ` `        ``} ` `    ``} ` ` `  `    ``// If possible then check for lexographically ` `    ``// larger permutation (if any possible) ` `    ``if` `(flag == 0) { ` ` `  `        ``// If larger arrangement is possible ` `        ``if` `(a == a + __gcd(a, a[n - 1])) { ` `            ``ans.push_back(a[n - 1]); ` `            ``for` `(``int` `i = 0; i < n - 1; i++) ` `                ``ans.push_back(a[i]); ` ` `  `            ``Print(ans); ` `            ``return``; ` `        ``} ` ` `  `        ``// If no other arrangement is possible ` `        ``else` `{ ` `            ``for` `(``int` `i = 0; i < n; i++) ` `                ``ans.push_back(a[i]); ` ` `  `            ``Print(ans); ` `            ``return``; ` `        ``} ` `    ``} ` ` `  `    ``// Need to re-arrange the array ` `    ``else` `{ ` ` `  `        ``// If possible, place at first position ` `        ``if` `(a == a + __gcd(a[pos], a)) { ` `            ``flag = 0; ` `            ``for` `(``int` `i = n - 1; i > pos + 2; i--) { ` ` `  `                ``// If even after one arrangement its impossible ` `                ``// to get the required array ` `                ``if` `(a[i] != a[i - 1] + __gcd(a[i - 1], a[i - 2])) { ` `                    ``flag = 1; ` `                    ``break``; ` `                ``} ` `            ``} ` ` `  `            ``if` `(flag == 0 and pos < n - 1) { ` ` `  `                ``// If it is not possible to get ` `                ``// the required array ` `                ``if` `(a[pos + 1] ` `                    ``!= a[pos - 1] + __gcd(a[pos - 1], a[pos - 2])) ` `                    ``flag = 1; ` `            ``} ` ` `  `            ``if` `(flag == 0 and pos < n - 2) { ` ` `  `                ``// If it is not possible to get ` `                ``// the required array ` `                ``if` `(a[pos + 2] ` `                    ``!= a[pos + 1] + __gcd(a[pos - 1], a[pos + 1])) ` `                    ``flag = 1; ` `            ``} ` ` `  `            ``// If it is possible to get the answer ` `            ``if` `(flag == 0) { ` `                ``ans.push_back(a[pos]); ` `                ``for` `(``int` `i = 0; i < n; i++) ` `                    ``if` `(i != pos) ` `                        ``ans.push_back(a[i]); ` ` `  `                ``Print(ans); ` `                ``return``; ` `            ``} ` `        ``} ` `    ``} ` ` `  `    ``ans.push_back(-1); ` `    ``Print(ans); ` `} ` ` `  `// Driver code ` `int` `main() ` `{ ` `    ``int` `a[] = { 4, 6, 2, 8, 8 }; ` `    ``int` `n = ``sizeof``(a) / ``sizeof``(a); ` ` `  `    ``Permutation(a, n); ` ` `  `    ``return` `0; ` `} `

## Java

 `// Java implementation of the approach ` `import` `java.util.*; ` ` `  `class` `GFG ` `{ ` ` `  `// Function to find elements of vector ` `static` `void` `Print(Vector ans) ` `{ ` `    ``for` `(Integer i : ans) ` `        ``System.out.print(i + ``" "``); ` `} ` ` `  `// Function to find the lexicographically largest ` `// permutation that satisfies the given condition ` `static` `void` `Permutation(``int` `a[], ``int` `n) ` `{ ` `    ``int` `flag = ``0``, pos = ``0``; ` ` `  `    ``// To store the required ans ` `    ``Vector ans = ``new` `Vector(); ` ` `  `    ``// Sort the array ` `    ``Arrays.sort(a); ` ` `  `    ``for` `(``int` `i = ``2``; i < n; i++)  ` `    ``{ ` ` `  `        ``// If need to make arranagement ` `        ``if` `(a[i] != a[i - ``1``] + __gcd(a[i - ``1``], ` `                                     ``a[i - ``2``])) ` `        ``{ ` `            ``flag = ``1``; ` `            ``pos = i; ` `            ``break``; ` `        ``} ` `    ``} ` ` `  `    ``// If possible then check for lexographically ` `    ``// larger permutation (if any possible) ` `    ``if` `(flag == ``0``) ` `    ``{ ` ` `  `        ``// If larger arrangement is possible ` `        ``if` `(a[``1``] == a[``0``] + __gcd(a[``0``],  ` `                                 ``a[n - ``1``]))  ` `        ``{ ` `            ``ans.add(a[n - ``1``]); ` `            ``for` `(``int` `i = ``0``; i < n - ``1``; i++) ` `                ``ans.add(a[i]); ` ` `  `            ``Print(ans); ` `            ``return``; ` `        ``} ` ` `  `        ``// If no other arrangement is possible ` `        ``else`  `        ``{ ` `            ``for` `(``int` `i = ``0``; i < n; i++) ` `                ``ans.add(a[i]); ` ` `  `            ``Print(ans); ` `            ``return``; ` `        ``} ` `    ``} ` ` `  `    ``// Need to re-arrange the array ` `    ``else`  `    ``{ ` ` `  `        ``// If possible, place at first position ` `        ``if` `(a[``1``] == a[``0``] + __gcd(a[pos], a[``0``]))  ` `        ``{ ` `            ``flag = ``0``; ` `            ``for` `(``int` `i = n - ``1``; i > pos + ``2``; i--) ` `            ``{ ` ` `  `                ``// If even after one arrangement  ` `                ``// its impossible to get ` `                ``// the required array ` `                ``if` `(a[i] != a[i - ``1``] + __gcd(a[i - ``1``],  ` `                                             ``a[i - ``2``])) ` `                ``{ ` `                    ``flag = ``1``; ` `                    ``break``; ` `                ``} ` `            ``} ` ` `  `            ``if` `(flag == ``0` `& pos < n - ``1``)  ` `            ``{ ` ` `  `                ``// If it is not possible to get ` `                ``// the required array ` `                ``if` `(a[pos + ``1``] ` `                    ``!= a[pos - ``1``] + __gcd(a[pos - ``1``],  ` `                                          ``a[pos - ``2``])) ` `                    ``flag = ``1``; ` `            ``} ` ` `  `            ``if` `(flag == ``0` `& pos < n - ``2``)  ` `            ``{ ` ` `  `                ``// If it is not possible to get ` `                ``// the required array ` `                ``if` `(a[pos + ``2``] ` `                    ``!= a[pos + ``1``] + __gcd(a[pos - ``1``],  ` `                                          ``a[pos + ``1``])) ` `                    ``flag = ``1``; ` `            ``} ` ` `  `            ``// If it is possible to get the answer ` `            ``if` `(flag == ``0``) ` `            ``{ ` `                ``ans.add(a[pos]); ` `                ``for` `(``int` `i = ``0``; i < n; i++) ` `                    ``if` `(i != pos) ` `                        ``ans.add(a[i]); ` ` `  `                ``Print(ans); ` `                ``return``; ` `            ``} ` `        ``} ` `    ``} ` ` `  `    ``ans.add(-``1``); ` `    ``Print(ans); ` `} ` ` `  `static` `int` `__gcd(``int` `a, ``int` `b)  ` `{  ` `    ``if` `(b == ``0``)  ` `        ``return` `a;  ` `    ``return` `__gcd(b, a % b);      ` `}  ` ` `  `// Driver code ` `public` `static` `void` `main(String[] args) ` `{ ` `    ``int` `a[] = { ``4``, ``6``, ``2``, ``8``, ``8` `}; ` `    ``int` `n = a.length; ` ` `  `    ``Permutation(a, n); ` `    ``} ` `} ` ` `  `// This code is contributed  ` `// by PrinciRaj1992  `

## Python3

 `# Python 3 implementation of the approach ` `from` `math ``import` `gcd ` ` `  `# Function to find elements of vector ` `def` `Print``(ans): ` `    ``for` `i ``in` `range``(``len``(ans)): ` `        ``print``(ans[i], end ``=` `" "``) ` ` `  `# Function to find the lexicographically  ` `# largest permutation that satisfies  ` `# the given condition ` `def` `Permutation(a, n): ` `    ``flag ``=` `0` ` `  `    ``# To store the required ans ` `    ``ans ``=` `[] ` ` `  `    ``# Sort the array ` `    ``a.sort(reverse ``=` `False``) ` ` `  `    ``for` `i ``in` `range``(``2``, n, ``1``): ` `         `  `        ``# If need to make arranagement ` `        ``if` `(a[i] !``=` `a[i ``-` `1``] ``+`  `        ``gcd(a[i ``-` `1``], a[i ``-` `2``])): ` `            ``flag ``=` `1` `            ``pos ``=` `i ` `            ``break` ` `  `    ``# If possible then check for  ` `    ``# lexographically larger  ` `    ``# permutation (if any possible) ` `    ``if` `(flag ``=``=` `0``): ` `         `  `        ``# If larger arrangement is possible ` `        ``if` `(a[``1``] ``=``=` `a[``0``] ``+`  `        ``gcd(a[``0``], a[n ``-` `1``])): ` `            ``ans.append(a[n ``-` `1``]) ` `            ``for` `i ``in` `range``(n ``-` `1``): ` `                ``ans.append(a[i]) ` ` `  `            ``Print``(ans) ` `            ``return` ` `  `        ``# If no other arrangement is possible ` `        ``else``: ` `            ``for` `i ``in` `range``(n): ` `                ``ans.append(a[i]) ` ` `  `            ``Print``(ans) ` `            ``return` ` `  `    ``# Need to re-arrange the array ` `    ``else``: ` `         `  `        ``# If possible, place at first position ` `        ``if` `(a[``1``] ``=``=` `a[``0``] ``+`  `        ``gcd(a[pos], a[``0``])): ` `            ``flag ``=` `0` `            ``i ``=` `n ``-` `1` `            ``while``(i > pos ``+` `2``): ` `                 `  `                ``# If even after one arrangement its  ` `                ``# impossible to get the required array ` `                ``if` `(a[i] !``=` `a[i ``-` `1``] ``+`  `                ``gcd(a[i ``-` `1``], a[i ``-` `2``])): ` `                    ``flag ``=` `1` `                    ``break` ` `  `                ``i ``-``=` `1` `             `  `            ``if` `(flag ``=``=` `0` `and` `pos < n ``-` `1``): ` `                 `  `                ``# If it is not possible to get ` `                ``# the required array ` `                ``if` `(a[pos ``+` `1``] !``=` `a[pos ``-` `1``] ``+`  `                ``gcd(a[pos ``-` `1``], a[pos ``-` `2``])): ` `                    ``flag ``=` `1` ` `  `            ``if` `(flag ``=``=` `0` `and` `pos < n ``-` `2``): ` `                 `  `                ``# If it is not possible to get ` `                ``# the required array ` `                ``if` `(a[pos ``+` `2``] !``=` `a[pos ``+` `1``] ``+` `                ``gcd(a[pos ``-` `1``], a[pos ``+` `1``])): ` `                    ``flag ``=` `1` ` `  `            ``# If it is possible to get the answer ` `            ``if` `(flag ``=``=` `0``): ` `                ``ans.append(a[pos]) ` `                ``for` `i ``in` `range``(n): ` `                    ``if` `(i !``=` `pos): ` `                        ``ans.append(a[i]) ` ` `  `                ``Print``(ans) ` `                ``return` ` `  `    ``ans.append(``-``1``) ` `    ``Print``(ans) ` ` `  `# Driver code ` `if` `__name__ ``=``=` `'__main__'``: ` `    ``a ``=` `[``4``, ``6``, ``2``, ``8``, ``8``] ` `    ``n ``=` `len``(a) ` ` `  `    ``Permutation(a, n) ` `     `  `# This code is contributed by ` `# Surendra_Gangwar `

## C#

 `// C# implementation of the approach ` `using` `System; ` `using` `System.Collections.Generic;  ` ` `  `class` `GFG ` `{ ` ` `  `// Function to find elements of vector ` `static` `void` `Print(List<``int``> ans) ` `{ ` `    ``foreach` `(``int` `i ``in` `ans) ` `        ``Console.Write(i + ``" "``); ` `} ` ` `  `// Function to find the lexicographically largest ` `// permutation that satisfies the given condition ` `static` `void` `Permutation(``int` `[]a, ``int` `n) ` `{ ` `    ``int` `flag = 0, pos = 0; ` ` `  `    ``// To store the required ans ` `    ``List<``int``> ans = ``new` `List<``int``>(); ` ` `  `    ``// Sort the array ` `    ``Array.Sort(a); ` ` `  `    ``for` `(``int` `i = 2; i < n; i++)  ` `    ``{ ` ` `  `        ``// If need to make arranagement ` `        ``if` `(a[i] != a[i - 1] + __gcd(a[i - 1], ` `                                     ``a[i - 2])) ` `        ``{ ` `            ``flag = 1; ` `            ``pos = i; ` `            ``break``; ` `        ``} ` `    ``} ` ` `  `    ``// If possible then check for lexographically ` `    ``// larger permutation (if any possible) ` `    ``if` `(flag == 0) ` `    ``{ ` ` `  `        ``// If larger arrangement is possible ` `        ``if` `(a == a + __gcd(a,  ` `                                 ``a[n - 1]))  ` `        ``{ ` `            ``ans.Add(a[n - 1]); ` `            ``for` `(``int` `i = 0; i < n - 1; i++) ` `                ``ans.Add(a[i]); ` ` `  `            ``Print(ans); ` `            ``return``; ` `        ``} ` ` `  `        ``// If no other arrangement is possible ` `        ``else` `        ``{ ` `            ``for` `(``int` `i = 0; i < n; i++) ` `                ``ans.Add(a[i]); ` ` `  `            ``Print(ans); ` `            ``return``; ` `        ``} ` `    ``} ` ` `  `    ``// Need to re-arrange the array ` `    ``else` `    ``{ ` ` `  `        ``// If possible, place at first position ` `        ``if` `(a == a + __gcd(a[pos], a))  ` `        ``{ ` `            ``flag = 0; ` `            ``for` `(``int` `i = n - 1; i > pos + 2; i--) ` `            ``{ ` ` `  `                ``// If even after one arrangement  ` `                ``// its impossible to get ` `                ``// the required array ` `                ``if` `(a[i] != a[i - 1] + __gcd(a[i - 1],  ` `                                             ``a[i - 2])) ` `                ``{ ` `                    ``flag = 1; ` `                    ``break``; ` `                ``} ` `            ``} ` ` `  `            ``if` `(flag == 0 & pos < n - 1)  ` `            ``{ ` ` `  `                ``// If it is not possible to get ` `                ``// the required array ` `                ``if` `(a[pos + 1] ` `                    ``!= a[pos - 1] + __gcd(a[pos - 1],  ` `                                          ``a[pos - 2])) ` `                    ``flag = 1; ` `            ``} ` ` `  `            ``if` `(flag == 0 & pos < n - 2)  ` `            ``{ ` ` `  `                ``// If it is not possible to get ` `                ``// the required array ` `                ``if` `(a[pos + 2] ` `                    ``!= a[pos + 1] + __gcd(a[pos - 1],  ` `                                          ``a[pos + 1])) ` `                    ``flag = 1; ` `            ``} ` ` `  `            ``// If it is possible to get the answer ` `            ``if` `(flag == 0) ` `            ``{ ` `                ``ans.Add(a[pos]); ` `                ``for` `(``int` `i = 0; i < n; i++) ` `                    ``if` `(i != pos) ` `                        ``ans.Add(a[i]); ` ` `  `                ``Print(ans); ` `                ``return``; ` `            ``} ` `        ``} ` `    ``} ` ` `  `    ``ans.Add(-1); ` `    ``Print(ans); ` `} ` ` `  `static` `int` `__gcd(``int` `a, ``int` `b)  ` `{  ` `    ``if` `(b == 0)  ` `        ``return` `a;  ` `    ``return` `__gcd(b, a % b);      ` `}  ` ` `  `// Driver code ` `public` `static` `void` `Main(String[] args) ` `{ ` `    ``int` `[]a = { 4, 6, 2, 8, 8 }; ` `    ``int` `n = a.Length; ` ` `  `    ``Permutation(a, n); ` `    ``} ` `} ` ` `  `// This code is contributed by Rajput-Ji `

Output:

```8 2 4 6 8
```

Time complexity: O(NlogN)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

3

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.