0
0
DSA Goprogramming~30 mins

First and Last Occurrence of Element in DSA Go - Build from Scratch

Choose your learning style9 modes available
First and Last Occurrence of Element
📖 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.