Skip to content

Commit 7e33f9e

Browse files
committed
added UniquePermutations algorithm with test cases
1 parent 0d68b65 commit 7e33f9e

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.thealgorithms.Recursion;
2+
3+
public class UniquePermutations {
4+
throw new UnsupportedOperationException("Utility class");
5+
6+
7+
public static List<String> getUniquePermutations(String str) {
8+
List<String> result = new ArrayList<>();
9+
boolean[] used = new boolean[str.length()];
10+
char[] chars = str.toCharArray();
11+
StringBuilder currentPermutation = new StringBuilder();
12+
generatePermutations(chars, used, currentPermutation, result);
13+
return result;
14+
}
15+
16+
private static void generatePermutations(char[] chars, boolean[] used, StringBuilder currentPermutation, List<String> result) {
17+
if (currentPermutation.length() == chars.length) {
18+
result.add(currentPermutation.toString());
19+
return;
20+
}
21+
22+
for (int i = 0; i < chars.length; i++) {
23+
if (used[i] || (i > 0 && chars[i] == chars[i - 1] && !used[i - 1])) {
24+
continue;
25+
}
26+
used[i] = true;
27+
currentPermutation.append(chars[i]);
28+
generatePermutations(chars, used, currentPermutation, result);
29+
used[i] = false;
30+
currentPermutation.deleteCharAt(currentPermutation.length() - 1);
31+
}
32+
}
33+
}
34+
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.thealgorithms.recursion;
2+
3+
import org.junit.jupiter.api.Test;
4+
import java.util.List;
5+
import static org.junit.jupiter.api.Assertions.assertEquals;
6+
7+
public class UniquePermutationsTest {
8+
9+
@Test
10+
void testUniquePermutations() {
11+
String str = "abc";
12+
List<String> expected = List.of("abc", "acb", "bac", "bca", "cab", "cba");
13+
List<String> result = UniquePermutations.getUniquePermutations(str);
14+
assertEquals(expected.size(), result.size());
15+
assertEquals(expected, result);
16+
}
17+
18+
@Test
19+
void testUniquePermutationsWithDuplicates() {
20+
String str = "aab";
21+
List<String> expected = List.of("aab", "aba", "baa");
22+
List<String> result = UniquePermutations.getUniquePermutations(str);
23+
assertEquals(expected.size(), result.size());
24+
assertEquals(expected, result);
25+
}
26+
27+
@Test
28+
void testEmptyString() {
29+
String str = "";
30+
List<String> result = UniquePermutations.getUniquePermutations(str);
31+
assertEquals(1, result.size()); // only 1 permutation which is an empty string
32+
}
33+
34+
@Test
35+
void testSingleCharacter() {
36+
String str = "a";
37+
List<String> result = UniquePermutations.getUniquePermutations(str);
38+
assertEquals(1, result.size());
39+
assertEquals("a", result.get(0));
40+
}
41+
}

0 commit comments

Comments
 (0)