Place first N natural numbers at indices not equal to their values in an array
Last Updated :
30 Aug, 2022
Given an integer N(N > 1), the task is to arrange all integers from the range [1, N] in an array such that none of the elements are same as the index (1-based indexing) in which they are present in the array.
Examples:
Input: N = 2
Output: 2 1
Explanation: Only possible arrangement of an array of size 2 is 2 1.
Input: N=5
Output: 2 1 5 3 4
Explanation: One possible arrangement of an array of size 5 is 2 1 5 3 4l.
Approach: The simplest idea is to place N at the first index and place the remaining elements [1, N – 1] in the remaining indices.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void generatepermutation( int N)
{
vector< int > answer;
answer.push_back(N);
for ( int i = 1; i < N; i++)
{
answer.push_back(i);
}
for ( int i:answer) cout << i << " " ;
}
int main()
{
int N = 4;
generatepermutation(N);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void generatepermutation( int N)
{
Vector<Integer> answer = new Vector<Integer>();
answer.add(N);
for ( int i = 1 ; i < N; i++)
{
answer.add(i);
}
for ( int i:answer) System.out.print(i+ " " );
}
public static void main(String[] args)
{
int N = 4 ;
generatepermutation(N);
}
}
|
Python3
def generatepermutation(N):
answer = []
answer.append(N)
for i in range ( 1 , N):
answer.append(i)
print ( * answer)
N = 4
generatepermutation(N)
|
C#
using System;
class GFG
{
static void generatepermutation( int N)
{
int [] answer = new int [N];
answer[0] = N;
for ( int i = 1; i < N; i++)
{
answer[i] = i;
}
foreach ( int i in answer) Console.Write(i+ " " );
}
static public void Main ()
{
int N = 4;
generatepermutation(N);
}
}
|
Javascript
<script>
function generatepermutation(N)
{
var answer = [];
answer.push(N);
console.log(answer);
for ( var i = 1; i < N; i++) {
console.log(answer);
answer.push(i);
}
for ( var i in answer)
document.write(answer[i] + " " );
}
var N = 4;
generatepermutation(N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N) because using extra space for vector
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...