0
0
DSA Javascriptprogramming~3 mins

Why First and Last Occurrence of Element in DSA Javascript?

Choose your learning style9 modes available
The Big Idea

What if you could find the first and last place of anything in a list without missing a beat?

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 be tiring and confusing, especially if the list is very long.

The Problem

Manually scanning through the list takes a lot of time and you might miss the first or last spot by mistake.

It's easy to get lost or confused, especially if the name appears many times.

The Solution

Using a simple method to find the first and last place of the name quickly helps you avoid mistakes and saves time.

This method checks the list just once and remembers the first and last spots automatically.

Before vs After
Before
let index = -1;
for (let i = 0; i < arr.length; i++) {
  if (arr[i] === target) {
    index = i; // keeps updating
  }
}
console.log(index);
After
let first = -1, last = -1;
for (let i = 0; i < arr.length; i++) {
  if (arr[i] === target) {
    if (first === -1) first = i;
    last = i;
  }
}
console.log({first, last});
What It Enables

This lets you quickly find the exact start and end positions of any item in a list, making searching easy and reliable.

Real Life Example

Think about searching for a word in a book to see where it first appears and where it last appears to understand its importance or context.

Key Takeaways

Manually searching is slow and error-prone.

Using a simple loop to track first and last positions is fast and accurate.

This method helps in many searching and data analysis tasks.