# LeetCode 34. Find First and Last Position of Element in Sorted Array

## Description

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

Your algorithm’s runtime complexity must be in the order of O(log n).

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

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]```

## Explanation

Use binary search twice to solve the problem. The first binary search to find the first occurrence of the target. The second binary search to find the second occurrence of the target.

## Java Solution

``````class Solution {
public int[] searchRange(int[] nums, int target) {
int[] result = new int;
result = -1;
result = -1;

if (nums == null || nums.length == 0) {
return result;
}

// first binary search to find the first occurence of the target
int start = 0;
int end = nums.length - 1;

while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
end = mid;
} else if (nums[mid] > target) {
end = mid;
} else {
start = mid;
}
}

if (nums[end] == target) {
result = end;
}
if (nums[start] == target) {
result = start;
}

// second binary search to find the last occurence of the target
start = 0;
end = nums.length - 1;

while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
start = mid;
} else if (nums[mid] < target) {
start = mid;
} else {
end = mid;
}
}

if (nums[start] == target) {
result = start;
}
if (nums[end] == target) {
result = end;
}

return result;
}
}``````

## Python Solution

``````class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
range_start = -1
range_end = -1

if (nums == None or len(nums) == 0):
return [range_start, range_end]

start = 0
end = len(nums) - 1

while start + 1 < end:
mid = start + (end - start) // 2
if nums[mid] < target:
start = mid
elif nums[mid] > target:
end = mid
else:
start = mid

if nums[end] == target:
range_end = end
elif nums[start] == target:
range_end = start

start = 0
end = len(nums) - 1

while start + 1 < end:
mid = start + (end - start) // 2
if nums[mid] < target:
start = mid
elif nums[mid] > target:
end = mid
else:
end = mid

if nums[start] == target:
range_start = start
elif nums[end] == target:
range_start = end

return [range_start, range_end]``````
• Time complexity: O(log(N)).
• Space complexity: O(1).

## 4 Thoughts to “LeetCode 34. Find First and Last Position of Element in Sorted Array”

1. Deepa says:

Hi GoodTecher,
I really like your leetcode video tutorials..hope you continue making more tutorials. 🙂

1. GoodTecher says:

Thank you, Deepa. I have been getting busy recently. Will do after that 🙂