Find the Kth occurrence of an element in a sorted Array
Last Updated :
21 Apr, 2024
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
// 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_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;
}
}
// 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 occurrence of " + x + " is at index: "
+ obj.Kth_occurrence(arr, n, x, k));
}
}
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_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;
}
}
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 occurrence of {0} is at index: {1}", x,
obj.Kth_occurrence(arr, n, x, k));
}
}
// This code is contributed by Gaurav_Arora
JavaScript
class solution {
Kth_occurrence(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 occurrence of " + x + " is at index: " + obj.Kth_occurrence(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_occurrence(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_occurrence(arr, n, x, k)}")
# This code is contributed by Susobhan Akhuli
OutputKth 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:
- Initialize two variables, left and right, to point to the first and last indices of the array, respectively.
- Perform binary search on the array to find the index of the first occurrence of X. If X is not found, return -1.
- Initialize a variable firstIndex to the index of the first occurrence of X.
- Set left to firstIndex + 1 and right to N-1.
- 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.
- 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
// 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<Integer> 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<Integer> 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<Integer> 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
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)}`);
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
Output2nd 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:
- 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.
- Initialize ans variable to -1.
- Use the lower_bound() function to find the first occurrence of the key element in the array. Store its index in the lb variable.
- Use the upper_bound() function to find the last occurrence of the key element in the array. Store its index in the ub variable.
- 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.
- 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.
- 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
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);
}
}
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_occurrence(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 occurrences
// 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 occurrence of " + x + " is at index: " + obj.Kth_occurrence(arr, x, k));
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.")
OutputKth 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.
Similar Reads
Find the frequency of each element in a sorted array
Given a sorted array, arr[] consisting of N integers, the task is to find the frequencies of each array element. Examples: Input: arr[] = {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10} Output: Frequency of 1 is: 3 Frequency of 2 is: 1 Frequency of 3 is: 2 Frequency of 5 is: 2 Frequency of 8 is: 3 Frequ
10 min read
Find the number of elements greater than k in a sorted array
Given a sorted array arr[] of integers and an integer k, the task is to find the count of elements in the array which are greater than k. Note that k may or may not be present in the array.Examples: Input: arr[] = {2, 3, 5, 6, 6, 9}, k = 6 Output: 1Input: arr[] = {1, 1, 2, 5, 5, 7}, k = 8 Output: 0
7 min read
Find Kth most occurring element in an Array
Given an array of integers arr[] of size N and a number K, the task is to find the Kth most occurring element in this array.Note: If there are more than one numbers in the array with the same frequency, then both are considered to be at the same level of occurrence. Therefore print both the numbers.
11 min read
First element occurring k times in an array
Given an array arr[] of size n, the task is to find the first element that occurs k times. If no element occurs k times, print -1. If multiple elements occur k times, the first one in the array should be the answer. Examples: Input: arr = [1,7,4,3,4,8,7], k=2Output: 7Explanation: Both 7 and 4 occur
9 min read
Find index of first occurrence when an unsorted array is sorted
Given an unsorted array and a number x, find an index of first occurrence of x when we sort the array. If x is not present, print -1. Examples: Input : arr[] = {10, 30, 20, 50, 20} x = 20 Output : 1 Sorted array is {10, 20, 20, 30, 50} Input : arr[] = {10, 30, 20, 50, 20} x = 60 Output : -1 60 is no
8 min read
k-th missing element in an unsorted array
Given an unsorted sequence a[], the task is to find the K-th missing contiguous element in the increasing sequence of the array elements i.e. consider the array in sorted order and find the kth missing number. If no k-th missing element is there output -1. Note: Only elements exists in the range of
6 min read
Find given occurrences of Mth most frequent element of Array
Given an array arr[], integer M and an array query[] containing Q queries, the task is to find the query[i]th occurrence of Mth most frequent element of the array. Examples: Input: arr[] = {1, 2, 20, 8, 8, 1, 2, 5, 8, 0, 6, 8, 2}, M = 1, query[] = {100, 4, 2}Output: -1, 12, 5Explanation: Here most f
9 min read
Sort an array in descending order based on the sum of its occurrence
Given an unsorted array of integers which may contain repeated elements, sort the elements in descending order of some of its occurrence. If there exists more than one element whose sum of occurrences are the same then, the one which is greater will come first. Examples: Input: arr[] = [2, 4, 1, 2,
7 min read
Remove an occurrence of most frequent array element exactly K times
Given an array arr[], the task is to remove an occurrence of the most frequent array element exactly K times. If multiple array elements have maximum frequency, remove the smallest of them. Print the K deleted elements. Examples: Input: arr[] = {1, 3, 2, 1, 4, 1}, K = 2Output: 1 1Explanation: The fr
12 min read
Find k largest elements in an array
Given an array arr[] and an integer k, the task is to find k largest elements in the given array. Elements in the output array should be in decreasing order. Examples: Input: [1, 23, 12, 9, 30, 2, 50], k = 3Output: [50, 30, 23] Input: [11, 5, 12, 9, 44, 17, 2], k = 2Output: [44, 17] Table of Content
15+ min read