First and Last Occurrence of Element in DSA Go - 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.
func firstAndLastOccurrence(arr []int, target int) (int, int) {
first, last := -1, -1
for i := 0; i < len(arr); i++ {
if arr[i] == target {
if first == -1 {
first = i
}
last = i
}
}
return first, last
}
This code finds the first and last places where the target number appears in the list.
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 once for each item in the list, from start to end.
As the list gets bigger, the time to check each item grows directly with the size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of checks grows evenly as the list grows.
Time Complexity: O(n)
This means the time needed grows in a straight line with the size of the list.
[X] Wrong: "Since we only want first and last, we can stop early and the time is always small."
[OK] Correct: The code checks every item to find the last occurrence, so it must look at the whole list in the worst case.
Understanding this helps you explain how searching through data works and shows you can analyze simple loops clearly.
"What if we used binary search on a sorted list to find the first and last occurrence? 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 return the indices of the first and last occurrence of the element, not sums or counts.Final Answer:
The first and last positions where a given element appears -> Option BQuick Check:
First and last occurrence = positions [OK]
- Confusing occurrence with sum or count
- Looking for max/min instead of positions
- Ignoring the last occurrence
Solution
Step 1: Check function signature and return type
The function must return an int index, so signature must be func firstOccurrence(arr []int, x int) int.Step 2: Verify loop and condition syntax
func firstOccurrence(arr []int, x int) int { for i := 0; i < len(arr); i++ { if arr[i] == x { return i } } return -1 } uses a for loop with index and correct equality check (arr[i] == x) and returns index or -1.Final Answer:
func firstOccurrence(arr []int, x int) int { for i := 0; i < len(arr); i++ { if arr[i] == x { return i } } return -1 } -> Option DQuick Check:
Correct syntax and return type = func firstOccurrence(arr []int, x int) int { for i := 0; i < len(arr); i++ { if arr[i] == x { return i } } return -1 } [OK]
- Missing return type in function signature
- Using assignment '=' instead of equality '=='
- Returning inside a void function
arr := []int{2, 4, 4, 4, 6, 7}
first := -1
last := -1
x := 4
for i, v := range arr {
if v == x {
if first == -1 {
first = i
}
last = i
}
}
fmt.Println(first, last)Solution
Step 1: Trace the loop to find first and last occurrence of 4
Indices with value 4 are 1, 2, 3. First occurrence is 1, last occurrence is 3.Step 2: Confirm printed values
Variables first and last hold 1 and 3 respectively, so output is "1 3".Final Answer:
1 3 -> Option AQuick Check:
First=1, Last=3 for element 4 [OK]
- Confusing index positions starting at 0
- Updating first occurrence multiple times
- Not updating last occurrence correctly
func lastOccurrence(arr []int, x int) int {
last := -1
for i := 0; i <= len(arr); i++ {
if arr[i] == x {
last = i
}
}
return last
}Solution
Step 1: Check loop boundary conditions
The loop uses i <= len(arr), which causes index out-of-range error because valid indices are 0 to len(arr)-1.Step 2: Correct loop condition
Change to i < len(arr) to safely access elements without error.Final Answer:
Loop condition should be i < len(arr), not i <= len(arr) to avoid out-of-range error -> Option AQuick Check:
Loop index must be less than length [OK]
- Using <= instead of < in loop condition
- Initializing last to 0 causing wrong default
- Confusing last occurrence with first
x?Solution
Step 1: Understand the input is sorted
Since the slice is sorted, binary search can be used to find positions efficiently.Step 2: Use two binary searches
One binary search finds the first occurrence, another finds the last occurrence of x in O(log n) time.Step 3: Compare with other options
Linear scan is O(n), sorting again is unnecessary and costly, hash map adds extra space and complexity.Final Answer:
Use two binary searches: one to find first occurrence, one for last occurrence -> Option CQuick Check:
Sorted array + binary search = efficient [OK]
- Using linear scan on sorted data ignoring binary search
- Sorting already sorted data again
- Using extra space unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
