📖 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.
Practice
(1/5)
1. What does the "First and Last Occurrence of Element" problem ask you to find in an array?
easy
A. The maximum and minimum elements in the array
B. The sum of all elements in the array
C. The first and last positions where a given element appears
D. The number of unique elements in the array
Solution
Step 1: Understand the problem statement
The problem asks to find the first and last positions of a specific element in an array.
Step 2: Identify what is required
We need to locate the earliest and latest index where the element appears.
Final Answer:
The first and last positions where a given element appears -> Option C
Quick Check:
First and last occurrence = positions of element [OK]
Hint: Look for earliest and latest index of element [OK]
Common Mistakes:
Confusing with sum or max/min of array
Returning count instead of positions
Ignoring if element is not present
2. Which of the following C++ code snippets correctly finds the first occurrence of element x in vector arr?
easy
A. int first = 0; while(arr[first] != x) { first++; }
B. int first = -1; for(int i=0; i
C. int first = arr.size(); for(int i=0; i
D. int first = -1; for(int i=arr.size()-1; i>=0; i--) { if(arr[i] == x) { first = i; break; } }
Solution
Step 1: Check each option for correctness
int first = -1; for(int i=0; i
Step 2: Identify errors in other options
int first = 0; while(arr[first] != x) { first++; } may cause out-of-bound error if x not found; int first = arr.size(); for(int i=0; i=0; i--) { if(arr[i] == x) { first = i; break; } } finds last occurrence due to reverse loop.
Final Answer:
int first = -1; for(int i=0; i -> Option B
Quick Check:
Loop from start, break on first match = first occurrence [OK]
Hint: Loop forward, break on first match for first occurrence [OK]
Common Mistakes:
Looping backward for first occurrence
Not handling element not found case
Using wrong initial index values
3. What will be the output of the following C++ code?
std::vector<int> arr = {2, 3, 5, 3, 7};
int x = 3;
int first = -1, last = -1;
for(int i=0; i<arr.size(); i++) {
if(arr[i] == x) {
if(first == -1) first = i;
last = i;
}
}
std::cout << first << " " << last << std::endl;
medium
A. 2 3
B. 0 4
C. 1 1
D. 1 3
Solution
Step 1: Trace the loop to find first and last occurrence of 3
Indices: 0->2, 1->3, 2->5, 3->3, 4->7. First 3 at index 1, last 3 at index 3.
Step 2: Confirm output printed
Prints first and last indices: 1 3.
Final Answer:
1 3 -> Option D
Quick Check:
First=1, Last=3 for element 3 [OK]
Hint: Track first set once, update last on every match [OK]
Common Mistakes:
Confusing indices with values
Not updating last occurrence correctly
Printing values instead of indices
4. Identify the bug in this code snippet that tries to find the last occurrence of x in arr:
int last = -1;
for(int i=0; i<arr.size(); i++) {
if(arr[i] = x) {
last = i;
}
}
medium
A. Using assignment (=) instead of comparison (==) in if condition
B. Loop should run backwards from end to start
C. Variable last should be initialized to 0
D. Missing break statement after finding last occurrence
Solution
Step 1: Check the if condition
The condition uses single '=' which assigns x to arr[i], not compares.
Step 2: Understand impact of assignment in condition
Assignment returns value of x, which may cause wrong behavior or infinite loop.
Final Answer:
Using assignment (=) instead of comparison (==) in if condition -> Option A
Quick Check:
Use '==' for comparison, not '=' [OK]
Hint: Use '==' for comparison, '=' is assignment [OK]
Common Mistakes:
Confusing '=' and '==' in conditions
Thinking loop direction causes bug here
Assuming break needed for last occurrence
5. Given a sorted vector arr and an element x, which approach is the most efficient to find the first and last occurrence of x?
hard
A. Use binary search twice to find first and last positions
B. Use linear search from start to end
C. Sort the array again and then find occurrences
D. Use a hash map to store all indices of elements
Solution
Step 1: Understand the array is sorted
Sorted array allows binary search to find elements efficiently.
Step 2: Use binary search twice
One binary search finds first occurrence, another finds last occurrence in O(log n) time.
Step 3: Compare other options
Linear search is O(n), sorting again is unnecessary, hash map adds extra space and complexity.
Final Answer:
Use binary search twice to find first and last positions -> Option A