At a contest, children can participate only if they have ages between minAge
and maxAge
. Given the age of a child, check if they are allowed or not.
Example 1:
Input: minAge = 7, maxAge = 12, age = 7 Output: true
Example 2:
Input: minAge = 3, maxAge = 8, age = 10 Output: false
The core challenge of this problem is to determine if a given age falls within a specified range. This is a common problem in scenarios where eligibility criteria are based on age, such as contests, sports events, or age-restricted activities.
Potential pitfalls include misunderstanding the inclusive nature of the age range or incorrectly implementing the boundary checks.
To solve this problem, we need to check if the given age is within the inclusive range defined by minAge
and maxAge
. There are several ways to approach this:
A naive solution would involve checking if the age is less than minAge
or greater than maxAge
and returning False
in those cases. Otherwise, return True
.
We can optimize the solution by using a single if statement with two conditions or directly returning the boolean expression.
Here is a step-by-step breakdown of the algorithm:
minAge
or greater than maxAge
.False
.True
.Below are the implementations of the different approaches in Python:
def is_allowed_to_contest(minAge, maxAge, age):
# Check if age is less than minAge or greater than maxAge
if age < minAge or age > maxAge:
return False
return True
def is_allowed_to_contest(minAge, maxAge, age):
# Using a single if statement with two conditions
return age >= minAge and age <= maxAge
def is_allowed_to_contest(minAge, maxAge, age):
# Directly returning the boolean expression
return minAge <= age <= maxAge
All the solutions have a time complexity of O(1) because they involve a constant number of operations regardless of the input size. The space complexity is also O(1) as no additional space is required.
Potential edge cases include:
minAge
or maxAge
.minAge
or just above maxAge
.Examples:
minAge = 5, maxAge = 10, age = 5 # Expected output: True
minAge = 5, maxAge = 10, age = 10 # Expected output: True
minAge = 5, maxAge = 10, age = 4 # Expected output: False
minAge = 5, maxAge = 10, age = 11 # Expected output: False
To test the solution comprehensively, consider a variety of test cases:
Using a testing framework like unittest
in Python can help automate and organize these tests.
When approaching such problems:
In this blog post, we discussed how to determine if a child's age falls within a specified range. We explored different approaches, analyzed their complexities, and provided Python implementations. Understanding and solving such problems is crucial for developing strong problem-solving skills.
For further reading and practice: