Find First and Last Position of Element in Sorted Array | Programming Tutorials

preview_player
Показать описание

First and Last Occurrences of x in sorted array where x is a target value

Given a sorted array of integers (Sorted in ascending order). Write a code to find first and last position of a given number. If a number is not found return -1.

The array is sorted and it contains duplicate elements.

In this tutorial, I have explained java code to find first and last position of element in a sorted array using Binary Search in O(logn) time complexity.

For Example -

Example 1 -

Input : {1, 4, 7, 8, 8, 11, 11, 11, 11, 12, 13, 13}, target = 11

Output: {5, 8}

First position : 5
Last position : 8


Example 2 -

Input : {1, 6, 7, 7, 8, 8, 9, 9}, target = 5

Output: {-1, -1}

The target value is not found in an array.


NOTE - Try to solve this problem in O(logn) time complexity.
Рекомендации по теме
Комментарии
Автор

Thanks for drawing things and slowly explaining stuff, you got yourself a subscription sir !

yigitkucuk
Автор

Hi, it is very difficult to be consistent in making videos, your effort is truly inspiring.

Keeep doing the good work. Let us know on how are you achieving this consistency.

skaLife
Автор

So is this a linear search approach then?

KaisarAnvar
Автор

We can also do it by binary search to reduce its time complexity. I recently went through your videos. Your playlist section is well organized, I am looking for such type of organized playlist.But I need to go through your content, it might help me in learning. Nice video.

abhishekverma
Автор

You didn't print the case of target value isn't find

lastmomentofcompetition
Автор

I came from ur advt.... Dont invest money on advt.... Btr make quality products

rounak