0
0
DSA C++programming~30 mins

First and Last Occurrence of Element in DSA C++ - Build from Scratch

Choose your learning style9 modes available
First and Last Occurrence of Element
📖 Scenario: You have a list of numbers representing daily temperatures recorded over several days. You want to find the first and last day a specific temperature was recorded.
🎯 Goal: Build a program that finds the first and last position of a given temperature in the list.
📋 What You'll Learn
Create a vector called temperatures with the exact values: 23, 25, 23, 22, 25, 23, 24
Create an integer variable called target and set it to 23
Write a loop to find the first occurrence index of target in temperatures
Write a loop to find the last occurrence index of target in temperatures
Print the first and last occurrence indices separated by a space
💡 Why This Matters
🌍 Real World
Finding the first and last occurrence of an element is useful in analyzing time series data, logs, or any ordered data to know when an event started and ended.
💼 Career
This skill is important for software developers and data analysts who work with arrays or lists and need to locate specific data points efficiently.
Progress0 / 4 steps
1
Create the temperature list
Create a vector of integers called temperatures with these exact values: 23, 25, 23, 22, 25, 23, 24
DSA C++
Hint

Use std::vector<int> and initialize it with the given numbers inside curly braces.

2
Set the target temperature
Create an integer variable called target and set it to 23
DSA C++
Hint

Use int target = 23; to create the variable.

3
Find first and last occurrence of target
Write a loop to find the first occurrence index of target in temperatures and store it in firstIndex. Then write a loop to find the last occurrence index of target in temperatures and store it in lastIndex. If target is not found, set both indices to -1.
DSA C++
Hint

Use two separate loops: one from start to find firstIndex, one from end to find lastIndex. Initialize both to -1 before loops.

4
Print the first and last occurrence indices
Print the values of firstIndex and lastIndex separated by a space.
DSA C++
Hint

Use std::cout << firstIndex << " " << lastIndex << std::endl; to print the indices.