Search code examples
arraysfunctiontriplet

Find unique triplets


In my function I have to find all unique triplets to given numbers K from given array. It finds all triplets but many of them are there twice or more like 1 1 5 is same as 1 5 1 or 5 1 1 and etc.

Can somebody help me with this?

int triplet(int *array, int size, int K) {
  int i, j, k;
  int found = 0; /* triplets whose sum is equal to K */
  for(i = 0; i < size; i++) {
    for (j = 0; j < size; j++) {    
      for (k = 0; k < size; k++) {
        if(array[i] + array[j] + array[k] == K) {
          printf("Triplet Found : %d, %d, %d\n", array[i], array[j], array[k]);
          found++;
        }           
      }
    }
  }
  return found;
}

Solution

  • You should not repeat already processed combinations; a possible solution would be to start each for cycle from de previous ID + 1, like so:

    for(i = 0; i < size; i++) {
     for (j = i+1; j < size; j++) {    
      for (k = j+1; k < size; k++) {
        if(array[i] + array[j] + array[k] == K) {
          printf("Triplet Found : %d, %d, %d\n", array[i], array[j], array[k]);
          found++;
        }           
      }
    }
    

    setting j = i + 1; you prevent same-element triplets!