-
Notifications
You must be signed in to change notification settings - Fork 254
Return Item
TIP102 Unit 1 Session 1 Standard (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 5 mins
- 🛠️ Topics: List Indexing, Return Statements
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?
- The function
get_item()
should take a list items and an integer x, and return the element at index x if it is a valid index. If x is not a valid index, the function should return None.
HAPPY CASE
Input: items = ["piglet", "pooh", "roo", "rabbit"], x = 2
Expected Output: "roo"
Input: items = ["piglet", "pooh", "roo", "rabbit"], x = 0
Expected Output: "piglet"
EDGE CASE
Input: items = ["piglet", "pooh", "roo", "rabbit"], x = 5
Expected Output: None
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
This problem falls under: List Indexing and Validation.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Define a function that checks if the provided index is valid and returns the corresponding element if it is, or None if it isn't.
1. Define the function `get_item(items, x)`.
2. Check if `x` is within the valid range of indices for `items`.
3. If `x` is valid, return the element at index `x`.
4. If `x` is not valid, return `None`.
- Forgetting to check if x is within the valid range.
- Not handling negative values for x.
Implement the code to solve the algorithm.
def get_item(items, x):
# Check if x is within the valid range
if 0 <= x < len(items):
return items[x]
else:
return None
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Call the function with the provided examples:
print(get_item(["piglet", "pooh", "roo", "rabbit"], 2)) # Expected Output: "roo"
print(get_item(["piglet", "pooh", "roo", "rabbit"], 5)) # Expected Output: None
print(get_item(["piglet", "pooh", "roo", "rabbit"], 0)) # Expected Output: "piglet"
print(get_item(["piglet", "pooh", "roo", "rabbit"], -1)) # Expected Output: None
Expected outputs:
"roo"
None
"piglet"
None
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
- Time Complexity: O(1) since accessing an element by index in a list is a constant time operation.
- Space Complexity: O(1) as no additional data structures are used.