# Find the Kth occurrence of an element in a sorted Array

Given a sorted array arr[] of size N, an integer X, and a positive integer K, the task is to find the index of Kth occurrence of X in the given array.

Examples:

Input: N = 10, arr[] = [1, 2, 3, 3, 4, 5, 5, 5, 5, 5], X = 5, K = 2
Output: Starting index of the array is ‘0’ Second occurrence of 5 is at index 6.
Explanation: The first occurrence of 5 is at index 5. And the second occurrence of 5 is at index 6.

Input: N = 8, arr[] = [1, 2, 4, 4, 4, 8, 10, 15], X = 4, K = 1
Output: Starting index of the array is ‘0’ First occurrence of 4 is at index 2.
Explanation: The first occurrence of 4 is at index 2.

Input: N = 4, arr[] = [1, 2, 3, 4], X = 4, K = 2
Output: -1

Approach: To solve the problem follow the below idea:

The idea is to use binary search and check if the middle element is equal to the key, check if the Kth occurrence of the key is to the left of the middle element or to the right of it, or if the middle element itself is the Kth occurrence of the key.

Below are the steps for the above approach:

• Initialize the mid index, mid = start + (end – start) / 2, and a variable ans = -1.
• Run a while loop till start â‰¤ end index,
• Check if the key element and arr[mid] are the same, there is a possibility that the Kth occurrence of the key element is either on the left side or on the right side of the arr[mid].
• Check if arr[mid-K] and arr[mid] are the same. Then the Kth occurrence of the key element must lie on the left side of the arr[mid]
• Else if arr[mid-(K-1)] and arr[mid] are the same, then arr[mid] itself will be the Kth element, update ans = mid.
• Else Kth occurrence of the element will lie on the right side of the mid-element. For which start becomes start = mid+1 (Going to the right search space)
• If arr[mid] and key elements are not the same, then
• Check if key < arr[mid], then end = mid – 1. Since the key element is smaller than arr[mid], it will lie to the left of arr[mid].
• Check if key > arr[mid], then start = mid +1. Since the key element is greater than arr[mid], it will lie to the right of arr[mid].
• Return the Kth occurrence of the key element.

Below is the code for the above approach:

## C++

 `// C++ code for finding the Kth occurrence``// of an element in a sorted array``// using Binary search``#include ``using` `namespace` `std;` `class` `solution {``public``:``    ``int` `Kth_occurence(``int` `arr[], ``int` `size, ``int` `key, ``int` `k)``    ``{``        ``int` `s = 0;``        ``int` `e = size - 1;``        ``int` `mid = s + (e - s) / 2;``        ``int` `ans = -1;``        ``while` `(s <= e) {``            ``if` `(arr[mid] == key) {` `                ``// If arr[mid] happens to``                ``// be the element(whose``                ``// Kth occurrence we are``                ``// searching for), then``                ``// there is a possibility``                ``// that the Kth occurrence``                ``// of the element can be``                ``// either on left or on``                ``// the right side of arr[mid]` `                ``// If the Kth occurrence``                ``// lies to the left side``                ``// of arr[mid]``                ``if` `(arr[mid - k] == arr[mid])``                    ``e = mid - 1;` `                ``// If arr[mid] itself is``                ``// the Kth occurrence.``                ``else` `if` `(arr[mid - (k - 1)] == arr[mid]) {``                    ``ans = mid;``                    ``break``;``                ``}` `                ``// If the Kth occurrence``                ``// lies to the right side``                ``// of arr[mid].``                ``else` `{``                    ``s = mid + 1;``                ``}``            ``}` `            ``// Go for the Left portion.``            ``else` `if` `(key < arr[mid]) {``                ``e = mid - 1;``            ``}` `            ``// Go for the Right``            ``// portion.``            ``else` `if` `(key > arr[mid]) {``                ``s = mid + 1;``            ``}``            ``mid = s + (e - s) / 2;``        ``}``        ``return` `ans;``    ``}``};` `// Drivers code``int` `main()``{``    ``int` `n = 4;``    ``int` `arr[4] = { 1, 2, 3, 4 };``    ``int` `x = 4;``    ``int` `k = 2;``    ``solution obj;` `    ``cout << ``"Kth occurence of "` `<< x << ``" is at index: "``         ``<< obj.Kth_occurence(arr, n, x, k) << endl;``    ``return` `0;``}`

## Java

 `// Java code for finding the Kth occurrence``// of an element in a sorted array``// using Binary search``import` `java.util.*;` `class` `Solution {``    ``public` `int` `Kth_occurence(``int` `arr[], ``int` `size, ``int` `key,``                             ``int` `k)``    ``{``        ``int` `s = ``0``;``        ``int` `e = size - ``1``;``        ``int` `mid = s + (e - s) / ``2``;``        ``int` `ans = -``1``;``        ``while` `(s <= e) {``            ``if` `(arr[mid] == key) {` `                ``// If arr[mid] happens to``                ``// be the element(whose``                ``// Kth occurrence we are``                ``// searching for), then``                ``// there is a possibility``                ``// that the Kth occurrence``                ``// of the element can be``                ``// either on left or on``                ``// the right side of arr[mid]` `                ``// If the Kth occurrence``                ``// lies to the left side``                ``// of arr[mid]``                ``if` `(arr[mid - k] == arr[mid])``                    ``e = mid - ``1``;` `                ``// If arr[mid] itself is``                ``// the Kth occurrence.``                ``else` `if` `(arr[mid - (k - ``1``)] == arr[mid]) {``                    ``ans = mid;``                    ``break``;``                ``}` `                ``// If the Kth occurrence``                ``// lies to the right side``                ``// of arr[mid].``                ``else` `{``                    ``s = mid + ``1``;``                ``}``            ``}` `            ``// Go for the Left portion.``            ``else` `if` `(key < arr[mid]) {``                ``e = mid - ``1``;``            ``}` `            ``// Go for the Right``            ``// portion.``            ``else` `if` `(key > arr[mid]) {``                ``s = mid + ``1``;``            ``}``            ``mid = s + (e - s) / ``2``;``        ``}``        ``return` `ans;``    ``}``}` `// Driver code``class` `GFG {``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `n = ``4``;``        ``int` `arr[] = { ``1``, ``2``, ``3``, ``4` `};``        ``int` `x = ``4``;``        ``int` `k = ``2``;``        ``Solution obj = ``new` `Solution();``        ``System.out.println(``            ``"Kth occurence of "` `+ x + ``" is at index: "``            ``+ obj.Kth_occurence(arr, n, x, k));``    ``}``}`

## Python3

 `# Python code for finding the Kth occurrence``# of an element in a sorted array``# using Binary search` `class` `Solution:``    ``def` `Kth_occurence(``self``, arr, size, key, k):``        ``s ``=` `0``        ``e ``=` `size ``-` `1``        ``mid ``=` `s ``+` `(e ``-` `s) ``/``/` `2``        ``ans ``=` `-``1``        ` `        ``while` `s <``=` `e:``            ``if` `arr[mid] ``=``=` `key:``                ``# If arr[mid] happens to``                ``# be the element(whose``                ``# Kth occurrence we are``                ``# searching for), then``                ``# there is a possibility``                ``# that the Kth occurrence``                ``# of the element can be``                ``# either on left or on``                ``# the right side of arr[mid]` `                ``# If the Kth occurrence``                ``# lies to the left side``                ``# of arr[mid]``                ``if` `arr[mid ``-` `k] ``=``=` `arr[mid]:``                    ``e ``=` `mid ``-` `1` `                ``# If arr[mid] itself is``                ``# the Kth occurrence.``                ``elif` `arr[mid ``-` `(k ``-` `1``)] ``=``=` `arr[mid]:``                    ``ans ``=` `mid``                    ``break` `                ``# If the Kth occurrence``                ``# lies to the right side``                ``# of arr[mid].``                ``else``:``                    ``s ``=` `mid ``+` `1` `            ``# Go for the Left portion.``            ``elif` `key < arr[mid]:``                ``e ``=` `mid ``-` `1` `            ``# Go for the Right``            ``# portion.``            ``elif` `key > arr[mid]:``                ``s ``=` `mid ``+` `1``            ` `            ``mid ``=` `s ``+` `(e ``-` `s) ``/``/` `2``        ` `        ``return` `ans` `# Drivers code``if` `__name__ ``=``=` `'__main__'``:``    ``n ``=` `4``    ``arr ``=` `[``1``, ``2``, ``3``, ``4``]``    ``x ``=` `4``    ``k ``=` `2``    ``obj ``=` `Solution()``    ``print``(f``"Kth occurrence of {x} is at index: {obj.Kth_occurence(arr, n, x, k)}"``)` `# This code is contributed by Susobhan Akhuli`

## C#

 `// C# code for finding the Kth occurrence``// of an element in a sorted array``// using Binary search``using` `System;` `class` `Solution {``    ``public` `int` `Kth_occurence(``int``[] arr, ``int` `size, ``int` `key,``                             ``int` `k)``    ``{``        ``int` `s = 0;``        ``int` `e = size - 1;``        ``int` `mid = s + (e - s) / 2;``        ``int` `ans = -1;``        ``while` `(s <= e) {``            ``if` `(arr[mid] == key) {``                ``// If arr[mid] happens to``                ``// be the element(whose``                ``// Kth occurrence we are``                ``// searching for), then``                ``// there is a possibility``                ``// that the Kth occurrence``                ``// of the element can be``                ``// either on left or on``                ``// the right side of arr[mid]` `                ``// If the Kth occurrence``                ``// lies to the left side``                ``// of arr[mid]``                ``if` `(arr[mid - k] == arr[mid]) {``                    ``e = mid - 1;``                ``}``                ``// If arr[mid] itself is``                ``// the Kth occurrence.``                ``else` `if` `(arr[mid - (k - 1)] == arr[mid]) {``                    ``ans = mid;``                    ``break``;``                ``}``                ``// If the Kth occurrence``                ``// lies to the right side``                ``// of arr[mid].``                ``else` `{``                    ``s = mid + 1;``                ``}``            ``}` `            ``// Go for the Left portion.``            ``else` `if` `(key < arr[mid]) {``                ``e = mid - 1;``            ``}` `            ``// Go for the Right``            ``// portion.``            ``else` `if` `(key > arr[mid]) {``                ``s = mid + 1;``            ``}``            ``mid = s + (e - s) / 2;``        ``}``        ``return` `ans;``    ``}``}` `class` `Program {``    ``static` `void` `Main(``string``[] args)``    ``{``        ``int` `n = 4;``        ``int``[] arr = { 1, 2, 3, 4 };``        ``int` `x = 4;``        ``int` `k = 2;``        ``Solution obj = ``new` `Solution();` `        ``Console.WriteLine(``            ``"Kth occurence of {0} is at index: {1}"``, x,``            ``obj.Kth_occurence(arr, n, x, k));``    ``}``}` `// This code is contributed by Gaurav_Arora`

## Javascript

 `class solution {``    ``Kth_occurence(arr, size, key, k) {``        ``let s = 0;``        ``let e = size - 1;``        ``let mid = s + Math.floor((e - s) / 2);``        ``let ans = -1;``        ``while` `(s <= e) {``            ``if` `(arr[mid] === key) {``            ` `                ``// If arr[mid] happens to``                ``// be the element(whose``                ``// Kth occurrence we are``                ``// searching for), then``                ``// there is a possibility``                ``// that the Kth occurrence``                ``// of the element can be``                ``// either on left or on``                ``// the right side of arr[mid]`` ` `                ``// If the Kth occurrence``                ``// lies to the left side``                ``// of arr[mid]``                ``if` `(arr[mid - k] === arr[mid]) {``                    ``e = mid - 1;``                ``} ``                ` `                ``// If arr[mid] itself is``                ``// the Kth occurrence.``                ``else` `if` `(arr[mid - (k - 1)] === arr[mid]) {``                    ``ans = mid;``                    ``break``;``                ``}``                ` `                ``// If the Kth occurrence``                ``// lies to the right side``                ``// of arr[mid].``                ``else` `{``                    ``s = mid + 1;``                ``}``            ``}``            ` `            ``// Go for the Left portion.``            ``else` `if` `(key < arr[mid]) {``                ``e = mid - 1;``            ``}``            ` `            ``// Go for the Right``            ``// portion.``            ``else` `if` `(key > arr[mid]) {``                ``s = mid + 1;``            ``}``            ``mid = s + Math.floor((e - s) / 2);``        ``}``        ``return` `ans;``    ``}``}` `// Drivers code``let n = 4;``let arr = [1, 2, 3, 4];``let x = 4;``let k = 2;``let obj = ``new` `solution();``console.log(``"Kth occurence of "` `+ x + ``" is at index: "` `+ obj.Kth_occurence(arr, n, x, k));`

Output
```Kth occurence of 4 is at index: -1

```

Time Complexity: O(logN), because of the binary search approach.
Auxiliary Space: O(1).

### Another Approach: (Using Two Binary Search)

Another approach to solve this problem is to use two binary searches – one to find the index of the first occurrence of X and another to find the index of the Kth occurrence of X.

#### Algorithm:

1. Initialize two variables, left and right, to point to the first and last indices of the array, respectively.
2. Perform binary search on the array to find the index of the first occurrence of X. If X is not found, return -1.
3. Initialize a variable firstIndex to the index of the first occurrence of X.
4. Set left to firstIndex + 1 and right to N-1.
5. Perform binary search on the subarray arr[left…right] to find the index of the Kth occurrence of X. If Kth occurrence of X is not found, return -1.
6. Return the index of the Kth occurrence of X in the array as firstIndex + index found in step 5.

Below is the implementation of the above approach:

## C++

 `// C++ code for finding the Kth occurrence``// of an element in a sorted array``// Using Two Binary Search` `#include ``#include ` `using` `namespace` `std;` `int` `binarySearch(vector<``int``>& arr, ``int` `left, ``int` `right, ``int` `target) {``    ``while` `(left <= right) {``        ``int` `mid = (left + right) / 2;``        ``if` `(arr[mid] == target) {``            ``return` `mid;``        ``} ``else` `if` `(arr[mid] < target) {``            ``left = mid + 1;``        ``} ``else` `{``            ``right = mid - 1;``        ``}``    ``}``    ``return` `-1;``}` `int` `findKthOccurrence(vector<``int``>& arr, ``int` `N, ``int` `X, ``int` `K) {``    ``int` `left = 0, right = N - 1;``    ``int` `firstIndex = binarySearch(arr, left, right, X);` `    ``if` `(firstIndex == -1) {``        ``return` `-1;``    ``}` `    ``left = firstIndex + 1;``    ``right = N - 1;``    ``int` `count = 1;` `    ``while` `(left <= right) {``        ``int` `mid = (left + right) / 2;``        ``if` `(arr[mid] == X) {``            ``count++;``            ``if` `(count == K) {``                ``return` `mid;``            ``} ``else` `{``                ``left = mid + 1;``            ``}``        ``} ``else` `if` `(arr[mid] < X) {``            ``left = mid + 1;``        ``} ``else` `{``            ``right = mid - 1;``        ``}``    ``}``    ``return` `-1;``}` `// Drivers code``int` `main() {``    ``int` `n = 4;``    ``vector<``int``> arr = {1, 2, 3, 4};``    ``int` `x = 4;``    ``int` `k = 2;``    ``cout << k << ``"nd occurrence of "` `<< x << ``" is at index: "` `<< findKthOccurrence(arr, n, x, k) << endl;` `    ``return` `0;``}` `// This code is contributed by Pushpesh Raj`

## Java

 `// Java code for finding the Kth occurrence``// of an element in a sorted array``// Using Two Binary Search` `import` `java.util.*;` `class` `GFG {``    ``public` `static` `int` `binarySearch(List arr, ``int` `left, ``                                   ``int` `right, ``int` `target) {``        ``while` `(left <= right) {``            ``int` `mid = (left + right) / ``2``;``            ``if` `(arr.get(mid) == target) {``                ``return` `mid;``            ``} ``else` `if` `(arr.get(mid) < target) {``                ``left = mid + ``1``;``            ``} ``else` `{``                ``right = mid - ``1``;``            ``}``        ``}``        ``return` `-``1``;``    ``}` `    ``public` `static` `int` `findKthOccurrence(List arr, ``int` `N, ``                                        ``int` `X, ``int` `K) {``        ``int` `left = ``0``, right = N - ``1``;``        ``int` `firstIndex = binarySearch(arr, left, right, X);` `        ``if` `(firstIndex == -``1``) {``            ``return` `-``1``;``        ``}` `        ``left = firstIndex + ``1``;``        ``right = N - ``1``;``        ``int` `count = ``1``;` `        ``while` `(left <= right) {``            ``int` `mid = (left + right) / ``2``;``            ``if` `(arr.get(mid) == X) {``                ``count++;``                ``if` `(count == K) {``                    ``return` `mid;``                ``} ``else` `{``                    ``left = mid + ``1``;``                ``}``            ``} ``else` `if` `(arr.get(mid) < X) {``                ``left = mid + ``1``;``            ``} ``else` `{``                ``right = mid - ``1``;``            ``}``        ``}``        ``return` `-``1``;``    ``}` `    ``public` `static` `void` `main(String[] args) {``        ``int` `n = ``4``;``        ``List arr = Arrays.asList(``1``, ``2``, ``3``, ``4``);``        ``int` `x = ``4``;``        ``int` `k = ``2``;``        ``System.out.println(k + ``"nd occurrence of "` `+ x + ``" is at index: "` `+ findKthOccurrence(arr, n, x, k));``    ``}``}`  `// This code is contributed by Vaibhav Nandan`

## Python3

 `# Python code for finding the Kth occurrence``# of an element in a sorted array``# Using Two Binary Search` `def` `binarySearch(arr, left, right, target):``    ``while` `left <``=` `right:``        ``mid ``=` `(left ``+` `right) ``/``/` `2``        ``if` `arr[mid] ``=``=` `target:``            ``return` `mid``        ``elif` `arr[mid] < target:``            ``left ``=` `mid ``+` `1``        ``else``:``            ``right ``=` `mid ``-` `1``    ``return` `-``1``    ` `def` `findKthOccurrence(arr, N, X, K):``    ``left, right ``=` `0``, N``-``1``    ``firstIndex ``=` `binarySearch(arr, left, right, X)``    ` `    ``if` `firstIndex ``=``=` `-``1``:``        ``return` `-``1``    ` `    ``left, right ``=` `firstIndex``+``1``, N``-``1``    ``count ``=` `1``    ` `    ``while` `left <``=` `right:``        ``mid ``=` `(left ``+` `right) ``/``/` `2``        ``if` `arr[mid] ``=``=` `X:``            ``count ``+``=` `1``            ``if` `count ``=``=` `K:``                ``return` `mid``            ``else``:``                ``left ``=` `mid ``+` `1``        ``elif` `arr[mid] < X:``            ``left ``=` `mid ``+` `1``        ``else``:``            ``right ``=` `mid ``-` `1``    ``return` `-``1` `# Drivers code``if` `__name__ ``=``=` `'__main__'``:``    ``n ``=` `4``    ``arr ``=` `[``1``, ``2``, ``3``, ``4``]``    ``x ``=` `4``    ``k ``=` `2``    ``print``(f``"{k}nd occurrence of {x} is at index: {findKthOccurrence(arr, n, x, k)}"``)` `# This code is contributed by Susobhan Akhuli`

## C#

 `// C# code for finding the Kth occurrence``// of an element in a sorted array``// Using Two Binary Search``using` `System;` `class` `GFG``{``    ``static` `int` `BinarySearch(``int``[] arr, ``int` `left, ``int` `right, ``int` `target)``    ``{``        ``while` `(left <= right)``        ``{``            ``int` `mid = (left + right) / 2;``            ``if` `(arr[mid] == target)``            ``{``                ``return` `mid;``            ``}``            ``else` `if` `(arr[mid] < target)``            ``{``                ``left = mid + 1;``            ``}``            ``else``            ``{``                ``right = mid - 1;``            ``}``        ``}``        ``return` `-1;``    ``}``    ``static` `int` `FindKthOccurrence(``int``[] arr, ``int` `N, ``int` `X, ``int` `K)``    ``{``        ``int` `left = 0, right = N - 1;``        ``int` `firstIndex = BinarySearch(arr, left, right, X);` `        ``if` `(firstIndex == -1)``        ``{``            ``return` `-1;``        ``}``        ``left = firstIndex + 1;``        ``right = N - 1;``        ``int` `count = 1;``        ``while` `(left <= right)``        ``{``            ``int` `mid = (left + right) / 2;``            ``if` `(arr[mid] == X)``            ``{``                ``count++;``                ``if` `(count == K)``                ``{``                    ``return` `mid;``                ``}``                ``else``                ``{``                    ``left = mid + 1;``                ``}``            ``}``            ``else` `if` `(arr[mid] < X)``            ``{``                ``left = mid + 1;``            ``}``            ``else``            ``{``                ``right = mid - 1;``            ``}``        ``}``        ``return` `-1;``    ``}``    ``// Main function``    ``static` `void` `Main()``    ``{``        ``int` `n = 4;``        ``int``[] arr = { 1, 2, 3, 4 };``        ``int` `x = 4;``        ``int` `k = 2;``        ``Console.WriteLine(\$``"{k}nd occurrence of {x} is at index: {FindKthOccurrence(arr, n, x, k)}"``);``    ``}``}`

## Javascript

 `// Function to perform binary search in a sorted array``function` `binarySearch(arr, left, right, target) {``    ``while` `(left <= right) {``        ``let mid = Math.floor((left + right) / 2);``        ``if` `(arr[mid] === target) {``            ``return` `mid; ``// Return the index if target is found``        ``} ``else` `if` `(arr[mid] < target) {``            ``left = mid + 1; ``// Move the search range to the right``        ``} ``else` `{``            ``right = mid - 1; ``// Move the search range to the left``        ``}``    ``}``    ``return` `-1; ``// Return -1 if target is not found``}` `// Function to find the Kth occurrence of an element in a sorted array``function` `findKthOccurrence(arr, N, X, K) {``    ``let left = 0;``    ``let right = N - 1;` `    ``// Find the index of the first occurrence of X using binary search``    ``let firstIndex = binarySearch(arr, left, right, X);` `    ``if` `(firstIndex === -1) {``        ``return` `-1; ``// If X is not present, return -1``    ``}` `    ``left = firstIndex + 1;``    ``right = N - 1;``    ``let count = 1;` `    ``// Find the index of the Kth occurrence of X using binary search``    ``while` `(left <= right) {``        ``let mid = Math.floor((left + right) / 2);``        ``if` `(arr[mid] === X) {``            ``count++;``            ``if` `(count === K) {``                ``return` `mid; ``// Return the index of the Kth occurrence of X``            ``} ``else` `{``                ``left = mid + 1;``            ``}``        ``} ``else` `if` `(arr[mid] < X) {``            ``left = mid + 1;``        ``} ``else` `{``            ``right = mid - 1;``        ``}``    ``}``    ``return` `-1; ``// If Kth occurrence of X is not found, return -1``}` `// Driver code``const n = 4;``const arr = [1, 2, 3, 4];``const x = 4;``const k = 2;``console.log(`\${k}nd occurrence of \${x} is at index: \${findKthOccurrence(arr, n, x, k)}`);`

Output
```2nd occurrence of 4 is at index: -1

```

Time Complexity: O(log N + log N) = O(log N), as we are performing two binary searches on the array.
Auxiliary Space: O(1), as we are using only a constant amount of extra space to store the variables.

Using inbuilt functions:

This approach to solve the problem is to use inbuilt function lower_bound and upper_bound to get indices of first and last occurrence of the element. Once we get it we can add k to first occurrence index if it’s within element’s last occcurrence. Else, we can return -1.

Algorithm:

1.  Define a function Kth_occurence which takes four arguments: the sorted array arr[], its size n, the key element to be searched key and the  integer k representing the Kth occurrence of the key element.
2.  Initialize ans variable to -1.
3.  Use the lower_bound() function to find the first occurrence of the key element in the array. Store its index in the lb variable.
4.  Use the upper_bound() function to find the last occurrence of the key element in the array. Store its index in the ub variable.
5.  If the key element is not found in the array or the number of occurrences of the key element in the array is less than k, return -1.
6.  Otherwise, calculate the index of the kth occurrence of the key element by adding k-1 to lb. Store this index in the ans variable.
7.  Return ans.

Below is the implementation of the approach:

## C++

 `// C++ code for finding the Kth occurrence``// of an element in a sorted array` `#include ``using` `namespace` `std;` `class` `solution {``public``:``      ``// Function to find the Kth occurrence ``      ``// of an element in a sorted Array``    ``int` `Kth_occurence(``int` `arr[], ``int` `n, ``int` `key, ``int` `k) {``        ``int` `ans = -1;``          ` `          ``// lower_bound of key``          ``int` `lb = lower_bound( arr, arr + n, key ) - arr;``                    ` `          ``// upper_bound of key``          ``int` `ub = upper_bound( arr, arr + n, key ) - arr;``          ` `          ``// if key doesn't exist or k occurences``          ``// are not there of the key``          ``if``( (lb == n || arr[lb] != key) || (ub - lb) < k )``          ``return` `-1;``          ` `          ``ans = lb + k - 1;``          ``return` `ans;``    ``}``};` `// Drivers code``int` `main() {``    ``int` `n = 4;``    ``int` `arr[4] = { 1, 2, 3, 4 };``    ``int` `x = 4;``    ``int` `k = 2;``  ` `    ``solution obj;` `    ``cout << ``"Kth occurence of "` `<< x << ``" is at index: "``         ``<< obj.Kth_occurence(arr, n, x, k) << endl;``    ``return` `0;``}` `// This code is contributed by Chandramani Kumar`

## Java

 `public` `class` `Solution {``    ``// Function to find the Kth occurrence of an element in a sorted Array``    ``public` `int` `findKthOccurrence(``int``[] arr, ``int` `key, ``int` `k) {``        ``int` `ans = -``1``;``        ``// Finding the lower bound index of the key``        ``int` `lb = lowerBound(arr, key);``        ``// Finding the upper bound index of the key``        ``int` `ub = upperBound(arr, key);` `        ``// If key doesn't exist or there are not k occurrences of the key``        ``if` `(lb == -``1` `|| arr[lb] != key || (ub - lb) < k) {``            ``return` `-``1``;``        ``}` `        ``ans = lb + k - ``1``;``        ``return` `ans;``    ``}` `    ``// Function to find the lower bound index of key``    ``private` `int` `lowerBound(``int``[] arr, ``int` `key) {``        ``int` `left = ``0``;``        ``int` `right = arr.length - ``1``;``        ``int` `lb = -``1``;``        ` `        ``while` `(left <= right) {``            ``int` `mid = left + (right - left) / ``2``;` `            ``if` `(arr[mid] >= key) {``                ``lb = mid;``                ``right = mid - ``1``;``            ``} ``else` `{``                ``left = mid + ``1``;``            ``}``        ``}` `        ``return` `lb;``    ``}` `    ``// Function to find the upper bound index of key``    ``private` `int` `upperBound(``int``[] arr, ``int` `key) {``        ``int` `left = ``0``;``        ``int` `right = arr.length - ``1``;``        ``int` `ub = -``1``;` `        ``while` `(left <= right) {``            ``int` `mid = left + (right - left) / ``2``;` `            ``if` `(arr[mid] > key) {``                ``ub = mid;``                ``right = mid - ``1``;``            ``} ``else` `{``                ``left = mid + ``1``;``            ``}``        ``}` `        ``return` `ub;``    ``}` `    ``public` `static` `void` `main(String[] args) {``        ``int` `n = ``4``;``        ``int``[] arr = {``1``, ``2``, ``3``, ``4``};``        ``int` `x = ``4``;``        ``int` `k = ``2``;``        ``Solution obj = ``new` `Solution();``        ``int` `result = obj.findKthOccurrence(arr, x, k);``        ``System.out.println(``"Kth occurrence of "` `+ x + ``" is at index: "` `+ result);``    ``}``}`

## Python3

 `class` `Solution:``    ``def` `kth_occurrence(``self``, arr, key, k):``        ``lb ``=` `self``.lower_bound(arr, key)``        ``ub ``=` `self``.upper_bound(arr, key)` `        ``if` `lb ``=``=` `len``(arr) ``or` `arr[lb] !``=` `key ``or` `(ub ``-` `lb) < k:``            ``return` `-``1` `        ``return` `lb ``+` `k ``-` `1` `    ``def` `lower_bound(``self``, arr, key):``        ``left, right ``=` `0``, ``len``(arr)``        ` `        ``while` `left < right:``            ``mid ``=` `left ``+` `(right ``-` `left) ``/``/` `2``            ``if` `arr[mid] < key:``                ``left ``=` `mid ``+` `1``            ``else``:``                ``right ``=` `mid``        ` `        ``return` `left` `    ``def` `upper_bound(``self``, arr, key):``        ``left, right ``=` `0``, ``len``(arr)``        ` `        ``while` `left < right:``            ``mid ``=` `left ``+` `(right ``-` `left) ``/``/` `2``            ``if` `arr[mid] <``=` `key:``                ``left ``=` `mid ``+` `1``            ``else``:``                ``right ``=` `mid``        ` `        ``return` `left`  `# Driver's code``if` `__name__ ``=``=` `"__main__"``:``    ``arr ``=` `[``1``, ``2``, ``3``, ``4``]``    ``x ``=` `4``    ``k ``=` `2` `    ``obj ``=` `Solution()``    ``result ``=` `obj.kth_occurrence(arr, x, k)` `    ``if` `result !``=` `-``1``:``        ``print``(f``"Kth occurrence of {x} is at index: {result}"``)``    ``else``:``        ``print``(f``"Kth occurrence of {x} not found."``)`

## C#

 `using` `System;` `class` `Solution``{``    ``// Function to find the Kth occurrence ``    ``// of an element in a sorted Array``    ``public` `int` `KthOccurrence(``int``[] arr, ``int` `key, ``int` `k)``    ``{``        ``int` `ans = -1;` `        ``// Lower bound of key``        ``int` `lb = Array.BinarySearch(arr, key);` `        ``// Upper bound of key``        ``int` `ub = Array.BinarySearch(arr, key + 1);` `        ``// If key doesn't exist or k occurrences``        ``// are not there of the key``        ``if` `((lb < 0 || arr[lb] != key) || (ub - lb) < k)``            ``return` `-1;` `        ``ans = lb + k - 1;``        ``return` `ans;``    ``}``}` `class` `Program``{``    ``static` `void` `Main()``    ``{``        ``int``[] arr = { 1, 2, 3, 4 };``        ``int` `x = 4;``        ``int` `k = 2;` `        ``Solution obj = ``new` `Solution();` `        ``Console.WriteLine(``"Kth occurrence of "` `+ x + ``" is at index: "` `+``                           ``obj.KthOccurrence(arr, x, k));``    ``}``}`

## Javascript

 `cpp``// JavaScript code for finding the Kth occurrence``// of an element in a sorted array` `class Solution {``    ``// Function to find the Kth occurrence ``    ``// of an element in a sorted Array``    ``Kth_occurence(arr, key, k) {``        ``let ans = -1;``        ``// lower_bound of key``        ``let lb = arr.findIndex((element) => element >= key);``        ``// upper_bound of key``        ``let ub = arr.findIndex((element) => element > key);``        ``// if key doesn't exist or k occurences``        ``// are not there of the key``        ``if` `(lb === -1 || arr[lb] !== key || (ub - lb) < k) {``            ``return` `-1;``        ``}``        ``ans = lb + k - 1;``        ``return` `ans;``    ``}``}` `// Drivers code``let n = 4;``let arr = [1, 2, 3, 4];``let x = 4;``let k = 2;``let obj = ``new` `Solution();``console.log(``"Kth occurence of "` `+ x + ``" is at index: "` `+ obj.Kth_occurence(arr, x, k));`

Output
```Kth occurence of 4 is at index: -1

```

Time Complexity: O(logN) as lower_bound and upper_bound takes logN time. Here, N is size of input array.
Space Complexity: O(1) as no extra space has been used.

Previous
Next