fueanta

Triplet in array that sum to a given value.

Mar 13th, 2020
151
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. // Write a function that finds a triplet from an array that sum to a given value.
  4. // Complexity: O(n2)
  5.  
  6. function findTriplet($array, $sum)
  7. {
  8.     if (count($array) < 3) return null;
  9.  
  10.     for ($i = 0; $i < count($array) - 2; $i++) {
  11.         $firstItem = $array[$i];
  12.         $seenList = [];
  13.  
  14.         for ($j = $i + 1; $j < count($array); $j++) {
  15.             $thirdItem = $array[$j];
  16.             $secondItem = $sum - ($firstItem + $thirdItem);
  17.  
  18.             if (isset($seenList[$secondItem])) {
  19.                 return [$firstItem, $secondItem, $thirdItem];
  20.             }
  21.  
  22.             $seenList[$thirdItem] = '';
  23.         }
  24.     }
  25.  
  26.     return null;
  27. }
RAW Paste Data