Bird
Raised Fist0
DSA C++programming~10 mins

First and Last Occurrence of Element in DSA C++ - Execution Trace

Choose your learning style10 modes available
Concept Flow - First and Last Occurrence of Element
Start
↓
Initialize first = -1, last = -1
↓
Traverse array from i=0 to n-1
↓
Check if array[i
↓
If first == -1, set first = i
↓
Set last = i
↓
Continue traversal
↓
End traversal
↓
Return first and last
We scan the array once, updating first and last positions when we find the target.
Execution Sample
DSA C++
int first = -1, last = -1;
for (int i = 0; i < n; i++) {
  if (arr[i] == target) {
    if (first == -1) first = i;
    last = i;
  }
}
This code finds the first and last positions of target in the array.
Execution Table
StepIndex iarr[i]Condition arr[i]==targetfirstlastActionVisual State
105No-1-1No change[5, 3, 7, 3, 9]
213Yes-1-1first=1, last=1[5, 3, 7, 3, 9]
327No11No change[5, 3, 7, 3, 9]
433Yes11last=3[5, 3, 7, 3, 9]
549No13No change[5, 3, 7, 3, 9]
6End--13Traversal ends[5, 3, 7, 3, 9]
💡 Reached end of array, traversal stops.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5Final
first-1-111111
last-1-111333
i-01234-
Key Moments - 3 Insights
Why do we check if first == -1 before setting it?
Because first should store the earliest index where target appears. We only set it once, at the first occurrence (see Step 2 in execution_table).
Why do we update last every time we find the target?
Because last should always point to the most recent occurrence of target. This updates at every match (see Steps 2 and 4).
What if the target is not in the array at all?
Then first and last remain -1, indicating no occurrence found (see Step 1 and final values).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'first' after Step 2?
A-1
B1
C0
D3
💡 Hint
Check the 'first' column in row for Step 2 in execution_table.
At which step does 'last' get updated to 3?
AStep 4
BStep 5
CStep 3
DStep 2
💡 Hint
Look at the 'last' column and 'Action' in execution_table rows.
If the target was 7 instead of 3, what would be the final value of 'first'?
A1
B-1
C2
D3
💡 Hint
Check where 7 appears in the array and how 'first' is set in execution_table.
Concept Snapshot
Find first and last occurrence of target in array:
- Initialize first and last to -1
- Traverse array once
- If arr[i] == target:
  - If first == -1, set first = i
  - Set last = i
- After traversal, first and last hold positions or -1 if not found
Full Transcript
This concept finds the first and last positions of a target element in an array by scanning it once. We start with first and last set to -1, meaning not found. As we move through the array, when we find the target, if first is still -1, we set it to the current index. We always update last to the current index when we find the target. After the loop ends, first and last tell us where the target first and last appeared. If the target is not found, both remain -1.

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

  1. Step 1: Understand the problem statement

    The problem asks to find the first and last positions of a specific element in an array.
  2. Step 2: Identify what is required

    We need to locate the earliest and latest index where the element appears.
  3. Final Answer:

    The first and last positions where a given element appears -> Option C
  4. 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

  1. Step 1: Check each option for correctness

    int first = -1; for(int i=0; i
  2. 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.
  3. Final Answer:

    int first = -1; for(int i=0; i -> Option B
  4. 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

  1. 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.
  2. Step 2: Confirm output printed

    Prints first and last indices: 1 3.
  3. Final Answer:

    1 3 -> Option D
  4. 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

  1. Step 1: Check the if condition

    The condition uses single '=' which assigns x to arr[i], not compares.
  2. Step 2: Understand impact of assignment in condition

    Assignment returns value of x, which may cause wrong behavior or infinite loop.
  3. Final Answer:

    Using assignment (=) instead of comparison (==) in if condition -> Option A
  4. 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

  1. Step 1: Understand the array is sorted

    Sorted array allows binary search to find elements efficiently.
  2. Step 2: Use binary search twice

    One binary search finds first occurrence, another finds last occurrence in O(log n) time.
  3. Step 3: Compare other options

    Linear search is O(n), sorting again is unnecessary, hash map adds extra space and complexity.
  4. Final Answer:

    Use binary search twice to find first and last positions -> Option A
  5. Quick Check:

    Sorted array + binary search = efficient first/last occurrence [OK]
Hint: Binary search twice on sorted array for first and last occurrence [OK]
Common Mistakes:
  • Using linear search on sorted array
  • Sorting array again unnecessarily
  • Ignoring binary search advantages
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard