#976

Largest Perimeter Triangle

Easy
ArrayMathGreedySortingSortingGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n³)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

By sorting the array first, we can efficiently check for valid triangles starting from the largest sides. This allows us to quickly find the largest perimeter without checking all combinations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the array in non-decreasing order.
  2. 2Step 2: Iterate from the end of the sorted array to the beginning, checking each triplet (nums[i], nums[i-1], nums[i-2]).
  3. 3Step 3: If nums[i-2] + nums[i-1] > nums[i], we have a valid triangle and can calculate the perimeter.
  4. 4Step 4: Return the perimeter immediately as it will be the largest due to the sorted order. If no valid triangle is found, return 0.
solution.py6 lines
1def largestPerimeter(nums):
2    nums.sort()
3    for i in range(len(nums) - 1, 1, -1):
4        if nums[i - 2] + nums[i - 1] > nums[i]:
5            return nums[i - 2] + nums[i - 1] + nums[i]
6    return 0

Complexity note: The sorting step takes O(n log n) time, and the subsequent linear scan takes O(n), making this approach efficient overall.

  • 1The triangle inequality is crucial for determining if three lengths can form a triangle.
  • 2Sorting the lengths allows us to efficiently check for valid triangles from the largest sides.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.