Search for a range (find start and end indices of target in sorted array)?
Short answer: 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;…
Explain a bit more
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.
Example code
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.
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