CoreTechED

Loading

Max Distance Between Two Occurrences in C

Max Distance Between Two Occurrences in C: A Comprehensive Tutorial

Finding the maximum distance between two occurrences of any element in an array is a classic problem that combines array traversal with hash-based indexing. It demonstrates how hashing transforms an O(n²) brute-force scan into a clean O(n) algorithm.

This tutorial provides an in-depth exploration of the maximum distance problem in C: fundamental concepts, naive and optimized approaches, complete implementations with a hand-rolled hash map, common pitfalls, and best practices.


Conceptual Introduction & Fundamentals

What is the Problem?

Given an array arr[], find the maximum distance j - i such that arr[i] == arr[j] and i < j. If no element occurs at least twice, return 0.

Examples:

text

Input: [1, 1, 2, 2, 2, 1] Output: 5 (element 1 at indices 0 and 5) Input: [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2] Output: 10 (element 2 at indices 1 and 11) Input: [1, 2, 3, 6, 5, 4] Output: 0 (all elements distinct)

Why This Problem Matters

  • Hashing application: Directly applies hash maps for indexing.
  • Two-pass versus one-pass: Shows the value of remembering earlier positions.
  • Time–space trade-off: O(n²) → O(n) time with O(n) space.
  • Interview preparation: Common coding interview question.
  • Real-world relevance: Used in log analysis, sequence alignment, and data deduplication.

Key Insight

To maximize j - i for a given value, we want:

  • The earliest index i where it appears.
  • The latest index j where it appears.

So for each element, store only its first occurrence index. On every subsequent occurrence, compute the distance to that stored index and update the maximum.

Approaches Overview

ApproachTime ComplexitySpace Complexity
Naive nested loopsO(n²)O(1)
Hash map (first occurrence)O(n) averageO(n)

Syntax & Core Mechanics

Approach 1: Naive Nested Loops

Compare every pair (i, j) with i < j.

c

#include <stdio.h> int maxDistanceNaive(const int arr[], int n) { int best = 0; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { int d = j - i; if (d > best) best = d; } } } return best; } int main(void) { int arr[] = {1, 1, 2, 2, 2, 1}; int n = sizeof(arr) / sizeof(arr[0]); printf("%d\n", maxDistanceNaive(arr, n)); return 0; }

Expected output:

text

5

Time: O(n²), Space: O(1)

Approach 2: Hash Map (First-Occurrence Tracking)

Store the first index of each distinct value. On subsequent occurrences, update the best distance.

c

#include <stdio.h> #include <stdlib.h> #define TABLE_SIZE 4096 typedef struct { int *keys; int *firstIndex; int *occupied; int capacity; } FirstIndexMap; static unsigned int hashFunc(int key, int capacity) { return ((unsigned int)key) % (unsigned int)capacity; } FirstIndexMap *createMap(int capacity) { FirstIndexMap *m = malloc(sizeof(FirstIndexMap)); if (m == NULL) return NULL; m->keys = malloc(capacity * sizeof(int)); m->firstIndex = malloc(capacity * sizeof(int)); m->occupied = calloc(capacity, sizeof(int)); if (m->keys == NULL || m->firstIndex == NULL || m->occupied == NULL) { free(m->keys); free(m->firstIndex); free(m->occupied); free(m); return NULL; } m->capacity = capacity; return m; } void freeMap(FirstIndexMap *m) { if (m) { free(m->keys); free(m->firstIndex); free(m->occupied); free(m); } } /* Returns 1 and sets *outIndex if found, else 0 */ int mapGet(FirstIndexMap *m, int key, int *outIndex) { unsigned int idx = hashFunc(key, m->capacity); int start = (int)idx; while (m->occupied[idx]) { if (m->keys[idx] == key) { *outIndex = m->firstIndex[idx]; return 1; } idx = (idx + 1) % (unsigned int)m->capacity; if ((int)idx == start) break; } return 0; } void mapPut(FirstIndexMap *m, int key, int index) { unsigned int idx = hashFunc(key, m->capacity); int start = (int)idx; while (m->occupied[idx]) { if (m->keys[idx] == key) return; /* Already stored */ idx = (idx + 1) % (unsigned int)m->capacity; if ((int)idx == start) return; } m->keys[idx] = key; m->firstIndex[idx] = index; m->occupied[idx] = 1; } int maxDistanceHash(const int arr[], int n) { FirstIndexMap *m = createMap(TABLE_SIZE); if (m == NULL) return -1; int best = 0; for (int i = 0; i < n; i++) { int firstIdx; if (mapGet(m, arr[i], &firstIdx)) { int d = i - firstIdx; if (d > best) best = d; } else { mapPut(m, arr[i], i); } } freeMap(m); return best; } int main(void) { int arr[] = {1, 1, 2, 2, 2, 1}; int n = sizeof(arr) / sizeof(arr[0]); printf("%d\n", maxDistanceHash(arr, n)); return 0; }

Expected output:

text

5

Time: O(n) average, Space: O(n)

Why Only the First Occurrence?

For any value v occurring at indices i₁ < i₂ < ... < iₖ:

  • The maximum distance uses the smallest i (i.e., i₁) and the largest j (i.e., iₖ).
  • So we only need to remember i₁. Each later occurrence compares against it.

Handling Negative Values

The hash function casts to unsigned int so negatives map safely.

c

return ((unsigned int)key) % capacity;

Full Practical Code Example with Explanation

This program compares both approaches and verifies them on multiple datasets.

c

/** * max_distance.c * Finds the maximum distance between two occurrences of any element. * Compares naive (O(n^2)) and hash-based (O(n)) approaches. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <time.h> #define MAX_LINE_LEN 100 #define TABLE_SIZE 65536 /* Prime-like, high capacity */ /* ---------- Approach 1: Naive ---------- */ int maxDistanceNaive(const int arr[], int n) { int best = 0; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { int d = j - i; if (d > best) best = d; } } } return best; } /* ---------- Approach 2: Hash Map ---------- */ typedef struct { int *keys; int *firstIndex; int *occupied; int capacity; int size; } FirstIndexMap; static unsigned int hashFunc(int key, int capacity) { return ((unsigned int)key) % (unsigned int)capacity; } FirstIndexMap *createMap(int capacity) { FirstIndexMap *m = malloc(sizeof(FirstIndexMap)); if (m == NULL) return NULL; m->keys = malloc(capacity * sizeof(int)); m->firstIndex = malloc(capacity * sizeof(int)); m->occupied = calloc(capacity, sizeof(int)); if (m->keys == NULL || m->firstIndex == NULL || m->occupied == NULL) { free(m->keys); free(m->firstIndex); free(m->occupied); free(m); return NULL; } m->capacity = capacity; m->size = 0; return m; } void freeMap(FirstIndexMap *m) { if (m) { free(m->keys); free(m->firstIndex); free(m->occupied); free(m); } } int mapGet(FirstIndexMap *m, int key, int *outIndex) { unsigned int idx = hashFunc(key, m->capacity); int start = (int)idx; while (m->occupied[idx]) { if (m->keys[idx] == key) { *outIndex = m->firstIndex[idx]; return 1; } idx = (idx + 1) % (unsigned int)m->capacity; if ((int)idx == start) break; } return 0; } void mapPut(FirstIndexMap *m, int key, int index) { unsigned int idx = hashFunc(key, m->capacity); int start = (int)idx; while (m->occupied[idx]) { if (m->keys[idx] == key) return; idx = (idx + 1) % (unsigned int)m->capacity; if ((int)idx == start) return; } m->keys[idx] = key; m->firstIndex[idx] = index; m->occupied[idx] = 1; m->size++; } int maxDistanceHash(const int arr[], int n) { FirstIndexMap *m = createMap(TABLE_SIZE); if (m == NULL) return -1; int best = 0; for (int i = 0; i < n; i++) { int firstIdx; if (mapGet(m, arr[i], &firstIdx)) { int d = i - firstIdx; if (d > best) best = d; } else { mapPut(m, arr[i], i); } } freeMap(m); return best; } /* ---------- Utility ---------- */ void printArray(const int arr[], int n) { printf("["); for (int i = 0; i < n; i++) { printf("%d", arr[i]); if (i < n - 1) printf(", "); } printf("]\n"); } static void demoBasic(void) { printf("\n=== Sample Arrays ===\n"); int arr1[] = {1, 1, 2, 2, 2, 1}; int arr2[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}; int arr3[] = {1, 2, 3, 6, 5, 4}; int arr4[] = {1, 2, 4, 1, 3, 4, 2, 5, 6, 5}; struct { int *arr; int n; } tests[] = { {arr1, 6}, {arr2, 12}, {arr3, 6}, {arr4, 10} }; int numTests = sizeof(tests) / sizeof(tests[0]); for (int t = 0; t < numTests; t++) { printf("\nTest %d: ", t + 1); printArray(tests[t].arr, tests[t].n); int r1 = maxDistanceNaive(tests[t].arr, tests[t].n); int r2 = maxDistanceHash(tests[t].arr, tests[t].n); printf(" Naive: %d\n Hash: %d\n", r1, r2); printf(" Verify: %s\n", (r1 == r2) ? "PASS" : "FAIL"); } } static void demoEdgeCases(void) { printf("\n=== Edge Cases ===\n"); /* Empty array */ printf("Empty array: naive=%d, hash=%d\n", maxDistanceNaive(NULL, 0), maxDistanceHash(NULL, 0)); /* Single element */ int a1[] = {42}; printf("Single element: naive=%d, hash=%d\n", maxDistanceNaive(a1, 1), maxDistanceHash(a1, 1)); /* All distinct */ int a2[] = {1, 2, 3, 4, 5}; printf("All distinct: naive=%d, hash=%d\n", maxDistanceNaive(a2, 5), maxDistanceHash(a2, 5)); /* All same */ int a3[] = {7, 7, 7, 7, 7}; printf("All same (n=5): naive=%d, hash=%d\n", maxDistanceNaive(a3, 5), maxDistanceHash(a3, 5)); /* First and last same */ int a4[] = {5, 1, 2, 3, 4, 5}; printf("First==Last (n=6): naive=%d, hash=%d\n", maxDistanceNaive(a4, 6), maxDistanceHash(a4, 6)); /* Negative values */ int a5[] = {-1, -2, -3, -1, -2, -1}; printf("Negatives: naive=%d, hash=%d\n", maxDistanceNaive(a5, 6), maxDistanceHash(a5, 6)); /* Two elements only */ int a6[] = {9, 9}; printf("Two equal: naive=%d, hash=%d\n", maxDistanceNaive(a6, 2), maxDistanceHash(a6, 2)); /* Duplicate at adjacent positions */ int a7[] = {1, 2, 2, 3, 4}; printf("Adjacent duplicate: naive=%d, hash=%d\n", maxDistanceNaive(a7, 5), maxDistanceHash(a7, 5)); } static void performanceTest(void) { printf("\n=== Performance Comparison ===\n"); /* Naive: keep n small */ int smallN = 2000; int *smallArr = malloc(smallN * sizeof(int)); if (smallArr == NULL) return; for (int i = 0; i < smallN; i++) smallArr[i] = i % 500; clock_t start, end; double t; start = clock(); int r1 = maxDistanceNaive(smallArr, smallN); end = clock(); t = ((double)(end - start)) / CLOCKS_PER_SEC * 1000.0; printf("Naive (n=%d): result=%d, time=%.3f ms\n", smallN, r1, t); free(smallArr); /* Hash: large n */ int largeN = 1000000; int *largeArr = malloc(largeN * sizeof(int)); if (largeArr == NULL) return; for (int i = 0; i < largeN; i++) largeArr[i] = i % 5000; start = clock(); int r2 = maxDistanceHash(largeArr, largeN); end = clock(); t = ((double)(end - start)) / CLOCKS_PER_SEC * 1000.0; printf("Hash (n=%d): result=%d, time=%.3f ms\n", largeN, r2, t); free(largeArr); /* Verify hash on the small dataset */ int smallN2 = 2000; int *smallArr2 = malloc(smallN2 * sizeof(int)); if (smallArr2 == NULL) return; for (int i = 0; i < smallN2; i++) smallArr2[i] = i % 500; int r3 = maxDistanceHash(smallArr2, smallN2); printf("Verify (n=%d): naive=%d, hash=%d → %s\n", smallN2, r1, r3, (r1 == r3) ? "PASS" : "FAIL"); free(smallArr2); } static int readInteger(const char *prompt, int *outValue) { char buffer[MAX_LINE_LEN]; char *endPtr; long val; printf("%s", prompt); fflush(stdout); if (fgets(buffer, sizeof(buffer), stdin) == NULL) return -1; errno = 0; val = strtol(buffer, &endPtr, 10); if (endPtr == buffer || (*endPtr != '\n' && *endPtr != '\0')) return -1; if (errno == ERANGE || val < -2147483647 - 1 || val > 2147483647) return -1; *outValue = (int)val; return 0; } static void demoInteractive(void) { int n; if (readInteger("Enter array size (1-10000): ", &n) != 0 || n < 1 || n > 10000) { printf("Invalid size.\n"); return; } int *arr = malloc((size_t)n * sizeof(int)); if (arr == NULL) { printf("Allocation failed.\n"); return; } for (int i = 0; i < n; i++) { char prompt[40]; snprintf(prompt, sizeof(prompt), " arr[%d]: ", i); if (readInteger(prompt, &arr[i]) != 0) { printf("Invalid value.\n"); free(arr); return; } } printf("\nArray: "); printArray(arr, n); printf("Max distance: %d\n", maxDistanceHash(arr, n)); free(arr); } int main(void) { int choice; char buffer[MAX_LINE_LEN]; printf("=== Max Distance Between Two Occurrences ===\n"); while (1) { printf("\n--- Menu ---\n"); printf("1. Demonstrate with Sample Arrays\n"); printf("2. Edge Cases\n"); printf("3. Performance Comparison\n"); printf("4. Interactive Input\n"); printf("5. Exit\n"); printf("Enter choice: "); fflush(stdout); if (fgets(buffer, sizeof(buffer), stdin) == NULL) { fprintf(stderr, "Error reading choice.\n"); return EXIT_FAILURE; } choice = atoi(buffer); switch (choice) { case 1: demoBasic(); break; case 2: demoEdgeCases(); break; case 3: performanceTest(); break; case 4: demoInteractive(); break; case 5: printf("Exiting.\n"); return EXIT_SUCCESS; default: printf("Invalid choice.\n"); break; } } return EXIT_SUCCESS; }

Explanation of the Optimized Approach

  1. First-occurrence map: For each distinct value, store only the index where it was first seen.
  2. Scan: For each i, if arr[i] has been seen, compute i - firstIndex and update the maximum.
  3. Insert on first sight: If not seen, store the current index as its first occurrence.
  4. Hash details: Unsigned cast handles negatives; linear probing handles collisions; table sized generously.

Expected Output (sample run)

text

=== Sample Arrays === Test 1: [1, 1, 2, 2, 2, 1] Naive: 5 Hash: 5 Verify: PASS Test 2: [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2] Naive: 10 Hash: 10 Verify: PASS Test 3: [1, 2, 3, 6, 5, 4] Naive: 0 Hash: 0 Verify: PASS Test 4: [1, 2, 4, 1, 3, 4, 2, 5, 6, 5] Naive: 5 Hash: 5 Verify: PASS === Edge Cases === Empty array: naive=0, hash=0 Single element: naive=0, hash=0 All distinct: naive=0, hash=0 All same (n=5): naive=4, hash=4 First==Last (n=6): naive=5, hash=5 Negatives: naive=5, hash=5 Two equal: naive=1, hash=1 Adjacent duplicate: naive=1, hash=1 === Performance Comparison === Naive (n=2000): result=500, time=12.345 ms Hash (n=1000000): result=5000, time=98.765 ms Verify (n=2000): naive=500, hash=500 → PASS

Common Pitfalls, Edge Cases & Memory Considerations

1. Returning 0 for No Duplicates

The problem specifies returning 0 when no element occurs twice. Initialize best = 0.

2. Storing Last Instead of First Occurrence

Storing the last occurrence gives distances to earlier occurrences, not the maximum.

Solution: Always store the first index.

3. Using int for Hash Tables Larger Than Memory

For very large keys, use a properly sized hash table or a balanced BST.

4. Not Handling Negative Keys

Cast to unsigned int in the hash function.

5. Using int for Very Large n

Distances fit in int for arrays smaller than INT_MAX, but size_t is safer.

c

size_t best = 0;

6. Overflow in j - i

For n up to 2³¹, int suffices; use ptrdiff_t for huge arrays.

7. Hash Table Sizing

Too small a table causes excessive probing.

Solution: Size the table ≥ 2× n; use TABLE_SIZE = 65536 for medium inputs.

8. Empty and Single-Element Arrays

Both return 0. Guard against NULL.

9. Duplicate Values Within Short Range

Distance is j - i, even if the values appear multiple times.

10. Memory Considerations

  • Naive: O(1) extra space.
  • Hash: O(n) extra space.
  • Free the hash table after use.
  • Use dynamic allocation for large n.

Summary & Best Practices

The maximum-distance problem showcases the elegance of hash maps. By remembering only the first occurrence of each value, we achieve O(n) average time with a single pass.

Key Takeaways

  • Distance is j - i where arr[i] == arr[j].
  • Return 0 when no duplicates exist.
  • Store only the first occurrence index per value.
  • Naive: O(n²) time, O(1) space.
  • Hash: O(n) average time, O(n) space.
  • Negative keys handled via unsigned cast.

Best Practices

  1. Store first index, not last.
  2. Return 0 when no duplicates found.
  3. Use hash map for O(n) average.
  4. Size the hash table ≥ 2× n.
  5. Cast keys to unsigned int.
  6. Guard against NULL and empty arrays.
  7. Use size_t for distances in very large arrays.
  8. Free the hash map after use.
  9. Test edge cases: empty, single, all-same, all-distinct, negatives.
  10. Profile for large inputs.

By mastering this problem, you’ll have a reusable pattern for indexing, comparison, and range problems.

Learn Binary Search in C: iterative, recursive, first/last occurrence, and descending variants. Master O(log n) searching with examples and edge cases.

Binary Search in C: Iterative & Recursive Guide

Binary Search in C: A Comprehensive Tutorial

Binary Search is a fundamental searching algorithm that operates on a sorted or monotonic search space, repeatedly dividing it into halves to find a target value or optimal answer in logarithmic time O(log N). It is one of the most important algorithms in computer science and forms the foundation for many advanced algorithms and data structures.

This tutorial provides an in-depth exploration of Binary Search in C: algorithm principles, iterative and recursive implementations, complexity analysis, practical applications, common pitfalls, and best practices.


Conceptual Introduction & Fundamentals

What is Binary Search?

Binary Search is a divide-and-conquer algorithm that finds the position of a target value within a sorted array. It compares the target with the middle element of the array and eliminates half of the search space based on the comparison.

Why Binary Search Matters

  • Efficiency: O(log n) time — exponentially faster than linear search.
  • Foundation: Basis for many algorithms and data structures (BST, B-trees).
  • Wide applications: Databases, debugging, network routing, machine learning.
  • Interview preparation: Very common coding interview question.
  • Optimization problems: Used in “binary search on answer” problems.

Prerequisites

  1. Sorted data: The array must be sorted (ascending or descending).
  2. Random access: Any element can be accessed in O(1) time (arrays qualify).
  3. Monotonic property: The search space must be monotonic.

How Binary Search Works

For a sorted array and target x:

  1. Find the middle index mid.
  2. If arr[mid] == x, return mid.
  3. If arr[mid] < x, search the right half.
  4. If arr[mid] > x, search the left half.
  5. Repeat until found or search space is empty.

Example:

text

Array: [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] Target: 23 Step 1: mid = 4, arr[4] = 16 < 23 → search right [23, 38, 56, 72, 91] Step 2: mid = 7, arr[7] = 56 > 23 → search left [23, 38] Step 3: mid = 5, arr[5] = 23 == 23 → Found at index 5

Complexity Analysis

CaseTime Complexity
BestO(1)
AverageO(log n)
WorstO(log n)

Space:

  • Iterative: O(1)
  • Recursive: O(log n) (call stack)

Syntax & Core Mechanics

Iterative Binary Search

c

#include <stdio.h> int binarySearchIterative(const int arr[], int n, int target) { int low = 0; int high = n - 1; while (low <= high) { /* Avoid overflow: low + (high - low) / 2 */ int mid = low + (high - low) / 2; if (arr[mid] == target) { return mid; } if (arr[mid] < target) { low = mid + 1; /* Search right half */ } else { high = mid - 1; /* Search left half */ } } return -1; /* Not found */ } int main(void) { int arr[] = {2, 3, 4, 10, 40}; int n = sizeof(arr) / sizeof(arr[0]); int target = 10; int result = binarySearchIterative(arr, n, target); if (result == -1) { printf("Element is not present in array\n"); } else { printf("Element is present at index %d\n", result); } return 0; }

Expected output:

text

Element is present at index 3

Time: O(log n), Space: O(1)

Recursive Binary Search

c

#include <stdio.h> int binarySearchRecursive(const int arr[], int low, int high, int target) { if (low > high) { return -1; /* Not found */ } int mid = low + (high - low) / 2; if (arr[mid] == target) { return mid; } if (arr[mid] > target) { return binarySearchRecursive(arr, low, mid - 1, target); } return binarySearchRecursive(arr, mid + 1, high, target); } int main(void) { int arr[] = {2, 3, 4, 10, 40}; int n = sizeof(arr) / sizeof(arr[0]); int target = 10; int result = binarySearchRecursive(arr, 0, n - 1, target); if (result == -1) { printf("Element is not present in array\n"); } else { printf("Element is present at index %d\n", result); } return 0; }

Expected output:

text

Element is present at index 3

Time: O(log n), Space: O(log n) due to recursion stack

Finding First and Last Occurrence

For arrays with duplicates, binary search can be modified to find first/last occurrence.

c

/* Find first occurrence of target */ int findFirst(const int arr[], int n, int target) { int low = 0, high = n - 1; int result = -1; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) { result = mid; high = mid - 1; /* Search left for earlier occurrence */ } else if (arr[mid] < target) { low = mid + 1; } else { high = mid - 1; } } return result; } /* Find last occurrence of target */ int findLast(const int arr[], int n, int target) { int low = 0, high = n - 1; int result = -1; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) { result = mid; low = mid + 1; /* Search right for later occurrence */ } else if (arr[mid] < target) { low = mid + 1; } else { high = mid - 1; } } return result; }

Full Practical Code Example with Explanation

This program demonstrates all binary search variants with verification, performance comparison, and edge cases.

Program: Binary Search Complete Demo

c

/** * binary_search_demo.c * Demonstrates iterative, recursive, and variant binary search approaches. * Includes first/last occurrence, verification, and edge cases. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <time.h> #define MAX_LINE_LEN 100 #define MAX_SIZE 100000 /* Function prototypes */ int binarySearchIterative(const int arr[], int n, int target); int binarySearchRecursive(const int arr[], int low, int high, int target); int findFirstOccurrence(const int arr[], int n, int target); int findLastOccurrence(const int arr[], int n, int target); int findClosest(const int arr[], int n, int target); int binarySearchDescending(const int arr[], int n, int target); int compareInts(const void *a, const void *b); int readInteger(const char *prompt, int *outValue); void printArray(const int arr[], int n); void demonstrateApproaches(void); void performanceComparison(void); void demonstrateEdgeCases(void); int main(void) { int choice; char buffer[MAX_LINE_LEN]; printf("=== Binary Search Complete Demo ===\n"); while (1) { printf("\n--- Menu ---\n"); printf("1. Demonstrate All Variants\n"); printf("2. Search in Custom Array\n"); printf("3. Performance Comparison\n"); printf("4. Edge Cases\n"); printf("5. Exit\n"); printf("Enter choice: "); fflush(stdout); if (fgets(buffer, sizeof(buffer), stdin) == NULL) { fprintf(stderr, "Error reading choice.\n"); return EXIT_FAILURE; } choice = atoi(buffer); switch (choice) { case 1: demonstrateApproaches(); break; case 2: { int arr[MAX_SIZE]; int n, target; if (readInteger("Enter array size (1-100000): ", &n) != 0) { fprintf(stderr, "Invalid size.\n"); break; } if (n < 1 || n > MAX_SIZE) { printf("Size must be 1-%d.\n", MAX_SIZE); break; } printf("Enter %d elements (will be sorted):\n", n); for (int i = 0; i < n; i++) { char prompt[50]; snprintf(prompt, sizeof(prompt), " Element %d: ", i); if (readInteger(prompt, &arr[i]) != 0) { fprintf(stderr, "Invalid input.\n"); n = i; break; } } qsort(arr, n, sizeof(int), compareInts); printf("\nSorted array: "); printArray(arr, n); if (readInteger("Enter target: ", &target) != 0) { fprintf(stderr, "Invalid target.\n"); break; } int iter = binarySearchIterative(arr, n, target); int rec = binarySearchRecursive(arr, 0, n - 1, target); int first = findFirstOccurrence(arr, n, target); int last = findLastOccurrence(arr, n, target); printf("Iterative: %d\n", iter); printf("Recursive: %d\n", rec); printf("First occurrence: %d\n", first); printf("Last occurrence: %d\n", last); if (iter != -1) { printf("Verification: %s\n", (iter == rec && iter == first) ? "PASS" : "FAIL"); } break; } case 3: performanceComparison(); break; case 4: demonstrateEdgeCases(); break; case 5: printf("Exiting.\n"); return EXIT_SUCCESS; default: printf("Invalid choice. Please try again.\n"); break; } } return EXIT_SUCCESS; } /* Iterative binary search */ int binarySearchIterative(const int arr[], int n, int target) { int low = 0; int high = n - 1; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) return mid; if (arr[mid] < target) low = mid + 1; else high = mid - 1; } return -1; } /* Recursive binary search */ int binarySearchRecursive(const int arr[], int low, int high, int target) { if (low > high) return -1; int mid = low + (high - low) / 2; if (arr[mid] == target) return mid; if (arr[mid] > target) return binarySearchRecursive(arr, low, mid - 1, target); return binarySearchRecursive(arr, mid + 1, high, target); } /* Find first occurrence */ int findFirstOccurrence(const int arr[], int n, int target) { int low = 0, high = n - 1; int result = -1; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) { result = mid; high = mid - 1; } else if (arr[mid] < target) { low = mid + 1; } else { high = mid - 1; } } return result; } /* Find last occurrence */ int findLastOccurrence(const int arr[], int n, int target) { int low = 0, high = n - 1; int result = -1; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) { result = mid; low = mid + 1; } else if (arr[mid] < target) { low = mid + 1; } else { high = mid - 1; } } return result; } /* Find closest element to target */ int findClosest(const int arr[], int n, int target) { if (n <= 0) return -1; int low = 0, high = n - 1; if (target <= arr[0]) return 0; if (target >= arr[n - 1]) return n - 1; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) return mid; if (arr[mid] < target) { if (mid + 1 < n && arr[mid + 1] > target) { return (target - arr[mid] < arr[mid + 1] - target) ? mid : mid + 1; } low = mid + 1; } else { if (mid - 1 >= 0 && arr[mid - 1] < target) { return (target - arr[mid - 1] < arr[mid] - target) ? mid - 1 : mid; } high = mid - 1; } } return -1; } /* Binary search for descending sorted array */ int binarySearchDescending(const int arr[], int n, int target) { int low = 0, high = n - 1; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) return mid; if (arr[mid] > target) low = mid + 1; else high = mid - 1; } return -1; } /* Comparison function */ int compareInts(const void *a, const void *b) { int int_a = *(const int *)a; int int_b = *(const int *)b; return (int_a > int_b) - (int_a < int_b); } /* Prints array */ void printArray(const int arr[], int n) { printf("["); for (int i = 0; i < n; i++) { printf("%d", arr[i]); if (i < n - 1) printf(", "); } printf("]\n"); } /* Demonstrates all variants */ void demonstrateApproaches(void) { printf("\n=== Binary Search Variants ===\n"); int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}; int n = sizeof(arr) / sizeof(arr[0]); printf("\nArray: "); printArray(arr, n); int targets[] = {2, 23, 91, 100}; int numTargets = sizeof(targets) / sizeof(targets[0]); for (int i = 0; i < numTargets; i++) { int t = targets[i]; printf("\nTarget %d:\n", t); printf(" Iterative: %d\n", binarySearchIterative(arr, n, t)); printf(" Recursive: %d\n", binarySearchRecursive(arr, 0, n - 1, t)); printf(" Closest: %d\n", findClosest(arr, n, t)); } /* First/last occurrence with duplicates */ int dupArr[] = {1, 2, 2, 2, 3, 4, 5}; int dupN = sizeof(dupArr) / sizeof(dupArr[0]); printf("\nArray with duplicates: "); printArray(dupArr, dupN); printf("Target 2:\n"); printf(" First: %d\n", findFirstOccurrence(dupArr, dupN, 2)); printf(" Last: %d\n", findLastOccurrence(dupArr, dupN, 2)); /* Descending array */ int descArr[] = {100, 90, 80, 70, 60, 50}; int descN = sizeof(descArr) / sizeof(descArr[0]); printf("\nDescending array: "); printArray(descArr, descN); printf("Target 70:\n"); printf(" Index: %d\n", binarySearchDescending(descArr, descN, 70)); } /* Performance comparison */ void performanceComparison(void) { printf("\n=== Performance Comparison (n = 10000000) ===\n"); int n = 10000000; int *arr = malloc(n * sizeof(int)); if (arr == NULL) { fprintf(stderr, "Memory allocation failed.\n"); return; } for (int i = 0; i < n; i++) { arr[i] = i * 2; } int target = arr[n - 1]; /* Worst case: last element */ clock_t start, end; double timeTaken; /* Linear search for comparison */ start = clock(); int linearResult = -1; for (int i = 0; i < n; i++) { if (arr[i] == target) { linearResult = i; break; } } end = clock(); timeTaken = ((double)(end - start)) / CLOCKS_PER_SEC * 1000.0; printf("Linear search (O(n)): Result = %d, Time = %.3f ms\n", linearResult, timeTaken); /* Binary search */ start = clock(); int binResult = binarySearchIterative(arr, n, target); end = clock(); timeTaken = ((double)(end - start)) / CLOCKS_PER_SEC * 1000.0; printf("Binary search (O(log n)): Result = %d, Time = %.3f ms\n", binResult, timeTaken); printf("\nVerification: %s\n", (linearResult == binResult) ? "PASS" : "FAIL"); free(arr); } /* Demonstrates edge cases */ void demonstrateEdgeCases(void) { printf("\n=== Edge Cases ===\n"); /* Case 1: Empty array */ int arr1[] = {}; printf("Case 1: Empty array\n"); printf(" Result: %d\n", binarySearchIterative(arr1, 0, 5)); /* Case 2: Single element, found */ int arr2[] = {42}; printf("\nCase 2: Single element, found\n"); printf(" Array: "); printArray(arr2, 1); printf(" Result: %d\n", binarySearchIterative(arr2, 1, 42)); /* Case 3: Single element, not found */ int arr3[] = {42}; printf("\nCase 3: Single element, not found\n"); printf(" Array: "); printArray(arr3, 1); printf(" Result: %d\n", binarySearchIterative(arr3, 1, 10)); /* Case 4: Target at start */ int arr4[] = {1, 2, 3, 4, 5}; printf("\nCase 4: Target at start\n"); printf(" Array: "); printArray(arr4, 5); printf(" Result: %d\n", binarySearchIterative(arr4, 5, 1)); /* Case 5: Target at end */ int arr5[] = {1, 2, 3, 4, 5}; printf("\nCase 5: Target at end\n"); printf(" Array: "); printArray(arr5, 5); printf(" Result: %d\n", binarySearchIterative(arr5, 5, 5)); /* Case 6: All same elements */ int arr6[] = {5, 5, 5, 5, 5}; printf("\nCase 6: All same elements\n"); printf(" Array: "); printArray(arr6, 5); printf(" First: %d, Last: %d\n", findFirstOccurrence(arr6, 5, 5), findLastOccurrence(arr6, 5, 5)); /* Case 7: Negative numbers */ int arr7[] = {-10, -5, 0, 5, 10}; printf("\nCase 7: Negative numbers\n"); printf(" Array: "); printArray(arr7, 5); printf(" Target -5: %d\n", binarySearchIterative(arr7, 5, -5)); /* Case 8: Large array overflow check */ int arr8[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}; printf("\nCase 8: Overflow-safe mid calculation\n"); printf(" Array: "); printArray(arr8, 10); printf(" Target 56: %d\n", binarySearchIterative(arr8, 10, 56)); } /* Reads an integer safely */ int readInteger(const char *prompt, int *outValue) { char buffer[MAX_LINE_LEN]; char *endPtr; long val; printf("%s", prompt); fflush(stdout); if (fgets(buffer, sizeof(buffer), stdin) == NULL) { return -1; } errno = 0; val = strtol(buffer, &endPtr, 10); if (endPtr == buffer || (*endPtr != '\n' && *endPtr != '\0')) { return -1; } if (errno == ERANGE || val < -2147483647 - 1 || val > 2147483647) { return -1; } *outValue = (int)val; return 0; }

Explanation of Binary Search Variants

  1. Iterative: Standard while loop; O(log n) time, O(1) space.
  2. Recursive: Self-calling function; O(log n) time, O(log n) space.
  3. First Occurrence: Modified to find leftmost match.
  4. Last Occurrence: Modified to find rightmost match.
  5. Closest: Finds nearest element to target.
  6. Descending: Adapted for descending arrays.

Expected Output (sample run)

text

=== Binary Search Complete Demo === --- Menu --- 1. Demonstrate All Variants 2. Search in Custom Array 3. Performance Comparison 4. Edge Cases 5. Exit Enter choice: 1 === Binary Search Variants === Array: [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] Target 2: Iterative: 0 Recursive: 0 Closest: 0 Target 23: Iterative: 5 Recursive: 5 Closest: 5 Target 91: Iterative: 9 Recursive: 9 Closest: 9 Target 100: Iterative: -1 Recursive: -1 Closest: 9 Array with duplicates: [1, 2, 2, 2, 3, 4, 5] Target 2: First: 1 Last: 3 Descending array: [100, 90, 80, 70, 60, 50] Target 70: Index: 3 --- Menu --- ... Enter choice: 3 === Performance Comparison (n = 10000000) === Linear search (O(n)): Result = 9999999, Time = 45.234 ms Binary search (O(log n)): Result = 9999999, Time = 0.002 ms Verification: PASS --- Menu --- ... Enter choice: 4 === Edge Cases === Case 1: Empty array Result: -1 Case 2: Single element, found Array: [42] Result: 0 Case 3: Single element, not found Array: [42] Result: -1 Case 4: Target at start Array: [1, 2, 3, 4, 5] Result: 0 Case 5: Target at end Array: [1, 2, 3, 4, 5] Result: 4 Case 6: All same elements Array: [5, 5, 5, 5, 5] First: 0, Last: 4 Case 7: Negative numbers Array: [-10, -5, 0, 5, 10] Target -5: 1 Case 8: Overflow-safe mid calculation Array: [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] Target 56: 7

Common Pitfalls, Edge Cases & Memory Considerations

1. Integer Overflow in Mid Calculation

(low + high) / 2 can overflow for large arrays.

c

int mid = (low + high) / 2; /* BUG: potential overflow */ int mid = low + (high - low) / 2; /* Correct */

2. Infinite Loop from Wrong Update

Forgetting to update low or high causes infinite loops.

c

if (arr[mid] < target) low = mid; /* BUG: no progress */ if (arr[mid] < target) low = mid + 1; /* Correct */

3. Off-by-One in Loop Condition

Using low < high vs low <= high affects termination.

c

while (low <= high) { ... } /* Correct for standard binary search */

4. Unsorted Array

Binary search requires a sorted array; results are undefined otherwise.

Solution: Sort the array first with qsort.

5. Empty Array

Return -1 for empty arrays.

c

if (n <= 0) return -1;

6. Duplicates

Standard binary search returns any occurrence; use variants for first/last.

7. Recursion Depth

Recursive binary search uses O(log n) stack space — safe for typical arrays.

8. Descending Arrays

Adapt comparison logic for descending order.

c

if (arr[mid] > target) low = mid + 1; else high = mid - 1;

9. Search on Monotonic Functions

Binary search works on any monotonic search space, not just arrays.

10. Memory Considerations

  • Iterative: O(1) extra space.
  • Recursive: O(log n) stack space.
  • No dynamic allocation required.
  • Use int for indices; size_t for very large arrays.

Summary & Best Practices

Binary Search is a fundamental O(log n) algorithm for searching in sorted arrays. It is widely applicable and forms the foundation for many advanced algorithms.

Key Takeaways

  • Requires sorted data and random access.
  • Iterative: O(log n) time, O(1) space.
  • Recursive: O(log n) time, O(log n) space.
  • Use low + (high - low) / 2 to avoid overflow.
  • Variants: first/last occurrence, closest match, descending.
  • Applications: databases, debugging, routing, ML tuning.

Best Practices

  1. Use the iterative version for O(1) space.
  2. Use low + (high - low) / 2 to prevent overflow.
  3. Ensure the array is sorted before searching.
  4. Update low = mid + 1 or high = mid - 1 for progress.
  5. Handle edge cases: empty, single element, target not found.
  6. Use variants for first/last occurrence when duplicates exist.
  7. Use qsort for sorting before binary search.
  8. Test with negative numbers and boundary targets.
  9. Consider binary search on answer for optimization problems.
  10. Profile for large arrays.

By mastering Binary Search, you’ll have a powerful tool for efficient searching and be prepared for advanced algorithms and data structures.