Problem 611

Abstract / Summary

Given an array of positive integers, count how many triplets can form a triangle using the triangle inequality.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0611.cpp

class Solution {
public:
    int triangleNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end());

        int result = 0;
        for (int i = 0; i < nums.size(); i++)
        {
            if (nums[i] == 0)
                continue;

            for (int j = i + 1; j < nums.size(); j++)
            {
                auto minLength = nums[i] + nums[j];
                auto third = lower_bound(nums.begin(), nums.end(), minLength);
                auto toobig = distance(third, nums.end());
                result += nums.size() - toobig - j - 1;
            }
        }

        return result;
    }
};
23 lines | 641 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 57% (600k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Greedy
  • Sorting
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the number of distinct triplets in an integer array that can form a non-degenerate triangle. A triangle is valid when the sum of any two side lengths exceeds the third side. The algorithm first orders the input to enable efficient searching, then iterates over pairs of indices while using binary search to locate the smallest index that satisfies the triangle inequality for the third side. The count of suitable third sides is accumulated into the result.

Key Steps

Sorting the Input

sort(nums.begin(), nums.end());

Sorting arranges the side lengths in non-decreasing order. This ordering guarantees that for any indices i < j < k, the condition nums[i] + nums[j] > nums[k] is sufficient to satisfy all three triangle inequalities because nums[i] ≤ nums[j] ≤ nums[k]. The sorted sequence also allows binary search to be applied later.

Skipping Zero Length Sides

if (nums[i] == 0)
    continue;

A side of length zero cannot contribute to a valid triangle, as the sum of the other two sides would never be greater than zero. By checking for zero and moving to the next i, the loop avoids unnecessary work for such values.

Pairwise Traversal

for (int i = 0; i < nums.size(); i++)
{
    for (int j = i + 1; j < nums.size(); j++)
    {
        // ...
    }
}

Two nested loops enumerate every ordered pair (i, j) with i < j. For each pair, the algorithm determines how many indices k with k > j can serve as the third side.

Determining the Minimum Required Length

auto minLength = nums[i] + nums[j];

The sum of the two chosen sides defines the smallest value that the third side must be strictly less than to satisfy the triangle inequality. Because the array is sorted, any element equal to or larger than this sum cannot form a triangle with the current pair.

Binary Search for the Upper Bound

auto third = lower_bound(nums.begin(), nums.end(), minLength);

lower_bound finds the first position in the sorted array where the element is not less than minLength. All elements before this iterator are strictly less than minLength and therefore eligible as the third side. This binary search replaces a linear scan, reducing the work needed to locate the boundary.

Counting Valid Third Indices

auto toobig = distance(third, nums.end());
result += nums.size() - toobig - j - 1;

distance(third, nums.end()) yields the number of elements from the found position to the end of the array, i.e., the count of elements that are too large. Subtracting this from the total size gives the number of elements that are small enough. The expression further subtracts j + 1 to exclude indices that are not greater than j, ensuring only valid third positions are counted. The resulting value is added to the cumulative result.

Edge Cases Handled

The algorithm explicitly ignores elements equal to zero, preventing degenerate triangles where one side contributes no length. Because the array is sorted, duplicate values are naturally accommodated; each occurrence is treated as a distinct side, and the binary search correctly accounts for multiple identical lengths when determining the boundary. The use of lower_bound ensures that even when the sum of the two chosen sides equals an existing element, that element is excluded from the count, preserving the strict inequality required for a valid triangle.

When the input contains fewer than three elements, the outer loops still execute but the inner calculations produce zero contributions, resulting in a final count of zero without any special casing. The algorithm also gracefully handles very large integer values because the sum is stored in an auto variable that matches the type of the operands, and the comparison performed by lower_bound respects the underlying integer limits.

Performance Optimizations

The most significant optimization is the replacement of a potential third nested loop with a binary search (lower_bound). By locating the cutoff point for the third side in logarithmic time, the algorithm avoids scanning the remainder of the array for each pair, which would otherwise lead to cubic behavior. The sorted order, established once at the beginning, enables this binary search to be applied repeatedly without additional overhead.

The calculation of the number of valid third sides uses arithmetic on indices rather than iterating over each candidate, turning what could be a linear accumulation into a constant-time update per pair. The use of distance on iterators is efficient because the iterators are random-access, allowing the operation to be performed in constant time.

Skipping zero-length sides early eliminates entire branches of the pairwise loops, reducing the number of binary searches performed when the input contains many zeros. This early exit contributes to overall speed, especially for inputs dominated by non-positive values.

Collectively, these choices keep the algorithm’s work proportional to the number of index pairs multiplied by a logarithmic factor, delivering a fast solution for large input sizes while maintaining correctness across all edge conditions.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big pile of sticks of all different sizes and you want to build as many triangles as possible. To know if three sticks can make a triangle, the two smaller sticks added together must be longer than the biggest stick.

First, the code lines up all the sticks from the shortest to the longest. Putting them in order makes the job much easier because you can search through them quickly.

The computer then looks at two sticks at a time. It picks one stick and then a second stick that is slightly longer. It adds their lengths together to see how long a third stick would need to be to make a triangle work.

Next, the computer goes on a hunt to see how many of the remaining sticks in the pile are the right size. It wants sticks that are longer than the third one we talked about, but not so long that they break the rules of being a triangle.

By counting all the sticks that fit perfectly between those limits, the computer figures out how many combinations of three sticks will form a triangle. It keeps doing this for every pair of sticks until it has checked every single possibility.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.63 | σ = 0.95

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fengvyi C++
fpdjsns C++
halfrost Go
JoshCrozier JS
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
withaarzoo C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fengvyi C++
fpdjsns C++
halfrost Go
JoshCrozier JavaScript
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
withaarzoo C++
zfang399 C++
38 links | 23 authors | 8 languages

Videos

13 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

40 easy 30 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality