|
| 1 | +# Triangle Numbers |
| 2 | + |
| 3 | +Write a function to count the number of triplets in an integer array nums that could form the sides of a triangle. For |
| 4 | +three sides to form a valid triangle, the sum of any two sides must be greater than the third side. The triplets do not |
| 5 | +need to be unique. |
| 6 | + |
| 7 | +## Examples |
| 8 | + |
| 9 | +```text |
| 10 | +Input: |
| 11 | +nums = [11,4,9,6,15,18] |
| 12 | +
|
| 13 | +Output: |
| 14 | +10 |
| 15 | +
|
| 16 | +Explanation: Valid combinations are... |
| 17 | +
|
| 18 | +4, 15, 18 |
| 19 | +6, 15, 18 |
| 20 | +9, 15, 18 |
| 21 | +11, 15, 18 |
| 22 | +9, 11, 18 |
| 23 | +6, 11, 15 |
| 24 | +9, 11, 15 |
| 25 | +4, 6, 9 |
| 26 | +``` |
| 27 | + |
| 28 | +## Solution |
| 29 | + |
| 30 | +In order for a triplet to be valid lengths of a triangle, the sum of any two sides must be greater than the third side. |
| 31 | +By sorting the array, we can leverage the two-pointer technique to count all valid triplets in O(n2) time and O(1) space. |
| 32 | +The key to this question is realizing that if we sort three numbers from smallest to largest (say a ≤ b ≤ c), we only |
| 33 | +need to check if a + b > c. If this condition holds, the other two conditions (a + c > b and b + c > a) are automatically |
| 34 | +satisfied because c ≥ b and b ≥ a. For example, with 4, 8, 9, if 4 + 8 > 9 is true, then we have a valid triplet. |
| 35 | + |
| 36 | + |
| 37 | + |
| 38 | +But not only that, triplets where the smallest number is between 4 and 8 are also valid triplets. |
| 39 | + |
| 40 | + |
| 41 | + |
| 42 | +This means that if we sort the input array, and then iterate from the end of the array to the beginning, we can use the |
| 43 | +two-pointer technique to efficiently count all valid triplets. |
| 44 | + |
| 45 | + |
| 46 | + |
| 47 | +The pointers i, left, and right represent the current triplet we are considering. If nums[left] + nums[right] > nums[i] |
| 48 | +then we know there are a total of right - left valid triplets, since all triplets between left and right are also valid |
| 49 | +triplets. We can then decrement right to check for the valid triplets that can be made by decreasing the middle value. |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | + |
| 56 | +When nums[left] + nums[right] < nums[i], we know that all triplets between left and right are also invalid, so we |
| 57 | +increment left to look for a larger smallest value. |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | +Each time left and right cross, we decrement i and reset left and right to their positions at opposite ends of the array. |
| 62 | +This happens until i is less than 2, at which point we have counted all valid triplets. |
| 63 | + |
| 64 | + |
| 65 | + |
| 66 | + |
| 67 | + |
| 68 | + |
| 69 | + |
| 70 | + |
| 71 | + |
| 72 | + |
| 73 | + |
| 74 | + |
| 75 | + |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | + |
| 80 | + |
| 81 | + |
| 82 | + |
| 83 | + |
0 commit comments