easy +10 pts

Last Occurrence of a Value

Find the last index where a value appears in a list, or return -1.

Write a function `last_occurrence(values, target)` that takes a list of values (which may be integers, strings, or other comparable items) and a target value. The function should return the index (0-based) of the **last** occurrence of `target` in the list. If the target is not present, return `-1`. Your function should not use the built-in `list.index()` method or any other helper that directly finds the index. Instead, implement the search logic yourself. Examples: - `last_occurrence([1, 2, 3, 2, 1], 2)` should return `3`. - `last_occurrence(['apple', 'banana', 'apple'], 'apple')` should return `2`. - `last_occurrence([], 5)` should return `-1`. Ensure your function handles empty lists and missing targets correctly.

Constraints

The input list can contain any comparable elements (e.g., integers, strings). The list length can be up to 10^5. Time complexity should be O(n), where n is the list length. Memory usage O(1) aside from the input.

Example

>>> last_occurrence([1, 2, 3, 2, 1], 2)
3
>>> last_occurrence([])
-1
>>> last_occurrence([5, 6, 5], 5)
2
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Iterate over the list and update the result whenever you find a matching element.
Initialize the result to -1 so it naturally becomes the answer if no match is found.
Since you want the last index, you can iterate from the end of the list and return the first match, or iterate from the beginning and keep updating.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.