Find First And Last Position of Element in Sorted Array

My Linh Tran
2 min readFeb 4, 2021

This is the first post on my series of Leetcode solutions. I would try to explain my solution as clearly as possible. Some of my solutions might not be as optimized as others. Thus, constructive criticism would be highly appreciated.

Photo by Benjamin Suter on Unsplash

Description

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

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

Some Thoughts

  • The array is already sorted in ascending order. This means that we only need to iterate through the array once.
  • Initiate the result array with values as [-1, -1] to take advantage of some edge cases.
  • We first go through the array, once we found the element that has the same value as the target, update result[0,1] = [i, i] with i as the index of the found element.
  • Continue to loop through the array. If the next element does not have the same value as the target, we can stop now and return the result; else, update result[1] = i.
  • In case the final element of the array has the same value as the target, we stop and return the result array.

Proposed Solution

I normally use Java for most of my solutions. On Leetcode, you can also do it using another language that you are most comfortable with. It’s also a good practice to try to solve the same problem while learning a new programming language.

Happy coding!

--

--