0

This is my first question on StackOverflow.

I need to find unique permutations of size n which will have unique elements. I have already written a logic for that (for now it is limited to size 3), but it is slow, as in the worst case, it gives n*n*n complexity. Also it won't work for size more than 3.

What should I do in order to reduce the complexity, and make it work for any size of permutation?

Example:
Input :
ABCD

Output :
A B C
A B D
A C D
B C D
(Adding the list to a set will improve the speed a little bit, but it won't affect the time complexity for a list with less number of duplicates).

Here's my code:

Set<String> permute(List<String> input, int limit) {
    Set<String> one = new HashSet<>();
    Set<String> two = new HashSet<>();
    Set<String> three = new HashSet<>();

    for (int i = 0; limit > 0 && i < input.size(); i++) {
        one.add(input.get(i));

        for (int j = i + 1; limit > 1 && j < input.size(); j++) {
            String temp = input.get(i) + "-" + input.get(j);
            two.add(temp);

            for (int k = j + 1; limit > 2 && k < input.size(); k++) {
                temp = input.get(i) + "-" + input.get(j) + "-" + input.get(k);
                three.add(temp);
            }
        }
    }

    switch(limit) {
        case 1:
            return one;
        case 2:
            return two;
        case 3:
            return three;
        default:
            return new HashSet<>(); 
    }
}

Thanks

  • I advice to put a clear question in your question. – Absurd-Mind Sep 13 '17 at 12:10
  • Why not remove the duplicates first (if you are really talkin about permutations; i did not check the code)? – sascha Sep 13 '17 at 12:15
  • Ohh, okay. I can dump the list into a Set, but it will still be a high complexity algorithm. Could you please suggest me what should be done in order to reduce the complexity ? – Sampada Kulkarni Sep 13 '17 at 12:41
  • 1
    Your example is not really a [permutation](https://en.wikipedia.org/wiki/Permutation) and every algorithm generating permutations will be of complexity O(n!) as there are n! permutations. Maybe you want to generate a k-permutation, or a combination?. But these are growing fast too. – sascha Sep 13 '17 at 12:58
  • yes, k-permutation. But my implementation will work only upto 3. I will have to put that number of nested for loops, which definitely won't be optimal. – Sampada Kulkarni Sep 13 '17 at 13:02
  • Your example does more look like a combination. And for that, the duplicate-link is valid. So improve the question. – sascha Sep 13 '17 at 13:52
  • ABC=1110, ABD=1101, ACD=1011, BCD=0111. There are several ways to efficiently generate all x-bit numbers with y bits set. – m69's been on strike for years Sep 13 '17 at 15:13
  • Thank you, that link solved my problem. – Sampada Kulkarni Sep 14 '17 at 06:06

0 Answers0