Tutorialspoint
Problem
Solution
Submissions

First and Last Position of Element

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript program to find the first and last position of a target element in a sorted array. Given a sorted array of integers and a target value, return the starting and ending position of the target element. 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:
    • The sorted array is [5, 7, 7, 8, 8, 10].
    • Target element 8 appears at indices 3 and 4.
    • First occurrence of 8 is at index 3, last occurrence of 8 is at index 4.
    • Return [3, 4] as the result.
Example 2
  • Input: nums = [5, 7, 7, 8, 8, 10], target = 6
  • Output: [-1, -1]
  • Explanation:
    • The sorted array is [5, 7, 7, 8, 8, 10].
    • Target element 6 is searched in the array.
    • 6 is not present in the array.
    • Since target is not found, return [-1, -1].
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)
ArraysAlgorithmsIBMSnowflake
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 achieve O(log n) time complexity
  • Perform two separate binary searches: one for first position, one for last position
  • For finding first position, when target is found, continue searching in left half
  • For finding last position, when target is found, continue searching in right half
  • Handle edge cases where target is not present in the array
  • Return [-1, -1] if target is not found

Steps to solve by this approach:

 Step 1: Create a main function that calls two separate binary search functions
 Step 2: Implement findFirst function using binary search to locate first occurrence
 Step 3: In findFirst, when target is found, store index and search left half for earlier occurrence
 Step 4: Implement findLast function using binary search to locate last occurrence
 Step 5: In findLast, when target is found, store index and search right half for later occurrence
 Step 6: Return [-1, -1] if target is not found in either search
 Step 7: Combine results from both searches to get the range

Submitted Code :