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

Опубликовано: 25 Январь 2020
на канале: Programming Tutorials
5,976
72

Find first and last position of element in sorted array - https://webrewrite.com/find-first-and...

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.


Смотрите видео Find First and Last Position of Element in Sorted Array | Programming Tutorials онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь Programming Tutorials 25 Январь 2020, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 5,976 раз и оно понравилось 72 людям.