File: largest-perimeter-triangle/solution.py

Date: 2026-06-06

Time: 17:16

largest-perimeter-triangle/solution.py

Purpose

This file implements LeetCode problem 976 ("Largest Perimeter Triangle"). It owns the single responsibility of determining the largest possible perimeter from any three side lengths in a given list that can form a valid triangle. It returns 0 when no valid triangle exists.

Key Components

largestperimetertriangle(nums: list[int]) -> int — The sole public function. Takes a list of candidate side lengths and returns the largest perimeter achievable, or 0 if no triple satisfies the triangle inequality.

Contract: nums must have at least 3 elements for a meaningful result. The function mutates nums in-place via sort().

Patterns

Greedy via sorted scan. The solution sorts descending then checks consecutive triples. This is the canonical greedy approach for this problem: if the three largest sides don't form a triangle, no combination involving the largest side will either, so you can safely discard it and move on.

Early return on first valid triple. Because the array is sorted largest-first, the first triple that satisfies the triangle inequality is guaranteed to yield the maximum perimeter. No need to examine further.

Dependencies

Imports: None — pure stdlib, no external dependencies.

Imported by: Its own test_solution.py. The "Imported By" list in the prompt is misleading — that list appears to be every test file in the repo, likely an artifact of a shared test runner or import structure, not actual cross-problem imports.

Flow

1. Sort descendingnums.sort(reverse=True) arranges sides from largest to smallest.

2. Scan consecutive triples — Iterate i from 0 to len(nums) - 3. At each step, check nums[i], nums[i+1], nums[i+2].

3. Triangle inequality check — Only the "largest < sum of two smaller" condition is tested (nums[i] < nums[i+1] + nums[i+2]). The other two inequalities are automatically satisfied because nums[i] >= nums[i+1] >= nums[i+2].

4. Return perimeter or 0 — First valid triple returns immediately. If the loop exhausts, return 0.

Invariants

Error Handling

None. The function assumes valid input (list of positive integers with length >= 3, per LeetCode constraints). If len(nums) < 3, the loop body never executes and it returns 0, which happens to be correct but isn't explicitly guarded.

Topics to Explore

Beliefs