On this page
List Occurrences
TIP101 Unit 1 Session 2 (Click for link to problem statements)
U-nderstand
Understand what the interviewer is asking for by using test cases and questions about the problem.
- What are the inputs?
- A list
lstand atargetvalue.
- A list
- What should the function return?
- A list of every index where
targetappears inlst, from smallest to largest.
- A list of every index where
- What if the target does not appear in the list?
- Return an empty list.
HAPPY CASE
Input: lst = [5, 3, 5, 1, 5], target = 5
Output: [0, 2, 4]
Explanation: 5 appears at indices 0, 2 and 4.
EDGE CASE
Input: lst = [1, 2, 3], target = 7
Output: []
Explanation: 7 is not in the list, so there are no indices to return.
P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Loop through a list of numbers, and if a number matches the target, add its index to a results list.
1) Create an empty list to hold the results
2) Loop through the indices of the input list
a) If the element at that index matches the target, add the index to the results list
3) Return the results list
⚠️ Common Mistakes
- Be sure you are adding the INDEX of each match to your results list – not the match itself!
I-mplement
def find_all_occurrences(lst, target):
indices = []
for i in range(len(lst)):
if lst[i] == target:
indices.append(i)
return indices