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 and incorrectly implementing the boundary conditions.
To solve this problem, we can use a simple comparison to check if the given age is within the specified range. There are multiple ways to implement this:
false
if the age is less than minAge
or greater than maxAge
, otherwise return true
.if
statement with two conditions to return true
if the age is within the range, otherwise return false
.Let's break down the algorithm step-by-step:
minAge
, maxAge
, and age
.minAge
, maxAge
].true
if the age is within the range, otherwise return false
.public class ContestEligibility {
// Method to check if the child is allowed to participate
public static boolean isAllowedToContest(int minAge, int maxAge, int age) {
// Return the result of the condition directly
return age >= minAge && age <= maxAge;
}
public static void main(String[] args) {
// Test cases
System.out.println(isAllowedToContest(7, 12, 7)); // true
System.out.println(isAllowedToContest(3, 8, 10)); // false
}
}
The time complexity of this solution is O(1) because it involves 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:
age
is exactly equal to minAge
or maxAge
.minAge
and maxAge
are the same.age
is outside the range.These cases are handled by the condition age >= minAge && age <= maxAge
.
To test the solution comprehensively, consider the following test cases:
minAge
or maxAge
.Using a testing framework like JUnit can help automate and validate these test cases.
When approaching such problems, consider the following tips:
In this blog post, we discussed how to determine if a child is allowed to participate in a contest based on their age. We explored different approaches, provided a detailed algorithm, and implemented the solution in Java. Understanding and solving such problems is crucial for developing strong problem-solving skills.
For further reading and practice, consider the following resources: