Magicsheet logo

Valid Triangle Number

Medium
97.7%
Updated 6/1/2025

Valid Triangle Number

What is this problem about?

The "Valid Triangle Number" interview question asks you to count the number of triplets chosen from a given array that can form a valid triangle. According to the triangle inequality theorem, three sides a, b, and c can form a triangle if and only if a + b > c, a + c > b, and b + c > a. When the sides are sorted such that a ≤ b ≤ c, this simplifies to the single condition: a + b > c.

Why is this asked in interviews?

This "Valid Triangle Number" coding problem is a frequent choice for companies like Goldman Sachs, Microsoft, and Meta. It tests a candidate's ability to optimize a brute-force O(n³) solution into a more efficient O(n²) approach. It evaluates your understanding of sorting and the "Two Pointers interview pattern," which is essential for handling triplet-based problems.

Algorithmic pattern used

The most efficient algorithmic pattern is a combination of "Sorting" and the "Two Pointers" technique. After sorting the array, you fix the largest side c (at index i) and then use two pointers (left and right) to find pairs (a, b) such that a + b > c. If nums[left] + nums[right] > nums[i], then all elements between left and right will also satisfy the condition when paired with nums[right].

Example explanation

Array: [4, 2, 3, 4]

  1. Sort the array: [2, 3, 4, 4]
  2. Fix i = 3 (Value 4):
    • left = 0 (Value 2), right = 2 (Value 4).
    • 2 + 4 > 4? Yes. Triplets are (2,4,4) and (3,4,4). Count = 2.
  3. Fix i = 2 (Value 4):
    • left = 0 (Value 2), right = 1 (Value 3).
    • 2 + 3 > 4? Yes. Triplet is (2,3,4). Count = 2 + 1 = 3.
  4. Total valid triangle numbers: 3.

Common mistakes candidates make

A common mistake is using a triple nested loop, which leads to a time complexity of O(n³). While correct, it will likely fail the performance constraints in a real interview. Another error is not sorting the array, which makes the two-pointer optimization impossible. Candidates also sometimes forget that the same value at different indices counts as a different side.

Interview preparation tip

For the "Valid Triangle Number" coding problem, always remember that sorting is often the first step for any problem involving "triplets" or "combinations" with mathematical inequalities. It allows you to use two pointers to "shrink" the search space, a technique that is applicable to many other problems like 3Sum.

Similar Questions