0
0
DSA Typescriptprogramming~3 mins

Why First and Last Occurrence of Element in DSA Typescript?

Choose your learning style9 modes available
The Big Idea

Discover how to instantly pinpoint where something starts and ends in a list without endless searching!

The Scenario

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

Doing this by scanning the list every time someone asks is tiring and slow.

The Problem

Manually searching through the list means checking each name one by one.

This takes a lot of time if the list is long, and you might lose track or make mistakes.

The Solution

Using the method to find the first and last occurrence of an element helps you quickly locate where the element starts and ends in the list.

This saves time and reduces errors by automating the search.

Before vs After
Before
let index = -1;
for(let i = 0; i < arr.length; i++) {
  if(arr[i] === target) {
    index = i;
    break;
  }
}
After
function findFirstAndLast(arr: number[], target: number): [number, number] {
  let first = -1, last = -1;
  for(let i = 0; i < arr.length; i++) {
    if(arr[i] === target) {
      if(first === -1) first = i;
      last = i;
    }
  }
  return [first, last];
}
What It Enables

This lets you quickly find the exact range where an element appears, enabling faster data analysis and decision-making.

Real Life Example

In a list of daily temperatures, finding the first and last day a certain temperature occurred helps understand weather patterns.

Key Takeaways

Manual search is slow and error-prone for large lists.

Finding first and last occurrence automates and speeds up locating elements.

This method helps in many real-world data tracking tasks.