0 out of 464 challenges solved

Find First Occurrence Index

Write a function `find_first_occurrence` that takes a sorted list of integers `A` and an integer `x` as input and returns the index of the first occurrence of `x` in the list. If `x` is not present in the list, the function should return `-1`.

The function should use a binary search approach to achieve an efficient solution.

#### Example Usage
```python [main.nopy]
find_first_occurrence([2, 5, 5, 5, 6, 6, 8, 9, 9, 9], 5)  # Output: 1
find_first_occurrence([2, 3, 5, 5, 6, 6, 8, 9, 9, 9], 5)  # Output: 2
find_first_occurrence([2, 4, 1, 5, 6, 6, 8, 9, 9, 9], 6)  # Output: 4
```

#### Constraints
- The input list `A` is sorted in non-decreasing order.
- The function should have a time complexity of O(log n).
- The function should return `-1` if the element is not found.
def find_first_occurrence(A, x):
    """
    Find the index of the first occurrence of x in the sorted list A.

    Args:
    A (list): A sorted list of integers.
    x (int): The target integer to find.

    Returns:
    int: The index of the first occurrence of x, or -1 if not found.
    """
    # Initialize the search bounds
    left, right = 0, len(A) - 1
    result = -1

    # Implement binary search
    while left <= right:
        mid = (left + right) // 2
        # Placeholder for logic
        pass

    return result
More challenges to try