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;
}
};
Difficulty
and has an acceptance rate of about 57% (600k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Greedy
- Sorting
- Two Pointers
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 259: 3Sum Smaller
- problem 2971: Find Polygon With the Largest Perimeter
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- 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