Tutorialspoint
Problem
Solution
Submissions

Search for a Range

Certification: Intermediate Level Accuracy: 0% Submissions: 8 Points: 10

Write a C program to find the first and last position of a given target value in a sorted array. If the target is not found in the array, return [-1, -1]. The algorithm must run in O(log n) time complexity.

Example 1
  • Input: nums = [5, 7, 7, 8, 8, 10], target = 8
  • Output: [3, 4]
  • Explanation:
    • Step 1: The target value 8 appears at indices 3 and 4.
    • Step 2: First occurrence is at index 3.
    • Step 3: Last occurrence is at index 4.
    • Step 4: Therefore, return [3, 4].
Example 2
  • Input: nums = [5, 7, 7, 8, 8, 10], target = 6
  • Output: [-1, -1]
  • Explanation:
    • Step 1: The target value 6 is not present in the array.
    • Step 2: Since target is not found, return [-1, -1].
    • Step 3: This indicates that the target has no first or last position.
Constraints
  • 0 ≤ nums.length ≤ 10^5
  • -10^9 ≤ nums[i] ≤ 10^9
  • nums is a non-decreasing array
  • -10^9 ≤ target ≤ 10^9
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
ArraysAlgorithmsDeloitteAdobe
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use binary search to find the first occurrence of the target.
  • Use binary search to find the last occurrence of the target.
  • Modify the standard binary search to find leftmost position.
  • Modify the standard binary search to find rightmost position.
  • Return [-1, -1] if target is not found in either search.

Steps to solve by this approach:

 Step 1: Create a helper function to find the first occurrence using modified binary search.
 Step 2: In the first search, when target is found, continue searching left to find the leftmost occurrence.
 Step 3: Create another helper function to find the last occurrence using modified binary search.
 Step 4: In the second search, when target is found, continue searching right to find the rightmost occurrence.
 Step 5: Handle edge cases where the array is empty or target is not found.
 Step 6: Return the results in an array format [first_position, last_position].
 Step 7: Use proper memory allocation for the result array.

Submitted Code :