Bird
Raised Fist0
DSA Goprogramming~10 mins

First and Last Occurrence of Element in DSA Go - Execution Trace

Choose your learning style10 modes available
Concept Flow - First and Last Occurrence of Element
Start
↓
Initialize first = -1, last = -1
↓
Traverse array from i=0 to n-1
↓
Check if array[i
↓
If first == -1, set first = i
↓
Set last = i
↓
Continue traversal
↓
End traversal
↓
Return first and last
We scan the array once, updating first and last positions when we find the target.
Execution Sample
DSA Go
arr := []int{2, 3, 5, 3, 7}
target := 3
first, last := -1, -1
for i := 0; i < len(arr); i++ {
  if arr[i] == target {
    if first == -1 {
      first = i
    }
    last = i
  }
}
Find first and last index of target 3 in array [2,3,5,3,7]
Execution Table
StepOperationIndex iarr[i]Condition arr[i]==targetfirstlastVisual State
1Initialize----1-1[2, 3, 5, 3, 7]
2Check arr[0]02False-1-1[2, 3, 5, 3, 7]
3Check arr[1]13True11[2, 3, 5, 3, 7]
4Check arr[2]25False11[2, 3, 5, 3, 7]
5Check arr[3]33True13[2, 3, 5, 3, 7]
6Check arr[4]47False13[2, 3, 5, 3, 7]
7End traversal---13[2, 3, 5, 3, 7]
💡 Traversal ends after checking all elements; first=1 and last=3 are returned
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5After Step 6Final
first-1-111111
last-1-111333
i-01234-
Key Moments - 3 Insights
Why do we set first only when it is -1?
Because first occurrence is the earliest index where target appears. Once set, we don't change it. See execution_table rows 3 and 5 where first is set only once.
Why do we update last every time we find the target?
Because last occurrence is the latest index where target appears. We keep updating last to current index when condition is true. See execution_table rows 3 and 5 where last changes.
What if the target is not found at all?
Both first and last remain -1, indicating target is absent. This is shown in execution_table row 2 when condition is false and no updates happen.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 3, what are the values of first and last?
Afirst=-1, last=1
Bfirst=1, last=-1
Cfirst=1, last=1
Dfirst=-1, last=-1
💡 Hint
Check the columns 'first' and 'last' in execution_table row with Step 3
At which step does the last occurrence get updated to index 3?
AStep 5
BStep 3
CStep 2
DStep 6
💡 Hint
Look at 'last' column changes in execution_table rows; last changes to 3 at Step 5
If the target was 10 (not in array), what would be the final values of first and last?
Afirst=0, last=0
Bfirst=-1, last=-1
Cfirst=4, last=4
Dfirst=1, last=3
💡 Hint
Refer to key_moments about target absence and initial values in variable_tracker
Concept Snapshot
First and Last Occurrence of Element:
- Initialize first and last as -1
- Traverse array from start to end
- When element == target:
  - If first == -1, set first = current index
  - Always update last = current index
- After traversal, first and last hold positions or -1 if not found
Full Transcript
This concept finds the first and last positions of a target element in an array. We start with first and last set to -1, meaning not found. We scan the array from left to right. When we find the target, if first is still -1, we set it to current index. We always update last to current index when target matches. After scanning all elements, first and last tell us the earliest and latest positions of the target. If target is not found, both remain -1. This method uses one pass and simple checks.

Practice

(1/5)
1. What does the "First and Last Occurrence of Element" problem ask you to find in an array?
easy
A. The sum of all elements in the array
B. The first and last positions where a given element appears
C. The maximum and minimum values in the array
D. The number of unique elements in the array

Solution

  1. Step 1: Understand the problem statement

    The problem asks to find the first and last positions of a specific element in an array.
  2. 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.
  3. Final Answer:

    The first and last positions where a given element appears -> Option B
  4. Quick Check:

    First and last occurrence = positions [OK]
Hint: Look for positions of element, not sums or counts [OK]
Common Mistakes:
  • Confusing occurrence with sum or count
  • Looking for max/min instead of positions
  • Ignoring the last occurrence
2. Which of the following Go code snippets correctly declares a function to find the first occurrence of an element in a slice?
easy
A. func firstOccurrence(arr []int, x int) int { for _, v := range arr { if v == x { return i } } return -1 }
B. func firstOccurrence(arr []int, x int) int { for i := range arr { if arr[i] = x { return i } } return -1 }
C. func firstOccurrence(arr []int, x int) { for i := 0; i < len(arr); i++ { if arr[i] == x { return i } } return -1 }
D. func firstOccurrence(arr []int, x int) int { for i := 0; i < len(arr); i++ { if arr[i] == x { return i } } return -1 }

Solution

  1. 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.
  2. 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.
  3. 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 D
  4. Quick 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]
Hint: Check function return type and equality operator carefully [OK]
Common Mistakes:
  • Missing return type in function signature
  • Using assignment '=' instead of equality '=='
  • Returning inside a void function
3. What will be the output of the following Go code snippet?
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)
medium
A. 1 3
B. 2 4
C. 1 4
D. 0 3

Solution

  1. 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.
  2. Step 2: Confirm printed values

    Variables first and last hold 1 and 3 respectively, so output is "1 3".
  3. Final Answer:

    1 3 -> Option A
  4. Quick Check:

    First=1, Last=3 for element 4 [OK]
Hint: Track indices where element matches, update first once, last every time [OK]
Common Mistakes:
  • Confusing index positions starting at 0
  • Updating first occurrence multiple times
  • Not updating last occurrence correctly
4. Identify the bug in this Go function that finds the last occurrence of an element in a slice:
func lastOccurrence(arr []int, x int) int {
  last := -1
  for i := 0; i <= len(arr); i++ {
    if arr[i] == x {
      last = i
    }
  }
  return last
}
medium
A. Loop condition should be i < len(arr), not i <= len(arr) to avoid out-of-range error
B. Variable 'last' should be initialized to 0 instead of -1
C. The function should return first occurrence, not last
D. The if condition should use '!=' instead of '=='

Solution

  1. 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.
  2. Step 2: Correct loop condition

    Change to i < len(arr) to safely access elements without error.
  3. Final Answer:

    Loop condition should be i < len(arr), not i <= len(arr) to avoid out-of-range error -> Option A
  4. Quick Check:

    Loop index must be less than length [OK]
Hint: Use i < len(arr) for loops to avoid index errors [OK]
Common Mistakes:
  • Using <= instead of < in loop condition
  • Initializing last to 0 causing wrong default
  • Confusing last occurrence with first
5. Given a sorted slice of integers, which approach is the most efficient to find the first and last occurrence of a target element x?
hard
A. Sort the slice again and then find occurrences linearly
B. Scan the slice from start to end once, record first and last occurrence
C. Use two binary searches: one to find first occurrence, one for last occurrence
D. Use a hash map to store all indices of elements and look up x

Solution

  1. Step 1: Understand the input is sorted

    Since the slice is sorted, binary search can be used to find positions efficiently.
  2. 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.
  3. Step 3: Compare with other options

    Linear scan is O(n), sorting again is unnecessary and costly, hash map adds extra space and complexity.
  4. Final Answer:

    Use two binary searches: one to find first occurrence, one for last occurrence -> Option C
  5. Quick Check:

    Sorted array + binary search = efficient [OK]
Hint: Use binary search twice on sorted data for first and last positions [OK]
Common Mistakes:
  • Using linear scan on sorted data ignoring binary search
  • Sorting already sorted data again
  • Using extra space unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard