### Find First and Last Position of Element in Sorted Array Solution - The Coding Shala

Home >> Interview Prep >> Find first and the last position of an element in a sorted array

In this post, we will learn how to Find the First and Last Position of Element in Sorted Array and will implement its solution in Java.

## Find First And Last Position of Element in Sorted Array Problem

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

If the target is not found in the array, return [-1, -1]

You must write an algorithm with O(log n) runtime complexity.

**Example 1:**

Input: nums = [5,7,7,8,8,10], target = 8

Output: [3,4]

**Example 2:**

Input: nums = [5,7,7,8,8,10], target = 6

Output: [-1,-1]

**Example 3:**

Input: nums = [], target = 0

Output: [-1,-1]

## Find First and Last Position of Element in Sorted Array Java Solution

#### Approach 1

Using Binary Search.

Time complexity: O(log n)

**Java Program: **

class Solution { public int[] searchRange(int[] nums, int target) { int[] result = new int[2]; result[0] = findFirst(nums, target); result[1] = findLast(nums, target); return result; } int findFirst(int[] nums, int target) { int index = -1; int start = 0; int end = nums.length - 1; while (start <= end) { int mid = start + (end - start) / 2; if (nums[mid] >= target) end = mid - 1; else start = mid + 1; if (nums[mid] == target) index = mid; } return index; } int findLast(int[] nums, int target) { int index = -1; int start = 0; int end = nums.length - 1; while (start <= end) { int mid = start + (end - start) / 2; if (nums[mid] <= target) start = mid + 1; else end = mid - 1; if (nums[mid] == target) index = mid; } return index; } }

**Other Posts You May Like**- 3Sum Problem
- Two Sum Problem
- Minimum Size Subarray Sum
- Repeat and Missing Number Array
- Max Sum Contiguous Subarray

## Comments

## Post a Comment