Lexicographically largest array possible from first N natural numbers such that every repetition is present at distance equal to its value from its previous occurrence
Last Updated :
16 Aug, 2021
Given a positive integer N, the task is to construct the lexicographically largest array of size (2 * N – 1) comprising of first N natural numbers such that each element occurs twice except 1 and the repetition of X is exactly X distance apart in the constructed array.
Examples:
Input: N = 4
Output: 4 2 3 2 4 3 1
Explanation:
For the generated array {4, 2, 3, 2, 4, 3, 1} each duplicate element(say X) is at distance X.
Input: N = 5
Output: 5 3 1 4 3 5 2 4 2
Approach: The problem can be solved using Backtracking. The idea is to generate all possible permutations as per the given condition and print the one that satisfies the given conditions. Follow the steps below to solve the problem:
- Initialize an array, say ans[], of size (2*N – 1) 0s at every index and a HashMap to store all the elements assigned to the constructed array.
- Define a function constructedArray(i, N) to generate the resultant array by performing following steps:
- If the value of i is (2*N – 1), then one of the possible permutations is generated. Therefore, return true.
- Otherwise, if the value at the current index is already assigned, then recursively call for the next iteration constructArray(i+1, N).
- Otherwise, perform the following:
- Place every unvisited number from the range[1, N] starting from N.
- If the value chosen in the above step doesn’t lead to a possible combination of the array, then remove the current value from the array and try other possible combinations by assigning other elements from the range.
- If no possible combination is obtained, then return false.
- After completing the above steps, print the array ans[] as obtained.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
const int N = 4;
vector< int > ans(2 * N - 1, 0);
set< int > visited;
bool constructArray( int i)
{
if (i == ans.size()) {
return true ;
}
if (ans[i] != 0)
return constructArray(i + 1);
else {
for ( int val = N; val >= 1; val--) {
if (visited.find(val) != visited.end())
continue ;
visited.insert(val);
ans[i] = val;
if (val == 1) {
bool found = constructArray(i + 1);
if (found)
return true ;
}
else if (i + val < ans.size()
&& ans[i + val] == 0) {
ans[val + i] = val;
bool found = constructArray(i + 1);
if (found)
return true ;
ans[i + val] = 0;
}
ans[i] = 0;
visited.erase(val);
}
}
return false ;
}
int main()
{
constructArray(0);
for ( int X : ans)
cout << X << " " ;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static int ans[];
static HashSet<Integer> visited;
public static boolean
constructArray( int i, int N)
{
if (i == ans.length) {
return true ;
}
if (ans[i] != 0 )
return constructArray(i + 1 , N);
else {
for ( int val = N; val >= 1 ; val--) {
if (visited.contains(val))
continue ;
visited.add(val);
ans[i] = val;
if (val == 1 ) {
boolean found
= constructArray(i + 1 , N);
if (found)
return true ;
}
else if (i + val < ans.length
&& ans[i + val] == 0 ) {
ans[val + i] = val;
boolean found
= constructArray(i + 1 , N);
if (found)
return true ;
ans[i + val] = 0 ;
}
ans[i] = 0 ;
visited.remove(val);
}
}
return false ;
}
public static void main(String[] args)
{
int N = 4 ;
ans = new int [ 2 * N - 1 ];
visited = new HashSet<>();
constructArray( 0 , N);
for ( int X : ans)
System.out.print(X + " " );
}
}
|
Python3
def constructArray(i, N):
global ans, visited
if (i = = len (ans)):
return True
if (ans[i] ! = 0 ):
return constructArray(i + 1 , N)
else :
for val in range (N, 0 , - 1 ):
if (val in visited):
continue
visited[val] = 1
ans[i] = val
if (val = = 1 ):
found = constructArray(i + 1 , N)
if (found):
return True
elif (i + val < len (ans) and ans[i + val] = = 0 ):
ans[val + i] = val
found = constructArray(i + 1 , N)
if (found):
return True
ans[i + val] = 0
ans[i] = 0
del visited[val]
return False
if __name__ = = '__main__' :
N = 4
ans = [ 0 ] * ( 2 * N - 1 )
visited = {}
constructArray( 0 , N)
for x in ans:
print (x,end = " " )
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG{
static int [] ans;
static HashSet< int > visited;
public static bool
constructArray( int i, int N)
{
if (i == ans.Length) {
return true ;
}
if (ans[i] != 0)
return constructArray(i + 1, N);
else {
for ( int val = N; val >= 1; val--) {
if (visited.Contains(val))
continue ;
visited.Add(val);
ans[i] = val;
if (val == 1) {
bool found
= constructArray(i + 1, N);
if (found)
return true ;
}
else if (i + val < ans.Length
&& ans[i + val] == 0) {
ans[val + i] = val;
bool found
= constructArray(i + 1, N);
if (found)
return true ;
ans[i + val] = 0;
}
ans[i] = 0;
visited.Remove(val);
}
}
return false ;
}
static public void Main()
{
int N = 4;
ans = new int [2 * N - 1];
visited = new HashSet< int >();
constructArray(0, N);
foreach ( int X in ans)
Console.Write(X + " " );
}
}
|
Javascript
<script>
var ans = [];
var visited = [];
function constructArray(i, N) {
if (i === ans.length) {
return true ;
}
if (ans[i] !== 0) return constructArray(i + 1, N);
else {
for ( var val = N; val >= 1; val--) {
if (visited.includes(val)) continue ;
visited.push(val);
ans[i] = val;
if (val === 1) {
var found = constructArray(i + 1, N);
if (found) return true ;
}
else if (i + val < ans.length && ans[i + val] === 0) {
ans[val + i] = val;
var found = constructArray(i + 1, N);
if (found) return true ;
ans[i + val] = 0;
}
ans[i] = 0;
var index = visited.indexOf(val);
if (index !== -1) {
visited.splice(index, 1);
}
}
}
return false ;
}
var N = 4;
ans = new Array(2 * N - 1).fill(0);
visited = [];
constructArray(0, N);
for (const X of ans) {
document.write(X + " " );
}
</script>
|
Time Complexity: O(N!)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...