-
Notifications
You must be signed in to change notification settings - Fork 254
Hunny Hunt
Raymond Chen edited this page Aug 1, 2024
·
5 revisions
TIP102 Unit 1 Session 1 Advanced (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 5 mins
- 🛠️ Topics: Lists, Linear Search, Iteration
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
linear_search()
should take a list of items and atarget
value, returning the first index of target initems
. If target is not found, it should return -1. Built-in functions should not be used.
HAPPY CASE
Input: items = ['haycorn', 'haycorn', 'haycorn', 'hunny'], target = 'hunny'
Expected Output: 3
Input: items = ['bed', 'blue jacket', 'red shirt', 'hunny'], target = 'red balloon'
Expected Output: -1
EDGE CASE
Input: items = [], target = 'hunny'
Expected Output: -1
Input: items = ['hunny'], target = 'hunny'
Expected Output: 0
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use a ranged for loop to iterate through the list, checking each element against the target.
1. Define the function `linear_search(items, target)`.
2. Iterate through the list using a ranged for loop based on the length of `items`.
3. For each index, check if the current element matches the target.
4. If a match is found, return the index.
5. If the loop completes without finding a match, return -1.
- Forgetting to handle the case of an empty list.
- Not returning the index for the first occurrence of the target.
Implement the code to solve the algorithm.
def linear_search(items, target):
# Iterate through the list with a ranged for loop
for index in range(len(items)):
# Check if the current element matches the target
if items[index] == target:
return index # Return the index if target is found
# If target is not found, return -1
return -1