Solution: Valid Triangle Number
Let’s solve the Valid Triangle Number problem using the Sort and Search pattern.
We'll cover the following
Statement
Given an array of integers, nums
, determine the number of unique triplets that can be selected from the array such that the selected values can form the sides of a
Constraints:
nums.length
nums[i]
Solution
The solution uses the sort and search pattern to count the number of valid triangles formed from a given set of numbers. The triangle inequality rule states that a triangle is valid if the sum of the two smaller sides is greater than the largest. Sorting the array in ascending order simplifies the problem, as the largest side in any triplet (group of three) is always at the end. After sorting and considering the triangle inequality rule, we iterate backward from the end of the array to perform the search for valid combinations. While iterating, we identify valid combinations by fixing the current element as the largest side and exploring potential pairs for the other two smaller sides.
Now, let’s look at the solution steps below:
We begin by sorting the array
nums
. Sorting is important because it ensures that for any triplet(nums[left], nums[right], nums[i])
wherei > right > left
,nums[i]
is the largest side. This allows us to only check ifnums[left] + nums[right] > nums[i]
.We initialize a variable,
count
, tofor tracking the number of valid triangles. We iterate backward from the end of
nums
, treating each current element,nums[i]
, as the largest side of the triangle.We initialize
left
andright
pointers to the start of the array and one position before the selected largest side, respectively.We use
left
andright
pointers to explore potential pairs (nums[left]
,nums[right]
) untilleft < right
.If
nums[left] + nums[right] > nums[i]
, then all combinations ofnums[left]
with indexes betweenleft
andright
will also be valid (due to the sorted order). We incrementcount
byright - left
and move theright
pointer one step to the left (right -= 1
).Otherwise, if the sum is not greater, increment the
left
pointer (left += 1
) to explore a larger pair sum.
After iterating through all combinations in
nums
, we return thecount
representing all the valid combinations.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.