β Back to Revisions
Day 5
View Problem βTriangle Validator
π
October 27, 2025π·οΈ Smart Interviews
Complexity Analysis
Brute Force
N/A
Optimized
N/A
Space
N/A
Solutions
Javaβ
import java.util.Scanner;
import java.util.Arrays;
class Solution {
// O(1) Time, O(1) Space - Optimal
public static boolean isTriangleValid_optimal(int a, int b, int c) {
if (a <= 0 || b <= 0 || c <= 0) return false;
return (a + b > c) && (a + c > b) && (b + c > a);
}
// O(1) Time, O(1) Space - Brute (Uses sorting which is O(1) for 3 elements)
public static boolean isTriangleValid_brute(int a, int b, int c) {
int[] sides = {a, b, c};
Arrays.sort(sides); // Sorting 3 elements is constant time
if (sides[0] <= 0) return false;
// Check if sum of two smaller sides > largest side
return sides[0] + sides[1] > sides[2];
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
if (!scanner.hasNextInt()) return;
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();
if (isTriangleValid_optimal(a, b, c)) {
System.out.println("Valid");
} else {
System.out.println("Invalid");
}
scanner.close();
}
}C++β‘
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
// O(1) Time, O(1) Space
bool isTriangleValid_optimal(int a, int b, int c) {
// Optimal: Direct application of the Triangle Inequality Theorem.
if (a <= 0 || b <= 0 || c <= 0) return false;
return (a + b > c) && (a + c > b) && (b + c > a);
}
// O(1) Time, O(1) Space (Brute force is unnecessary here, but shown for structure)
bool isTriangleValid_brute(int a, int b, int c) {
// Brute: Sort the sides and only check the condition for the largest side.
// If a+b > c, the other two conditions (a+c > b and b+c > a) are automatically true.
vector<int> sides = {a, b, c};
sort(sides.begin(), sides.end());
// Check if the sum of the two smaller sides is greater than the largest side.
if (sides[0] <= 0) return false; // Check for positive lengths
return sides[0] + sides[1] > sides[2];
}
void solve_triangle_validator() {
int a, b, c;
if (!(cin >> a >> b >> c)) return;
if (isTriangleValid_optimal(a, b, c)) {
cout << "Valid" << endl;
} else {
cout << "Invalid" << endl;
}
}
int main() {
solve_triangle_validator();
return 0;
}Tags
mathgeometrylogic
π‘ Revision Tips
- β’ Try solving from memory before checking your solution
- β’ Focus on the approach and pattern, not just the code
- β’ Can you explain the solution to someone else?
- β’ Try implementing in a different language