Open In App

Find the Kth occurrence of an element in a sorted Array

Last Updated : 21 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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 <bits/stdc++.h>
using namespace std;

class solution {
public:
    int Kth_occurrence(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 occurrence of " << x << " is at index: "
         << obj.Kth_occurrence(arr, n, x, k) << endl;
    return 0;
}
Java C# JavaScript Python3

Output
Kth occurrence 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 <iostream>
#include <vector>

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 C# JavaScript Python3

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_occurrence 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 <bits/stdc++.h>
using namespace std;

class solution {
public:
      // Function to find the Kth occurrence 
      // of an element in a sorted Array
    int Kth_occurrence(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 occurrences
          // 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 occurrence of " << x << " is at index: "
         << obj.Kth_occurrence(arr, n, x, k) << endl;
    return 0;
}

// This code is contributed by Chandramani Kumar
Java C# JavaScript Python3

Output
Kth occurrence 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.



Next Article

Similar Reads

three90RightbarBannerImg