Goldilocks Number - codepath/compsci_guides GitHub Wiki
"TIP102 Unit 1 Session 2 Standard (Click for link to problem statements)
Problem Highlights
- 💡 Difficulty: Easy
- ⏰ Time to complete: 10 mins
- 🛠️ Topics: Arrays, Conditionals, Iteration
U-nderstand
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
- Q: What is the input of the function?
- A: The function should take a list of distinct positive integers
nums
.
- A: The function should take a list of distinct positive integers
- Q: What is the output of the function?
- A: The function should return any number from the list that is neither the minimum nor the maximum value in the array.
- Q: What if there are only minimums or maximums?
- A: If no such number exists, return
-1
.
- A: If no such number exists, return
HAPPY CASES:
Input: [3, 2, 1, 4]
Expected Output: 2 or 3
Explanation: The minimum value is 1 and the maximum value is 4, so either 2 or 3 can be valid answers.
Input: [2, 1, 3]
Expected Output: 2
Explanation: Since 2 is neither the minimum nor the maximum value, it is the only valid answer.
EDGE CASES:
Input: [1, 2]
Expected Output: -1
Explanation: There is no number in nums that is neither the maximum nor the minimum, so no valid answer exists.
Input: [5]
Expected Output: -1
Explanation: Only one number exists in the list, so it cannot be neither the minimum nor the maximum.
P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Check if the length of the list is less than or equal to 2. If so, return -1 since no valid number can exist. Identify the minimum and maximum values in the list. Iterate through the list and return the first number that is neither the minimum nor the maximum. If no such number is found, return -1.
1.Define the function goldilocks_approved(nums).
2. Check if the length of nums is less than or equal to 2. If true, return -1.
3. Determine the minimum and maximum values in nums.
4. Iterate through nums:
If the current number is neither the minimum nor the maximum, return it.
5. If the loop completes without finding a valid number, return -1.
⚠️ Common Mistakes
- Failing to handle lists with only one or two elements.
- Incorrectly identifying minimum or maximum values.
I-mplement
Implement the code to solve the algorithm.
def goldilocks_approved(nums):
if len(nums) <= 2:
return -1
min_val = min(nums)
max_val = max(nums)
for num in nums:
if num != min_val and num != max_val:
return num
return -1