Mid Coding

Search for a range (find start and end indices of target in sorted array)?

public int[] SearchRange(int[] nums, int target) {

int left = FindBoundary(nums, target, true);

int right = FindBoundary(nums, target, false);

return new int[] { left, right };

private int FindBoundary(int[] nums, int target, bool findFirst) {

Follow on:

int left = 0, right = nums.Length - 1;

int boundary = -1;

while (left <= right) {

int mid = left + (right - left) / 2;

if (nums[mid] == target) {

boundary = mid;

if (findFirst)

right = mid - 1;

else

left = mid + 1;

else if (nums[mid] < target) left = mid + 1;

else right = mid - 1;

return boundary;

Explanation:

Binary search twice — once to find first occurrence and once for last occurrence.

More from C# Programming Tutorial

All questions for this course