Challenge - 5 Problems
First and Last Occurrence Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateFind first and last occurrence indexes
What is the output of the following code that finds the first and last occurrence of the number 3 in the list?
DSA Python
def first_last_occurrence(arr, x): first = -1 last = -1 for i in range(len(arr)): if arr[i] == x: if first == -1: first = i last = i return (first, last) arr = [1, 3, 5, 3, 7, 3, 9] x = 3 print(first_last_occurrence(arr, x))
Attempts:
2 left
💡 Hint
Check the positions where 3 appears in the list.
✗ Incorrect
The number 3 appears first at index 1 and last at index 5 in the list.
❓ Predict Output
intermediateOutput of binary search for first occurrence
What will be the output of this code that uses binary search to find the first occurrence of 4 in a sorted list?
DSA Python
def first_occurrence(arr, x): low, high = 0, len(arr) - 1 result = -1 while low <= high: mid = (low + high) // 2 if arr[mid] == x: result = mid high = mid - 1 elif arr[mid] < x: low = mid + 1 else: high = mid - 1 return result arr = [1, 2, 4, 4, 4, 5, 6] x = 4 print(first_occurrence(arr, x))
Attempts:
2 left
💡 Hint
Binary search narrows down to the leftmost index of the target.
✗ Incorrect
The first occurrence of 4 in the list is at index 2.
🔧 Debug
advancedIdentify the error in last occurrence function
What error will this code produce when trying to find the last occurrence of 7 in the list?
DSA Python
def last_occurrence(arr, x): low, high = 0, len(arr) - 1 result = -1 while low <= high: mid = (low + high) // 2 if arr[mid] == x: result = mid low = mid + 1 elif arr[mid] > x: high = mid - 1 else: low = mid + 1 return result arr = [1, 3, 5, 7, 7, 7, 9] x = 7 print(last_occurrence(arr, x))
Attempts:
2 left
💡 Hint
Check the loop conditions and updates of low and high.
✗ Incorrect
The code correctly finds the last occurrence at index 5 without errors.
❓ Predict Output
advancedOutput of first and last occurrence with no element found
What is the output of this code when searching for 10 in the list?
DSA Python
def first_last_occurrence(arr, x): first = -1 last = -1 for i in range(len(arr)): if arr[i] == x: if first == -1: first = i last = i return (first, last) arr = [2, 4, 6, 8] x = 10 print(first_last_occurrence(arr, x))
Attempts:
2 left
💡 Hint
Check what happens if the element is not found in the list.
✗ Incorrect
Since 10 is not in the list, both first and last remain -1.
🧠 Conceptual
expertTime complexity of first and last occurrence using binary search
What is the time complexity of finding the first and last occurrence of an element in a sorted list using binary search?
Attempts:
2 left
💡 Hint
Binary search divides the search space in half each step.
✗ Incorrect
Binary search runs in logarithmic time, so finding first and last occurrence is O(log n).
