Find the Largest of Two Numbers
Solve this ProblemEasy5 min
Topics
BasicsConditionals
Companies
TCSInfosysWipro
Given two integers
a and b, return whichever one is larger. If they're equal, either value is correct.
This is the simplest possible comparison problem — exactly one condition decides between exactly two outcomes. The if-elseIf-ElseA two-way branch: one block runs if the condition is true, the other if it's false. version spells the comparison out; the ternaryTernary OperatorThe condition ? valueIfTrue : valueIfFalse expression — a compact, single-line if-else. version compacts it into one line once that pattern feels natural.
Test Case 1:
Input:a = 7, b = 3
Output:7
Explanation:7 is greater than 3.
Test Case 2:
Input:a = 2, b = 9
Output:9
Explanation:9 is greater than 2.
Test Case 3:
Input:a = 5, b = 5
Output:5
Explanation:Equal values — either one is correct, so the comparison's else branch (b) is returned.
Constraints
- ◆
-1000 ≤ a ≤ 1000 - ◆
-1000 ≤ b ≤ 1000
Try the Dry Run
Approach & Solutions
If-Else ComparisonGood
Compare the two numbers directly: if a is strictly greater than b, a is the larger one; otherwise — including when they're equal — b is returned. One comparison, one decision.
Time
O(1)Space
O(1)Java
1class Solution {
2 public int findLargestOfTwo(int a, int b) {
3 if (a > b) {
4 return a;
5 } else {
6 return b;
7 }
8 }
9}Ternary OperatorOptimal
The same comparison, written as a single expression: a > b ? a : b. Once the if-else version feels obvious, this is the idiomatic one-liner for the same decision.
Time
O(1)Space
O(1)Java
1class Solution {
2 public int findLargestOfTwo(int a, int b) {
3 return a > b ? a : b;
4 }
5}