ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Binary Search for First Occurrence

TypeScript

Goal -- WPM

Ready
Exercise Algorithm Area
1/**
2* Finds the index of the first occurrence of a target value in a sorted array.
3* If the target is not found, returns -1.
4*
5* @param arr The sorted array of numbers.
6* @param target The value to search for.
7* @returns The index of the first occurrence of the target, or -1 if not found.
8*/
9function findFirstOccurrence(arr: number[], target: number): number {
10let low = 0;
11let high = arr.length - 1;
12let result = -1;
13
14// Handle edge case: empty array.
15if (arr.length === 0) {
16return -1;
17}
18
19while (low <= high) {
20// Calculate mid point to avoid potential overflow.
21const mid = low + Math.floor((high - low) / 2);
22
23if (arr[mid] === target) {
24// Found a potential first occurrence.
25// Store this index and try to find an earlier one by searching the left half.
26result = mid;
27high = mid - 1;
28} else if (arr[mid] < target) {
29// Target is in the right half.
30low = mid + 1;
31} else {
32// Target is in the left half.
33high = mid - 1;
34}
35}
36
37return result;
38}
39
40/**
41* Helper function to demonstrate the search on a sample array.
42* This is for illustrative purposes and not part of the core algorithm.
43* @param arr The sorted array.
44* @param target The target value.
45*/
46function demonstrateFindFirstOccurrence(arr: number[], target: number): void {
47console.log(`Searching for first occurrence of ${target} in [${arr.join(', ')}]`);
48const index = findFirstOccurrence(arr, target);
49if (index !== -1) {
50console.log(`First occurrence found at index: ${index}`);
51} else {
52console.log('Target not found.');
53}
54}
55
56// Example Usage:
57// const sortedArray = [2, 5, 5, 5, 6, 6, 8, 9, 9, 9];
58// demonstrateFindFirstOccurrence(sortedArray, 5);
59// demonstrateFindFirstOccurrence(sortedArray, 6);
60// demonstrateFindFirstOccurrence(sortedArray, 9);
61// demonstrateFindFirstOccurrence(sortedArray, 4);
62// demonstrateFindFirstOccurrence([], 5);
Algorithm description viewbox

Binary Search for First Occurrence

Algorithm description:

This function implements a modified binary search algorithm to find the index of the first occurrence of a specific target value within a sorted array. If the target value appears multiple times, it specifically returns the index of its earliest appearance. This is crucial for applications requiring precise identification of elements, such as in data indexing, searching for the start of a range, or in algorithms that depend on the first instance of a condition.

Algorithm explanation:

The `findFirstOccurrence` function adapts the standard binary search. When the `target` is found at `mid`, instead of terminating, it records `mid` as a potential `result` and continues searching in the left half (`high = mid - 1`) to find an even earlier occurrence. If `arr[mid]` is less than `target`, the search continues in the right half (`low = mid + 1`). If `arr[mid]` is greater than `target`, the search continues in the left half (`high = mid - 1`). The loop terminates when `low` exceeds `high`. The `result` variable holds the index of the first occurrence found, or -1 if the target was never encountered. The time complexity is O(log N) because it's a binary search. The space complexity is O(1) as it uses a constant amount of extra space.

Pseudocode:

function findFirstOccurrence(array, target):
  low = 0
  high = length of array - 1
  result = -1

  if array is empty:
    return -1

  while low <= high:
    mid = low + floor((high - low) / 2)

    if array[mid] == target:
      result = mid
      high = mid - 1 // Try to find an earlier occurrence to the left
    else if array[mid] < target:
      low = mid + 1 // Target is in the right half
    else:
      high = mid - 1 // Target is in the left half

  return result