Check Voting Eligibility by Age

Solve this Problem
Easy5 min
Topics
Companies
Given a person's age, return whether they're eligible to vote, assuming the minimum voting age is 18 (inclusive). A single comparison decides the whole outcome. The if-elseIf-ElseTwo branches, one condition — exactly one of "true" or "false" is returned. version spells out both outcomes explicitly, which is the natural way to write this before the next pattern clicks: once the condition itself already IS the true/false answer you want, returning it directly skips the if-else entirely.

Test Case 1:

Input:age = 15
Output:false
Explanation:15 is less than 18.

Test Case 2:

Input:age = 20
Output:true
Explanation:20 is at least 18.

Test Case 3:

Input:age = 18
Output:true
Explanation:Exactly 18 qualifies — the minimum age is inclusive.

Constraints

  • ◆0 ≤ age ≤ 150

Try the Dry Run

Approach & Solutions

If-Else StatementGood

Compare age against the minimum voting age of 18. If age is 18 or older, voting is allowed; otherwise it isn't. A single comparison with exactly two outcomes.

TimeO(1)
SpaceO(1)
1class Solution { 2 public boolean canVote(int age) { 3 if (age >= 18) { 4 return true; 5 } else { 6 return false; 7 } 8 } 9}
Direct Boolean ExpressionOptimal

age >= 18 is already a true/false value — there's no need to wrap it in an if-else just to hand back true or false. Returning the comparison directly says exactly the same thing in one line.

TimeO(1)
SpaceO(1)
1class Solution { 2 public boolean canVote(int age) { 3 return age >= 18; 4 } 5}

Related Problems