Solution: Valid Triangle Number

Let’s solve the Valid Triangle Number problem using the Sort and Search pattern.

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 valid triangleA triangle is valid if the sum of the lengths of any two smaller sides is strictly greater than the length of the third largest side. For three sides a, b, c (such that a ≤ b ≤ c), the condition to form a valid triangle is a + b > c.. Return this count as the result.

Constraints:

  • 1<=1 <= nums.length <=1000<= 1000

  • 0<=0 <= nums[i] <=1000<= 1000

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:

  1. We begin by sorting the array nums. Sorting is important because it ensures that for any triplet (nums[left], nums[right], nums[i]) where i > right > left, nums[i] is the largest side. This allows us to only check if nums[left] + nums[right] > nums[i].

  2. We initialize a variable, count, to 00 for tracking the number of valid triangles.

  3. We iterate backward from the end of nums, treating each current element, nums[i], as the largest side of the triangle.

    1. We initialize left and right pointers to the start of the array and one position before the selected largest side, respectively.

    2. We use left and right pointers to explore potential pairs (nums[left], nums[right]) until left < right.

      1. If nums[left] + nums[right] > nums[i], then all combinations of nums[left] with indexes between left and right will also be valid (due to the sorted order). We increment count by right - left and move the right pointer one step to the left (right -= 1).

      2. Otherwise, if the sum is not greater, increment the left pointer (left += 1) to explore a larger pair sum.

  4. After iterating through all combinations in nums, we return the count 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.