Discover how to instantly pinpoint where something starts and ends in a list without endless searching!
Why First and Last Occurrence of Element in DSA Typescript?
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.
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.
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.
let index = -1; for(let i = 0; i < arr.length; i++) { if(arr[i] === target) { index = i; break; } }
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];
}This lets you quickly find the exact range where an element appears, enabling faster data analysis and decision-making.
In a list of daily temperatures, finding the first and last day a certain temperature occurred helps understand weather patterns.
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.