Largest Perimeter Triangle — LeetCode 976 Python Solution

EasyGreedyArrayMathSorting
Problem
#976
Pattern
Greedy
Reading time
2 min

The problem

Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.

Example

Input
nums = [2,1,2]
Output
5
Explanation
You can form a triangle with three side lengths: 1, 2, and 2.

Python solution

Python
class Solution:
    def largestPerimeter(self, nums: List[int]) -> int:
        nums.sort()
        for i in range(len(nums) - 1, 1, -1):
            if (c := nums[i - 1] + nums[i - 2]) > nums[i]:
                return c + nums[i]
        return 0

Complexity

MeasureComplexity
TimeO(n \log n)
SpaceO(\log n), where n is the length of the array \textit{nums} auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 976. Largest Perimeter Triangle is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 976. Largest Perimeter Triangle?
LeetCode 976. Largest Perimeter Triangle is rated Easy on LeetCode.
What is the time complexity of LeetCode 976. Largest Perimeter Triangle?
The Python solution on this page runs in O(n \log n).
What is the space complexity of LeetCode 976. Largest Perimeter Triangle?
The Python solution on this page uses O(\log n), where n is the length of the array \textit{nums} auxiliary space.
What topics does LeetCode 976. Largest Perimeter Triangle cover?
LeetCode 976. Largest Perimeter Triangle is tagged Greedy, Array, Math and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview