0

There was one problem:

Given a natural number sequence S of size n, [1,2,3,4....n], the task is to generate n random permutations but the catch is that the values shouldn't repeat at any index among all permutations.

For example, given n=3, S=[1,2,3], the possible result can be

1.[3,1,2]

2.[2,3,1]

3.[1,2,3]

Output like below is not acceptable as permutation 1 and 3 have same second value as 1

1.[3,1,2]

2.[2,3,1]

3.[2,1,3]

Another restriction was this needs to be solved with O(n) space complexity.

dh1
  • 97
  • 1
  • 9
  • And what's your question about this? How is this related to programming? – Nico Haase Feb 22 '22 at 09:45
  • Add your current approach as well – Abhinav Mathur Feb 22 '22 at 10:37
  • 1
    A simple rotation will suffice, given that there are no repeats in the original number sequence. Each output is the previous out[ut shifted by one. – rossum Feb 22 '22 at 13:39
  • What distribution do you need to achieve in your randomness? Do you need to generate uniformly from the solution space? Does the support need to be the entire solution space? – Sneftel Feb 22 '22 at 13:39
  • 1
    As you can see from the duplicates, the main thing is to know that this kind of permutation is called a "derangement". That's easy to search for. – rici Feb 22 '22 at 14:05
  • By randomness I only meant there is no way to pre-determine what sequences will be resulted, and in what order. – dh1 Feb 22 '22 at 14:29
  • @rici thanks, that term will help! – dh1 Feb 22 '22 at 14:42
  • Adding to my previous comment: if you want randomness then first do a systematic row-by-row rotation to get an n x n grid. Then randomly shuffle the columns in the grid, followed by a random shuffle of the rows. That will preserve the properties you want while appearing random. – rossum Feb 22 '22 at 14:56

0 Answers0