0
0
DSA Typescriptprogramming~15 mins

First and Last Occurrence of Element in DSA Typescript - 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 sold in a store during a day. Some products appear multiple times because they were sold multiple times.You want to find the first and last time a specific product was sold to understand its sales pattern.
🎯 Goal: Build a program that finds the first and last position of a given product ID in the sales list.
📋 What You'll Learn
Create an array called sales with the exact product IDs: [101, 203, 101, 405, 203, 101, 507]
Create a variable called targetProduct and set it to 101
Write a loop to find the first and last index of targetProduct in sales
Print the first and last occurrence indexes in the format: First occurrence: X, Last occurrence: Y
💡 Why This Matters
🌍 Real World
Stores and businesses often analyze sales data to understand when products are sold during the day. Finding first and last occurrences helps in tracking product demand and stock management.
💼 Career
This skill is useful for data analysts, software developers, and anyone working with data searching and processing in real-world applications.
Progress0 / 4 steps
1
Create the sales data array
Create an array called sales with these exact product IDs: [101, 203, 101, 405, 203, 101, 507]
DSA Typescript
Hint

Use const sales = [101, 203, 101, 405, 203, 101, 507]; to create the array.

2
Set the target product ID
Create a variable called targetProduct and set it to 101
DSA Typescript
Hint

Use const targetProduct = 101; to set the product ID.

3
Find first and last occurrence indexes
Write a for loop with variable i from 0 to sales.length - 1 to find the first and last index of targetProduct in sales. Use variables firstIndex and lastIndex initialized to -1 before the loop. Update firstIndex when you find the first match, and update lastIndex every time you find a match.
DSA Typescript
Hint

Use a for loop and check each element. Set firstIndex only once when you find the first match. Update lastIndex every time you find a match.

4
Print the first and last occurrence
Print the first and last occurrence indexes using console.log in this exact format: First occurrence: X, Last occurrence: Y where X is firstIndex and Y is lastIndex
DSA Typescript
Hint

Use console.log(`First occurrence: ${firstIndex}, Last occurrence: ${lastIndex}`); to print the result.