LeetCode 1150: Check If a Number Is Majority Element in a Sorted Array - Interview Prep Ep 48

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


⭐ Support my channel and connect with me:

Solution explained:

1. We could use binary search to find either the first or last occurrence of this target element in this given array, then plus or minus half of the array length to get the lastIndex or firstIndex;
2. In order for this target to be qualified as a majority element, either lastIndex or firstIndex has to be within the array boundary and also the element at either lastIndex or firstIndex has to be equal to target.

Time complexity: O(logn)
Space complexity: O(1)

// TOOLS THAT I USE:

// MY FAVORITE BOOKS:

My ENTIRE Programming Equipment and Computer Science Bookshelf:

And make sure you subscribe to my channel!

Your comments/thoughts/questions/advice will be greatly appreciated!

#softwareengineering #leetcode #algorithms #coding #interview #SDE #SWE #SiliconValley #programming #datastructures
Рекомендации по теме
Комментарии
Автор

Why are you not considering the left<=right in the while loop, the less than or equal to lets the possibility of having even 1 element in the array!!
Whereas the left < right will not consider that. Please throw some more light, obviously you re solution is correct. But I would like to know the how part of this strong less than in the while loop condition!!

bablobko
Автор

It seems that it's better to consider the possibility that target doesn't exist in the array in the binary search function, although it's fine to solve this problem without considering it.

wonderzoner