Find Permutation

You are given an integer ‘N’. You need to find an array of size 2*N that satisfies the following two conditions.

1. All numbers from 1 to N should appear exactly twice in the array.

2. The distance between the second occurrence and the first occurrence of any number should exactly be equal to the value of that number.

The distance between two numbers at indices ‘i’ and ‘j’ is defined as (j-i-1) where i < j.

If no such array exists, then you should return an empty array.

For example :
For N = 3 one valid array is [3,1,2,1,3,2].
Input Format :
The first line of input contains an integer ‘T’, denoting the number of test cases. The test cases follow.

The first and the only line of each test case contains a single integer ‘N’.
Output Format :
The checker will print “Valid” if the returned permutation is valid and follows all the conditions, otherwise, it will print “Invalid”. If an empty array is returned, the checker will print -1.

Print the output of each test case in a new line.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1<= T <= 5
1 <= N <= 8

where ’T’ is the number of test cases and ‘N’  is the given integer.

Time Limit: 1 sec
CodingNinjas
author
2y
Brute Force

The idea is to make an array with exactly two occurrences of each element from 1 to N. Then we will generate all possible permutations of this array and check if any permutation is valid or...read more

CodingNinjas
author
2y
Backtracking based Approach

This approach is similar to the previous approach but the idea is to carry on the recursion forward only if there are exactly k number of elements between both the occurrenc...read more

Help your peers!
Add answer anonymously...
JPMorgan Chase & Co. Machine Learning Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter