🎯

First and last position of X

Beginner

Given a sorted array and a target, find the first and last position of that target in the array using binary search.

15-20 min
Level 1 - Easy

First and Last Position of X

Enter the first and last index of the target as a comma-separated pair (e.g. 1,3). If not found, enter -1,-1.

Array:

[1,2,2,2,3,4,5]

Target: 2

Enter First and Last Index:

First and Last Position of X - Pseudo Code

📋 Algorithm Pseudo Code


function findFirstAndLastPosition(arr, target):
    first = -1
    last = -1
    // Find first occurrence
    left = 0
    right = length(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            first = mid
            right = mid - 1
        else if arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    // Find last occurrence
    left = 0
    right = length(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            last = mid
            left = mid + 1
        else if arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return [first, last]
Progress1 / 4
Algorithm:First and Last Position of X
🎯 How to Play

1. Study the array and target shown on the left

2. Enter the first and last index as a comma-separated pair

3. Click "Check Solution" to verify

4. Use Tab to move between fields

5. Click "Next Level" to try more

🔄 Algorithm Steps

Step 1: Use binary search to find the first occurrence of the target

Step 2: Use binary search to find the last occurrence of the target

Step 3: If not found, return -1 for both

📊 Level Info

Difficulty: Easy

Array Size: 7

Target: 2