0
0
DSA Goprogramming~3 mins

Why First and Last Occurrence of Element in DSA Go?

Choose your learning style9 modes available
The Big Idea

Discover how to find exactly where something starts and ends in a list without endless searching!

The Scenario

Imagine you have a long list of names and you want to find where a particular name first appears and where it appears last.

Doing this by looking at each name one by one can take a lot of time and effort.

The Problem

Manually checking each item is slow and easy to make mistakes, especially if the list is very long.

You might miss the first or last place the name appears or spend too much time scanning.

The Solution

Using a method to find the first and last occurrence quickly helps you get the exact positions without checking every item manually.

This saves time and reduces errors.

Before vs After
Before
for i := 0; i < len(list); i++ {
    if list[i] == target {
        fmt.Println("Found at", i)
        break
    }
}
After
first := findFirstOccurrence(list, target)
last := findLastOccurrence(list, target)
fmt.Println("First at", first, "Last at", last)
What It Enables

This lets you quickly know where an item starts and ends in a list, enabling faster searches and better data handling.

Real Life Example

When checking attendance records, you can find the first and last time a student signed in without scanning the whole list manually.

Key Takeaways

Manual search is slow and error-prone.

Finding first and last occurrence speeds up locating items.

Useful in many real-world list and data searches.