DEV Community

Cover image for Devmates.co [Array Search]
Alex Wawl ๐Ÿผ
Alex Wawl ๐Ÿผ

Posted on

Devmates.co [Array Search]

Hello๐Ÿ‘‹,
*My name is Alex and I'm maker of Devmates.co.
๐Ÿ˜Š

We are resolving daily coding problems which asked by top tech companies together. We share our solutions, give some help if anyone stuck, support each other and just hangout together in the internet. ๐Ÿปโ˜•๏ธ๐Ÿ’ฌ

I get this problem from our members or just searching them in the internet(leetcode forums, Glassdoor, teamblind, etc.). Sometimes this problem can be very easy, sometimes too ๐Ÿ‘ทโ€โ™‚๏ธhard, everything depends on skills but we are trying to resolve all of them and Have Fun. ๐Ÿ™Œ

Today I want to share problem which was asked by ๐Ÿข Google.

Problem:

Find the starting and ending position of a given target value in array of integers nums sorted in ascending order.

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

Example:

Input: nums = [3,4,7,7,9,9,9,10], target = 9
Output: [4,6]

Input: nums = [3,4,7,7,9,9,9,10], target = 8
Output: [-1,-1]

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

Top comments (1)

Collapse
 
camicode profile image
CamCode
list_nums = [3,4,7,7,9,9,9,10]
new_list_nums = []

first_element = -1 #0 
last_element = -1 #len(new_list_nums)-1 

while list_nums:
  min = list_nums[0]
  for num in list_nums:
    if num < min:
      min = num 
  new_list_nums.append(min)
  list_nums.remove(min)
print(new_list_nums)
#how to find index in a list sorted 
index_of_list = [i for i in enumerate(new_list_nums)]

target = 8
n = len(new_list_nums)
def findFirstAndLast(new_list_nums, n, target) : 
  first_element = -1 #0 
  last_element = -1 #len(new_list_nums)-1 

  for i in range(0,n) : 
        if (target != new_list_nums[i]) : 
            continue
        if (first_element == -1) : 
            first_element = i 
        last_element = i 

  if (first_element != -1): 
      print( first_element ,last_element) 
  else : 
        print([-1 , -1]) 


print(findFirstAndLast(new_list_nums,n,target))