how can i decrease complexity of this part of code??

this code prints a combination of elememts present in an array “pts” (4 elements at atime) in such a way that a particular combination of digits never occurs more than once… eg. if 1 2 3 4 is printed already then none of its permutations should get printed.

for (int i = 0; i < pts.length; i++) {

		for (int j = i+1; j < pts.length; j++) {

			for (int k = j+1; k < pts.length; k++) {

				for (int l = k+1; l < pts.length; l++) {
					System.out.println(""+i+" "+j+" "+k+" "+l);

if anyone can suggest some other approach or can tell me how to reduce this code’s complexity… I shall be thankful. :slight_smile:

The number of solutions of this problem is in worst case C(n,4) (Number of ways of selecting four elements from a set of n elements). This is O(n^4). Since the number of solutions is O(n^4), which you have to generate, you cannot improve the worst case complexity.

To avoid printing permutations of the same group of four numbers, first sort the array. Now, the numbers generated by the four nested “for loops” written above, will be in sorted order. So, if any repetitions occur, they will occur consecutively. You will need to store the last group of numbers printed. If the current group is same as the previous group, don’t print it. If they are unequal, print the current group, and update the previous group.

1 Like