First and Last Occurrence of Element in DSA C++ - Time & Space Complexity
We want to know how long it takes to find the first and last positions of a number in a list.
How does the time needed change when the list gets bigger?
Analyze the time complexity of the following code snippet.
int firstOccurrence(const vector<int>& arr, int target) {
int start = 0, end = arr.size() - 1, result = -1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (arr[mid] == target) {
result = mid;
end = mid - 1;
} else if (arr[mid] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return result;
}
int lastOccurrence(const vector<int>& arr, int target) {
int start = 0, end = arr.size() - 1, result = -1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (arr[mid] == target) {
result = mid;
start = mid + 1;
} else if (arr[mid] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return result;
}
This code finds the first and last positions of a target number in a sorted list using binary search.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that halves the search range each time.
- How many times: The loop runs about log base 2 of n times, where n is the list size.
Each time the list size doubles, the number of steps increases by only one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 4 steps |
| 100 | About 7 steps |
| 1000 | About 10 steps |
Pattern observation: The steps grow slowly as the list gets bigger, increasing by one each time the size doubles.
Time Complexity: O(log n)
This means the search gets only a little slower even if the list grows a lot.
[X] Wrong: "Finding first and last occurrence takes as long as checking every item one by one."
[OK] Correct: Because the list is sorted, we can jump around and cut the search area in half each time, so we don't check every item.
Knowing how to quickly find positions in sorted data shows you understand efficient searching, a key skill in many coding tasks.
"What if the list was not sorted? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem statement
The problem asks to find the first and last positions of a specific element in an array.Step 2: Identify what is required
We need to locate the earliest and latest index where the element appears.Final Answer:
The first and last positions where a given element appears -> Option CQuick Check:
First and last occurrence = positions of element [OK]
- Confusing with sum or max/min of array
- Returning count instead of positions
- Ignoring if element is not present
x in vector arr?Solution
Step 1: Check each option for correctness
int first = -1; for(int i=0; iStep 2: Identify errors in other options
int first = 0; while(arr[first] != x) { first++; } may cause out-of-bound error if x not found; int first = arr.size(); for(int i=0; i=0; i--) { if(arr[i] == x) { first = i; break; } } finds last occurrence due to reverse loop.Final Answer:
int first = -1; for(int i=0; i -> Option BQuick Check:
Loop from start, break on first match = first occurrence [OK]
- Looping backward for first occurrence
- Not handling element not found case
- Using wrong initial index values
std::vector<int> arr = {2, 3, 5, 3, 7};
int x = 3;
int first = -1, last = -1;
for(int i=0; i<arr.size(); i++) {
if(arr[i] == x) {
if(first == -1) first = i;
last = i;
}
}
std::cout << first << " " << last << std::endl;Solution
Step 1: Trace the loop to find first and last occurrence of 3
Indices: 0->2, 1->3, 2->5, 3->3, 4->7. First 3 at index 1, last 3 at index 3.Step 2: Confirm output printed
Prints first and last indices: 1 3.Final Answer:
1 3 -> Option DQuick Check:
First=1, Last=3 for element 3 [OK]
- Confusing indices with values
- Not updating last occurrence correctly
- Printing values instead of indices
x in arr:int last = -1;
for(int i=0; i<arr.size(); i++) {
if(arr[i] = x) {
last = i;
}
}Solution
Step 1: Check the if condition
The condition uses single '=' which assigns x to arr[i], not compares.Step 2: Understand impact of assignment in condition
Assignment returns value of x, which may cause wrong behavior or infinite loop.Final Answer:
Using assignment (=) instead of comparison (==) in if condition -> Option AQuick Check:
Use '==' for comparison, not '=' [OK]
- Confusing '=' and '==' in conditions
- Thinking loop direction causes bug here
- Assuming break needed for last occurrence
arr and an element x, which approach is the most efficient to find the first and last occurrence of x?Solution
Step 1: Understand the array is sorted
Sorted array allows binary search to find elements efficiently.Step 2: Use binary search twice
One binary search finds first occurrence, another finds last occurrence in O(log n) time.Step 3: Compare other options
Linear search is O(n), sorting again is unnecessary, hash map adds extra space and complexity.Final Answer:
Use binary search twice to find first and last positions -> Option AQuick Check:
Sorted array + binary search = efficient first/last occurrence [OK]
- Using linear search on sorted array
- Sorting array again unnecessarily
- Ignoring binary search advantages
Ready to prove it?
Pass the test and this pattern moves unknown
