Largest Perimeter Triangle (LeetCode 976): Solution and Explanation

Easy
Array
Math
Greedy
Sorting

You get a list of stick lengths. Choose three that form a triangle with positive area and return the largest perimeter, or 0 if no three sticks can do it.

Intuition

Three sticks a <= b <= c close into a real triangle only if the two shorter ones together are longer than the longest: a + b > c. The other two triangle inequalities hold automatically once the sticks are sorted.

Fix the longest side c. To give it the best chance, pair it with the two longest sticks that are not longer than it. In sorted order those are simply the two sticks right below c.

If even those two fail, nothing smaller will work with c, so c is useless and can be dropped. Start from the longest stick and move down: the first window that passes uses the biggest sticks possible, so its perimeter is the answer.

Approach: Sort and test windows of three from the top

  1. Sort nums in ascending order.
  2. For i from n - 1 down to 2, let c = nums[i], b = nums[i - 1], a = nums[i - 2].
  3. If a + b > c, return a + b + c.
  4. Otherwise drop c and continue with the next smaller i.
  5. If no window passes, return 0.

Step-by-step example

nums = [2,1,2]
  1. Sort the sticks: [1, 2, 2].
  2. Take the longest stick c = 2 and its partners a = 1, b = 2.
  3. 1 + 2 = 3 > 2, so the three sticks form a triangle.
  4. Return 1 + 2 + 2 = 5.

Code: Python, Java, C++

1class Solution:
2    def largestPerimeter(self, nums: List[int]) -> int:
3        nums.sort()
4        for i in range(len(nums) - 1, 1, -1):
5            if nums[i - 2] + nums[i - 1] > nums[i]:
6                return nums[i - 2] + nums[i - 1] + nums[i]
7        return 0
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n)

Sorting dominates. The scan afterwards is a single pass from the top.

Space

O(1)

Only a few variables are used besides the in-place sort (which may use O(log n) stack internally).

Other approaches

Try every triple (time O(n^3), space O(1))

Check all combinations of three sticks and keep the best valid perimeter. Correct but O(n^3), far too slow for 10,000 sticks.

Max-heap without full sort (time O(n + k log n), space O(n))

Build a heap and pop sticks from the largest down, keeping the last three popped. It stops early once a window passes, which can beat a full sort when the answer is near the top.

Common mistakes

  • Using >= instead of >. When a + b equals c the three sticks lie flat on a line, which has zero area and does not count.
  • Checking non-adjacent triples after sorting. For a fixed longest side, the adjacent pair below it is always the best choice, so other pairs add work but never a better answer.
  • Scanning from the smallest sticks upward and returning the first valid triangle. That finds a triangle, but not the one with the largest perimeter.
  • Checking all three triangle inequalities. After sorting, a + b > c is the only one that can fail.

Frequently asked questions

Why does the first passing window give the largest perimeter?

Windows are tried with the longest side from largest to smallest, and each window uses the largest partners available for that side. Any triangle with a smaller longest side has all three sides no larger than this one's.

Why can a failing longest side be thrown away?

If the two largest sticks below c add up to at most c, every other pair below c adds up to even less. So c cannot be the longest side of any triangle, and it cannot be a shorter side either because everything above it was already ruled out.

How many windows can fail in a row?

Each failure means the longest stick is at least the sum of the next two, so lengths shrink like a reversed Fibonacci sequence. With lengths up to 10^6, only about 30 windows can fail before one passes or the sticks run out.