View Discussion Show
Improve Article Save Article View Discussion Improve Article Save Article Given a sorted array arr[] with possibly duplicate elements, the task is to find indexes of the first and last occurrences of an element x in the given array. Examples:
A Naive Approach:
Below are the steps to implement the above idea:
Below is the implementation of the above approach: C++
C
Java
Python3
C#
PHP
Javascript
Output First Occurrence = 8 Last Occurrence = 9 Time Complexity: O(n) An efficient approach using binary search:1. For the first occurrence of a number
2. For the last occurrence of a number
Below is the implementation of the above approach: C++
C
Java
Python3
C#
PHP
Javascript
Output First Occurrence = 8 Last Occurrence = 9 Time Complexity: O(log n) An Iterative Implementation of Binary Search Solution :
First occurrence:
Last occurrence:
Below is the implementation of the above approach: C++
C
Java
Python3
C#
Javascript
Output First Occurrence = 8 Last Occurrence = 9 Time Complexity:O(log n) An approach using inbuilt functions:Below is the implementation using an inbuilt function: C++
Java
Python
Output First Occurrence = 8 Last Occurrence = 9 Time Complexity: O(log n) Extended Problem : Count number of occurrences in a sorted array This article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks. Which of the following method call gives the position of X that occurs after n th position in the string S1?S1. indexOf("X")
Which of the following method call gives the position of the Firstoccurrence of x in the string S1?The Java String class indexOf() method returns the position of the first occurrence of the specified character or string in a specified string.
Which of the following functions is used to find the position of the particular substring within a string?The FIND function in Excel is used to return the position of a specific character or substring within a text string.
What is most useful when you are exporting a string value into an environment that does not support 16 bit Unicode characters?getBytes( ) is most useful when you are exporting a String value into an environment that does not support 16-bit Unicode characters. For example, most Internet protocols and text file formats use 8-bit ASCII for all text interchange.
|