C# || How To Generate Unique Permutations From Array With Duplicate Values Using C#

Print Friendly, PDF & Email

The following is a module with functions which demonstrates how to generate unique permutations from an array with duplicate values using C#.


1. Permute Unique – Problem Statement

Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

Example 1:


Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]

Example 2:


Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]


2. Permute Unique – Solution

The following is a solution which demonstrates how to generate unique permutations from an array with duplicate values.

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:


[[1,1,2],[1,2,1],[2,1,1]]
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Was this article helpful?
👍 YesNo

Leave a Reply