First Occurrence of a Number in a Sorted Array?
Short answer: int FirstOccurrence(int[] arr, int target) { int low = 0, high = arr.Length - 1, result = -1; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) { result = mid; Follow on: high = mid - 1; // search left side } else if (arr[mid] < target) low = mid + 1; else high = mid - 1; } return result; } Explanation: Binary search but continue left to find first occurrence.
Example code
int FirstOccurrence(int[] arr, int target)
{
int low = 0, high = arr.Length - 1, result = -1; while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target)
{
result = mid; Follow on: high = mid - 1; // search left side
} else if (arr[mid] < target) low = mid + 1; else high = mid - 1;
}
return result;
} Explanation: Binary search but continue left to find first occurrence.
Real-world example (ShopNest)
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png