Find First and Last Position

Read the lesson → understand the pattern → then code. Tutor works offline (built-in teacher); optional Cursor/Gemini keys upgrade chat quality.

Topic refresher: Binary Search — Halve & Conquer

On a sorted range, throw away half each step.

int L = 0, R = n - 1;
while (L <= R) {
    int mid = L + (R - L) / 2;
    if (a[mid] == target) return mid;
    if (a[mid] < target) L = mid + 1;
    else R = mid - 1;
}
return -1;
Binary Search

Find First and Last Position

Medium
LeetCode
3/3
MediumBinary SearchLeetCode #34

First & Last Position

Two binary searches: leftmost and rightmost index of target.

Examples

Example 1

Input

6 8
5 7 7 8 8 10

Output

3 4
Example 2

Input

6 6
5 7 7 8 8 10

Output

-1 -1

Stuck? Take a nudge

C++17