|
| 1 | +/** |
| 2 | + * Question: Determine Triangle Type |
| 3 | + * Link: https://leetcode.com/problems/triangle-type/ (hypothetical link, adjust if needed) |
| 4 | + * |
| 5 | + * Description: |
| 6 | + * Given three side lengths of a triangle, return the type of the triangle: |
| 7 | + * - "equilateral" if all sides are equal |
| 8 | + * - "isosceles" if exactly two sides are equal |
| 9 | + * - "scalene" if all sides are different |
| 10 | + * - "none" if the given sides cannot form a valid triangle |
| 11 | + * |
| 12 | + * Approach: |
| 13 | + * 1. Extract the three sides. |
| 14 | + * 2. Check the triangle inequality: sum of any two sides must be greater than the third. |
| 15 | + * If it fails, return "none". |
| 16 | + * 3. If all three sides are equal, return "equilateral". |
| 17 | + * 4. If exactly two sides are equal, return "isosceles". |
| 18 | + * 5. Otherwise, return "scalene". |
| 19 | + * |
| 20 | + * Dry Run: |
| 21 | + * Example: nums = [3, 4, 5] |
| 22 | + * - Check: 3+4 > 5, 3+5 > 4, 4+5 > 3 → valid triangle |
| 23 | + * - Not all sides equal |
| 24 | + * - No two sides equal |
| 25 | + * - Result → "scalene" |
| 26 | + * |
| 27 | + * Example: nums = [2, 2, 2] |
| 28 | + * - Check: valid triangle |
| 29 | + * - All equal → "equilateral" |
| 30 | + * |
| 31 | + * Example: nums = [2, 3, 5] |
| 32 | + * - Check: 2+3 = 5 → fails inequality |
| 33 | + * - Result → "none" |
| 34 | + * |
| 35 | + * Time Complexity: O(1) → only a few comparisons. |
| 36 | + * Space Complexity: O(1) → no extra data structures used. |
| 37 | + */ |
| 38 | + |
| 39 | +class Solution { |
| 40 | + public String triangleType(int[] nums) { |
| 41 | + |
| 42 | + int s1 = nums[0]; |
| 43 | + int s2 = nums[1]; |
| 44 | + int s3 = nums[2]; |
| 45 | + |
| 46 | + // Check triangle inequality |
| 47 | + if (s1 + s2 <= s3 || s1 + s3 <= s2 || s2 + s3 <= s1) { |
| 48 | + return "none"; |
| 49 | + } |
| 50 | + |
| 51 | + // All sides equal |
| 52 | + if (s1 == s2 && s2 == s3) { |
| 53 | + return "equilateral"; |
| 54 | + } |
| 55 | + // Any two equal |
| 56 | + else if (s1 == s2 || s2 == s3 || s1 == s3) { |
| 57 | + return "isosceles"; |
| 58 | + } |
| 59 | + // Otherwise scalene |
| 60 | + else { |
| 61 | + return "scalene"; |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments