Find the Smallest of Three Numbers

Solve this Problem
Easy5 min
Topics
Companies
Given three integers a, b and c, return the smallest of them. The ternary operatorTernary Operatorcondition ? valueIfTrue : valueIfFalse — an if-else that produces a value and fits inside an expression. is a compact if-else that produces a value. Because a ternary is itself a value, one can sit inside another, and two nested ternaries are enough for three numbers. The if-else version is shown first, so the two can be compared directly.

Test Case 1:

Input:a = 8, b = 2, c = 6
Output:2
Explanation:b is smaller than both a and c.

Test Case 2:

Input:a = 5, b = 5, c = 5
Output:5
Explanation:When values tie, the smallest value is still 5, whichever variable it comes from.

Constraints

  • ◆-1000000 ≤ a, b, c ≤ 1000000

Try the Dry Run

Approach & Solutions

If-Else ChainGood

First ask whether a is no bigger than both b and c. If it is, a is the answer. If not, a is ruled out, and one more comparison between b and c decides which of those two is smaller.

TimeO(1)
SpaceO(1)
class Solution { public int smallestOfThree(int a, int b, int c) { int smallest; if (a <= b && a <= c) { smallest = a; } else if (b <= c) { smallest = b; } else { smallest = c; } return smallest; } }
Nested Ternary OperatorOptimal

The ternary operator condition ? x : y is an if-else that produces a value, so it can be nested. The outer ternary compares a with b; the winner is then compared with c by an inner ternary. Python writes it as x if condition else y.

TimeO(1)
SpaceO(1)
class Solution { public int smallestOfThree(int a, int b, int c) { return a < b ? (a < c ? a : c) : (b < c ? b : c); } }

Related Problems