Decide Entry Using Logical Operators
Solve this ProblemEasy10 min
Topics
BasicsOperators
Companies
TCSInfosysWipro
A cinema lets someone in when they have a ticket and either are at least 18 or come with an adult. Given
age, hasTicket and withAdult, return whether they may enter.
Logical operatorsLogical OperatorsAND (&&, and), OR (||, or) and NOT (!, not) — they combine true/false values into one true/false result. let one condition express a whole rule. The first solution spells the rule out with separate if checks; the second writes it as a single expression. Both rely on short-circuit evaluationShort-Circuit EvaluationAND stops at the first false operand and OR stops at the first true one, because the final answer is already decided.: once the answer is known, the remaining checks are skipped.
Test Case 1:
Input:age = 15, hasTicket = true, withAdult = true
Output:true
Explanation:Under 18, but a ticket and an accompanying adult are enough.
Test Case 2:
Input:age = 30, hasTicket = false, withAdult = true
Output:false
Explanation:No ticket means no entry, whatever the age.
Constraints
- ◆
0 ≤ age ≤ 120
Try the Dry Run
Approach & Solutions
Nested if StatementsGood
Check the rules one at a time and leave as soon as the answer is known. No ticket: return false straight away. Otherwise an adult (18 or older) may enter. Otherwise entry depends on whether an adult is with them.
Time
O(1)Space
O(1)Java
class Solution {
public boolean canEnter(int age, boolean hasTicket, boolean withAdult) {
if (!hasTicket) {
return false;
}
if (age >= 18) {
return true;
}
if (withAdult) {
return true;
}
return false;
}
}One Logical ExpressionOptimal
Translate the rule straight into logic: a ticket AND (an adult OR accompanied by an adult). && / and and || / or combine the conditions, and the brackets make OR happen before AND. Both operators stop as soon as the answer is certain (short-circuit evaluation).
Time
O(1)Space
O(1)Java
class Solution {
public boolean canEnter(int age, boolean hasTicket, boolean withAdult) {
return hasTicket && (age >= 18 || withAdult);
}
}