📖 Scenario: You are working with a list of product IDs scanned at a store checkout. Some products appear multiple times. You want to find the first and last time a specific product was scanned.
🎯 Goal: Build a Go program that finds the first and last position of a given product ID in a list.
📋 What You'll Learn
Create a slice of integers called products with the exact values: 101, 203, 101, 405, 203, 101
Create an integer variable called target and set it to 101
Write a loop to find the first and last index of target in products
Print the first and last occurrence indices in the format: First: X, Last: Y
💡 Why This Matters
🌍 Real World
Finding first and last occurrences helps in searching logs, tracking events, or analyzing repeated data in real applications.
💼 Career
This skill is useful for software developers working with arrays, slices, or lists to analyze data and implement search features.
Progress0 / 4 steps
1
Create the product list
Create a slice of integers called products with these exact values: 101, 203, 101, 405, 203, 101
DSA Go
Hint
Use products := []int{101, 203, 101, 405, 203, 101} to create the slice.
2
Set the target product ID
Create an integer variable called target and set it to 101
DSA Go
Hint
Use target := 101 to create the variable.
3
Find first and last occurrence
Write a for loop with index i and value p to iterate over products. Inside the loop, find the first and last index of target and store them in variables first and last. Initialize first to -1 before the loop.
DSA Go
Hint
Use for i, p := range products and check if p == target. Set first only once, update last each time.
4
Print the first and last occurrence
Print the first and last occurrence indices using fmt.Printf in this exact format: First: X, Last: Y where X and Y are the values of first and last.
DSA Go
Hint
Use fmt.Printf("First: %d, Last: %d\n", first, last) to print the result.
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
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 B
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
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 D
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
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 A
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
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 A
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
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 C
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 unknownstrongwhile earning +1 Grip toward your certificate.