You are not logged in. Please login at to post your questions!


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. :)

asked 12 Oct '14, 14:10

rishabh_gour's gravatar image

accept rate: 0%

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.


answered 13 Oct '14, 00:36

aakashc31's gravatar image

accept rate: 27%

toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text]( "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:


question asked: 12 Oct '14, 14:10

question was seen: 959 times

last updated: 13 Oct '14, 00:36