AlgoMaster Logo

Valid Triangle from Three Sides

Last Updated: June 7, 2026

easy
2 min read

Understanding the Problem

Not every set of three lengths closes into a triangle. If one side is too long, the other two cannot reach far enough to meet at a corner. Picture two sticks hinged at the base of the longest stick: to form a triangle they together have to span more than that base. If they sum to exactly the base, they lie flat along it and the triangle collapses into a line. If they sum to less, they cannot touch at all.

This is the triangle inequality, and it has to hold for all three choices of which side is the "base". Each pair of sides must sum to strictly more than the third.

Key Constraints:

  • All sides are positive → A side length of zero or less cannot exist, but since the inputs are positive you can focus purely on the inequality.
  • The inequality must hold for all three pairs → Checking only one pair is not enough. A long third side could still violate the rule even when one pair passes.
  • The comparison must be strict → If two sides sum to exactly the third, the shape is degenerate and flat, so it is not a valid triangle. Use > rather than >=.

Approach 1: Triangle Inequality

Intuition

Turn the inequality into three conditions, one for each choice of the "third" side:

  • a + b > c
  • a + c > b
  • b + c > a

If all three hold, the lengths form a triangle. If any fails, they do not. Joining them with AND captures that.

With all sides positive, the only way to fail is for the largest side to be too long, so the two conditions with smaller "third" sides are easy to satisfy. Checking all three stays correct without first finding which side is largest.

Algorithm

  1. Check whether a + b is strictly greater than c.
  2. Check whether a + c is strictly greater than b.
  3. Check whether b + c is strictly greater than a.
  4. Return true only if all three checks pass.

Example Walkthrough

Input:

1
a
1
b
2
c

The sides are 1, 1, and 2. The first check, 1 + 1 > 2, asks whether 2 > 2, which is false. The two short sides sum to exactly the long side, so they lie flat along it instead of meeting at a point. One failed condition is enough to reject the whole set, so the answer is false.

false
output

Code