First and Last Occurrence of Element in DSA Python - Time & Space Complexity
We want to know how long it takes to find the first and last place a number appears in a list.
How does the time needed change when the list gets bigger?
Analyze the time complexity of the following code snippet.
def first_and_last_occurrence(arr, target):
first = -1
last = -1
for i in range(len(arr)):
if arr[i] == target:
if first == -1:
first = i
last = i
return first, last
This code finds the first and last positions of a target number in a list by checking each item once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: One loop that goes through each item in the list once.
- How many times: Exactly as many times as there are items in the list (n times).
As the list gets bigger, the time to check all items grows directly with the size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of operations grows in a straight line with the input size.
Time Complexity: O(n)
This means the time to find the first and last occurrence grows directly with the number of items in the list.
[X] Wrong: "Since we stop after finding the first occurrence, the time is always less than n."
[OK] Correct: The code keeps checking all items to find the last occurrence, so it must look at every item in the worst case.
Understanding how to find positions in a list efficiently is a common skill that shows you can analyze simple loops and their costs.
"What if we used binary search on a sorted list to find the first and last occurrence? How would the time complexity change?"
Practice
first occurrence of an element in a list mean?Solution
Step 1: Understand the meaning of first occurrence
The first occurrence means the earliest position (index) where the element appears in the list when reading from left to right.Step 2: Compare with other options
Other options describe last occurrence, count, or smallest value, which are different concepts.Final Answer:
The index where the element appears first in the list -> Option CQuick Check:
First occurrence = first index [OK]
- Confusing first occurrence with last occurrence
- Thinking it means the count of the element
- Mixing occurrence with element value
5 in list arr?Solution
Step 1: Recall Python list methods
Python lists have the methodindex()to find the first occurrence index of an element.Step 2: Check other options
Methodsfind(),search(), andlocate()do not exist for Python lists.Final Answer:
arr.index(5) -> Option BQuick Check:
Use list.index(element) to find first occurrence [OK]
- Using non-existent methods like find or search on lists
- Confusing string methods with list methods
- Trying to use index without handling exceptions
arr = [2, 4, 5, 4, 5, 6] first = arr.index(4) last = len(arr) - 1 - arr[::-1].index(4) print([first, last])
Solution
Step 1: Find first occurrence of 4
Usingarr.index(4)returns 1 because 4 first appears at index 1.Step 2: Find last occurrence of 4
arr[::-1]reverses the list to [6, 5, 4, 5, 4, 2]. The first index of 4 in reversed list is 2. So last occurrence index = len(arr) - 1 - 2 = 6 - 1 - 2 = 3.Final Answer:
[1, 3] -> Option AQuick Check:
First = 1, Last = 3 [OK]
- Mixing up reversed index with original index
- Using last = arr.index(4) instead of reversed search
- Confusing first and last occurrence indexes
7 in list nums. What is the error?nums = [1, 7, 3, 7, 5] first = nums.index(7) last = nums.index(7, -1) print(first, last)
Solution
Step 1: Understand index() with start parameter
Theindex()method can take a start index. Using -1 as start means start searching from the last element only.Step 2: Identify the error in last occurrence search
Usingnums.index(7, -1)starts searching from index -1 (last element), so it only checks last element which is 5, not 7, causing ValueError.Final Answer:
The second index() call should use a positive start index -> Option DQuick Check:
index(start=-1) limits search to last element [OK]
- Using negative start index in list.index()
- Expecting index() to find last occurrence without correct start
- Not handling ValueError when element not found
data = [1, 2, 2, 2, 3, 4, 5], which approach is best to find the first and last occurrence of 2 efficiently?Solution
Step 1: Understand the list is sorted
Since the list is sorted, binary search can be used to find positions efficiently in O(log n) time.Step 2: Compare approaches
Linear search (Use linear search from start and end to find occurrences) is slower (O(n)). Using list.index() and reversed index() (Use list.index() and reversed list index() methods) is also linear. count() (Use count() method to find number of occurrences) gives count but not positions.Step 3: Best approach
Binary search can be adapted to find first and last occurrence indexes quickly.Final Answer:
Use binary search to find first and last occurrence -> Option AQuick Check:
Sorted list + binary search = efficient occurrence search [OK]
- Using linear search on sorted lists
- Using count() instead of finding indexes
- Not leveraging sorted property for efficiency
Ready to prove it?
Pass the test and this pattern moves unknown
