ADVANCED DATA STRUCTURES PROGRAM • LEVEL 13 — ADVANCED SEARCHING

Find First and Last Occurrences

Learn how to find first and last occurrences using a clear C program.

IntermediateBinary searchSearch boundaries

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
First = 1 Last = 3

COMPLETE C PROGRAM

Complete C implementation

ads-first-last-occurrence-binary-search.c
Open in compiler
#include <stdio.h>

int boundary(const int values[], int count, int target, int first)
{
    int low = 0, high = count - 1, answer = -1;
    while (low <= high) { int middle = low + (high - low) / 2; if (values[middle] == target) { answer = middle; if (first) high = middle - 1; else low = middle + 1; } else if (values[middle] < target) low = middle + 1; else high = middle - 1; }
    return answer;
}

int main(void)
{
    int values[] = {1, 2, 2, 2, 4, 7}, target = 2;
    int first = boundary(values, 6, target, 1), last = boundary(values, 6, target, 0);
    printf("First = %d Last = %d\n", first, last); return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

First = 1 Last = 3
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Run two biased binary searches, continuing left after a match for first and right for last.
  3. Display the computed result.

Run two biased binary searches, continuing left after a match for first and right for last.

EFFICIENCY

Time and space complexity

Time complexity

O(log n)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.