Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Find Last Occurrence

Find the last occurrence with a Python index scan. Students update a saved position on every match and use minus one only as a not-found sentinel.

IntermediatePhase 4 - Level 2: Searching & Counting LogicExample 4 of 10
find-last-occurrence.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7x = int(input("Enter element to find: "))
8
9# Find last occurrence
10last_index = -1
11for i in range(len(arr)):
12 if arr[i] == x:
13 last_index = i
14
15if last_index != -1:
16 print(f"Last occurrence at index: {last_index}")
17else:
18 print("Element not found")

Output

Enter array size: 5
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 20
Element 5: 40
Enter element to find: 20
Last occurrence at index: 3

In this one

  • Use a not-found marker
  • Keep the latest match
  • Search every position

How it works

  1. 1

    Initialize last_index to -1.

  2. 2

    Replace it at each index whose value equals x.

  3. 3

    Print it only if the marker changed.

Edge cases

What if there is no match?

What if there is no match?

The marker stays -1 and Element not found prints.

What if x occurs at index zero only?

What if x occurs at index zero only?

Zero replaces the marker and is reported correctly.

What's going on

last_index begins at -1 to mean no match has been seen. The loop visits indexes in increasing order.

Every equality replaces the saved index, so the final one is the last match. The final condition checks the sentinel before printing. Although -1 is a valid Python indexing expression, here it is just a stored marker, not used to access the list.

What if there is no match? The marker stays -1 and Element not found prints.

What if x occurs at index zero only? Zero replaces the marker and is reported correctly.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why not break at the first match?

Pick an answer to check it.

Question 2

What if there is no match?

Pick an answer to check it.

Questions people ask

What if there is no match?

The marker stays -1 and Element not found prints.

What if x occurs at index zero only?

Zero replaces the marker and is reported correctly.

Why not break at the first match?

Later matches must still be found.