|
| 1 | +--- |
| 2 | +id: valid-triangle-number |
| 3 | +title: Valid Triangle Number |
| 4 | +sidebar_label: 0611 - Valid Triangle Number |
| 5 | +tags: |
| 6 | + - Two Pointers |
| 7 | + - Sorting |
| 8 | + - Binary Tree |
| 9 | +description: "This is a solution to the Valid Triangle Number problem on LeetCode." |
| 10 | +--- |
| 11 | + |
| 12 | +## Problem Description |
| 13 | + |
| 14 | +Given an integer array `nums`, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. |
| 15 | + |
| 16 | +### Examples |
| 17 | + |
| 18 | +**Example 1:** |
| 19 | + |
| 20 | +``` |
| 21 | +Input: nums = [2,2,3,4] |
| 22 | +Output: 3 |
| 23 | +Explanation: Valid combinations are: |
| 24 | +2,3,4 (using the first 2) |
| 25 | +2,3,4 (using the second 2) |
| 26 | +2,2,3 |
| 27 | +``` |
| 28 | + |
| 29 | +**Example 2:** |
| 30 | + |
| 31 | +``` |
| 32 | +Input: nums = [4,2,3,4] |
| 33 | +Output: 4 |
| 34 | +``` |
| 35 | + |
| 36 | +### Constraints |
| 37 | + |
| 38 | +- `1 <= nums.length <= 1000` |
| 39 | +- `0 <= nums[i] <= 1000` |
| 40 | + |
| 41 | +## Solution for Valid Triangle Number |
| 42 | + |
| 43 | +### Approach #1 Brute Force [Time Limit Exceeded] |
| 44 | + |
| 45 | +The condition for the triplets (a,b,c) representing the lengths of the sides of a triangle, to form a valid triangle, is that the sum of any two sides should always be greater than the third side alone. i.e. a+b>c, b+c>a, a+c>b. |
| 46 | + |
| 47 | +The simplest method to check this is to consider every possible triplet in the given nums array and checking if the triplet satisfies the three inequalities mentioned above. Thus, we can keep a track of the count of the number of triplets satisfying these inequalities. When all the triplets have been considered, the count gives the required result. |
| 48 | + |
| 49 | +> Caution: The brute force approach is included here because it is an intuitive way to approach this problem. However, when there are $10^3$ numbers, the if statement will be checked approximately $10^9$ times. Thus, this approach will result in TLE. In the following approaches we will discuss ways to optimize our solution. |
| 50 | +
|
| 51 | +## Code in Different Languages |
| 52 | + |
| 53 | +<Tabs> |
| 54 | +<TabItem value="cpp" label="C++"> |
| 55 | + <SolutionAuthor name="@Shreyash3087"/> |
| 56 | + |
| 57 | +```cpp |
| 58 | +#include <vector> |
| 59 | + |
| 60 | +class Solution { |
| 61 | +public: |
| 62 | + int triangleNumber(std::vector<int>& nums) { |
| 63 | + int count = 0; |
| 64 | + for (size_t i = 0; i < nums.size() - 2; i++) { |
| 65 | + for (size_t j = i + 1; j < nums.size() - 1; j++) { |
| 66 | + for (size_t k = j + 1; k < nums.size(); k++) { |
| 67 | + if (nums[i] + nums[j] > nums[k] && |
| 68 | + nums[i] + nums[k] > nums[j] && |
| 69 | + nums[j] + nums[k] > nums[i]) { |
| 70 | + count++; |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + return count; |
| 76 | + } |
| 77 | +}; |
| 78 | + |
| 79 | +``` |
| 80 | +</TabItem> |
| 81 | +<TabItem value="java" label="Java"> |
| 82 | + <SolutionAuthor name="@Shreyash3087"/> |
| 83 | +
|
| 84 | +```java |
| 85 | +class Solution { |
| 86 | + public int triangleNumber(int[] nums) { |
| 87 | + int count = 0; |
| 88 | + for (int i = 0; i < nums.length - 2; i++) { |
| 89 | + for (int j = i + 1; j < nums.length - 1; j++) { |
| 90 | + for (int k = j + 1; k < nums.length; k++) { |
| 91 | + if (nums[i] + nums[j] > nums[k] && |
| 92 | + nums[i] + nums[k] > nums[j] && |
| 93 | + nums[j] + nums[k] > nums[i]) { |
| 94 | + count++; |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + } |
| 99 | + return count; |
| 100 | + } |
| 101 | +} |
| 102 | +``` |
| 103 | + |
| 104 | +</TabItem> |
| 105 | +<TabItem value="python" label="Python"> |
| 106 | + <SolutionAuthor name="@Shreyash3087"/> |
| 107 | + |
| 108 | +```python |
| 109 | +class Solution: |
| 110 | + def triangleNumber(self, nums): |
| 111 | + count = 0 |
| 112 | + for i in range(len(nums) - 2): |
| 113 | + for j in range(i + 1, len(nums) - 1): |
| 114 | + for k in range(j + 1, len(nums)): |
| 115 | + if nums[i] + nums[j] > nums[k] and \ |
| 116 | + nums[i] + nums[k] > nums[j] and \ |
| 117 | + nums[j] + nums[k] > nums[i]: |
| 118 | + count += 1 |
| 119 | + return count |
| 120 | +``` |
| 121 | +</TabItem> |
| 122 | +</Tabs> |
| 123 | + |
| 124 | +## Complexity Analysis |
| 125 | + |
| 126 | +### Time Complexity: $O(N^3)$ |
| 127 | + |
| 128 | +> **Reason**: Three nested loops are there to check every triplet. |
| 129 | + |
| 130 | +### Space Complexity: $O(1)$ |
| 131 | + |
| 132 | +> **Reason**: Constant space is used. |
| 133 | + |
| 134 | +### Approach #2 Using Binary Search |
| 135 | +#### Algorithm |
| 136 | + |
| 137 | +If we sort the given `nums` array once, we can solve the problem more efficiently. This is because if we consider a triplet `(a, b, c)` such that $$a \leq b \leq c$$, we need not check all three inequalities for the validity of the triangle formed by them. Only the condition $$a + b > c$$ is necessary. This happens because $$c \geq b$$ and $$c \geq a$$. Thus, adding any number to c will always produce a sum greater than either a or b considered alone. Therefore, the inequalities $$c + a > b$$ and $$c + b > a$$ are satisfied implicitly by the property $$a < b < c$$. |
| 138 | + |
| 139 | +From this, we get the idea that we can sort the given `nums` array. Then, for every pair `(nums[i], nums[j])` considered from the beginning of the array, such that $$j > i$$ (leading to $$nums[j] \geq nums[i]$$, we can find the count of elements `nums[k]` (where $$k > j$$), which satisfy the inequality $$nums[k] > nums[i] + nums[j]$$. We can do this for every pair (i, j) considered to get the required result. |
| 140 | + |
| 141 | +We can also observe that, since we've sorted the `nums` array, as we traverse towards the right for choosing the index `k` (for number `nums[k]`), the value of `nums[k]` could increase or remain the same (doesn't decrease relative to the previous value). Thus, there will exist a right limit on the value of index `k`, such that the elements satisfy $$nums[k] > nums[i] + nums[j]$$. Any elements beyond this value of `k` won't satisfy this inequality as well, which is obvious. |
| 142 | + |
| 143 | +Thus, if we can find this right limit value of `k` (indicating the element just greater than $$nums[i] + nums[j]$$), we can conclude that all the elements in the `nums` array in the range $$(j + 1, k - 1)$$ (both included) satisfy the required inequality. Thus, the count of elements satisfying the inequality will be given by $$k - j - 1$$. |
| 144 | + |
| 145 | +Since the `nums` array has been sorted, we can use Binary Search to find this right limit of `k`. |
| 146 | + |
| 147 | +Another point to be observed is that once we find a right limit index $$k_{(i,j)}$$ for a particular pair (i,j) chosen, when we choose a higher value of j for the same value of i, we need not start searching for the right limit $$k_{(i,j+1)}$$ from the index j+2j. Instead, we can start off from the index $$k_{(i,j)}$$ directly where we left off for the last j chosen. |
| 148 | + |
| 149 | +This holds correct because when we choose a higher value of j(higher or equal nums[j] than the previous one), all the nums[k], such that $$k < k_{(i,j)}$$ will obviously satisfy nums[i]+nums[j]>nums[k] for the new value of j chosen. |
| 150 | + |
| 151 | +By taking advantage of this observation, we can limit the range of Binary Search for k to shorter values for increasing values of j considered while choosing the pairs (i,j). |
| 152 | + |
| 153 | +## Code in Different Languages |
| 154 | + |
| 155 | +<Tabs> |
| 156 | + |
| 157 | +<TabItem value="java" label="Java"> |
| 158 | + <SolutionAuthor name="@Shreyash3087"/> |
| 159 | + |
| 160 | +```java |
| 161 | +public class Solution { |
| 162 | + int binarySearch(int nums[], int l, int r, int x) { |
| 163 | + while (r >= l && r < nums.length) { |
| 164 | + int mid = (l + r) / 2; |
| 165 | + if (nums[mid] >= x) |
| 166 | + r = mid - 1; |
| 167 | + else |
| 168 | + l = mid + 1; |
| 169 | + } |
| 170 | + return l; |
| 171 | + } |
| 172 | + public int triangleNumber(int[] nums) { |
| 173 | + int count = 0; |
| 174 | + Arrays.sort(nums); |
| 175 | + for (int i = 0; i < nums.length - 2; i++) { |
| 176 | + int k = i + 2; |
| 177 | + for (int j = i + 1; j < nums.length - 1 && nums[i] != 0; j++) { |
| 178 | + k = binarySearch(nums, k, nums.length - 1, nums[i] + nums[j]); |
| 179 | + count += k - j - 1; |
| 180 | + } |
| 181 | + } |
| 182 | + return count; |
| 183 | + } |
| 184 | +} |
| 185 | + |
| 186 | +``` |
| 187 | + |
| 188 | +</TabItem> |
| 189 | +<TabItem value="python" label="Python"> |
| 190 | + <SolutionAuthor name="@Shreyash3087"/> |
| 191 | + |
| 192 | +```python |
| 193 | +class Solution: |
| 194 | + def binary_search(self, nums, l, r, x): |
| 195 | + while r >= l and r < len(nums): |
| 196 | + mid = (l + r) // 2 |
| 197 | + if nums[mid] >= x: |
| 198 | + r = mid - 1 |
| 199 | + else: |
| 200 | + l = mid + 1 |
| 201 | + return l |
| 202 | + |
| 203 | + def triangleNumber(self, nums): |
| 204 | + count = 0 |
| 205 | + nums.sort() |
| 206 | + for i in range(len(nums) - 2): |
| 207 | + k = i + 2 |
| 208 | + for j in range(i + 1, len(nums) - 1): |
| 209 | + if nums[i] == 0: |
| 210 | + continue |
| 211 | + k = self.binary_search(nums, k, len(nums) - 1, nums[i] + nums[j]) |
| 212 | + count += k - j - 1 |
| 213 | + return count |
| 214 | + |
| 215 | +``` |
| 216 | +</TabItem> |
| 217 | +</Tabs> |
| 218 | + |
| 219 | +## Complexity Analysis |
| 220 | + |
| 221 | +### Time Complexity: $O(n^2logn)$ |
| 222 | + |
| 223 | +> **Reason**: In worst case inner loop will take nlogn (binary search applied N times). |
| 224 | + |
| 225 | +### Space Complexity: $O(logn)$ |
| 226 | + |
| 227 | +> **Reason**: Sorting takes O(logn) space. |
| 228 | + |
| 229 | +## References |
| 230 | + |
| 231 | +- **LeetCode Problem**: [Valid Triangle Number](https://leetcode.com/problems/valid-triangle-number/description/) |
| 232 | + |
| 233 | +- **Solution Link**: [Valid Triangle Number](https://leetcode.com/problems/valid-triangle-number/solutions/) |
0 commit comments