Skip to content
Related Articles
Kth Smallest Element in a sorted array formed by reversing subarrays from a random index
• Difficulty Level : Expert
• Last Updated : 15 Jun, 2021

Given a sorted array arr[] of size N and an integer K, the task is to find Kth smallest element present in the array. The given array has been obtained by reversing subarrays {arr, arr[R]} and {arr[R + 1], arr[N – 1]} at some random index R. If the key is not present in the array, print -1.

Examples:

Input: arr[] = { 4, 3, 2, 1, 8, 7, 6, 5 }, K = 2
Output: 2
Explanation: Sorted form of the array arr[] is { 1, 2, 3, 4, 5, 6, 7, 8 }. Therefore, the 2nd smallest element in the array arr[] is 2.

Input: arr[] = { 10, 8, 6, 5, 2, 1, 13, 12 }, K = 3
Output: 5

Naive Approach: The simplest approach to solve the problem is to sort the given array arr[] in increasing order and print the Kth smallest element in the array.

Time Complexity: O(N*log(N))
Auxiliary Space: O(1)

Efficient Approach: The optimal idea is based on the observation that the Rth element is the smallest element because the elements in the range [1, R] are reversed. Now, if the random index is R, it means subarray [1, R] and [R + 1, N] are sorted in decreasing order. Therefore, the task reduceS to finding the value of R which can be obtained using binary search. Finally, print the Kth smallest element.

Follow the steps below to solve the problem:

• Initialize l as 1 and h as N to store the boundary elements index of the search space for the binary search.
• Loop while the value of l+1 < h
• Store the middle element in a variable, mid as (l+h)/2.
• If arr[l] ≥ arr[mid]. If it is true then check on the right side of mid by updating l to mid.
• Otherwise, update r to mid.
• Now after finding R, if K ≤  R, then the answer is arr[R-K+1]. Otherwise, arr[N-(K-R)+1].

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function to find the Kth element in a``// sorted and rotated array at random point``int` `findkthElement(vector<``int``> arr, ``int` `n, ``int` `K)``{``    ` `    ``// Set the boundaries for binary search``    ``int` `l = 0;``    ``int` `h = n - 1, r;` `    ``// Apply binary search to find R``    ``while` `(l + 1 < h)``    ``{``        ` `        ``// Initialize the middle element``        ``int` `mid = (l + h) / 2;``        ` `        ``// Check in the right side of mid``        ``if` `(arr[l] >= arr[mid])``            ``l = mid;``            ` `        ``// Else check in the left side``        ``else``            ``h = mid;``    ``}``    ` `    ``// Random point either l or h``    ``if` `(arr[l] < arr[h])``        ``r = l;``    ``else``        ``r = h;``    ` `    ``// Return the kth smallest element``    ``if` `(K <= r + 1)``        ``return` `arr[r + 1 - K];``    ``else``        ``return` `arr[n - (K - (r + 1))];``}` `// Driver Code``int` `main()``{``    ` `    ``// Given Input``    ``vector<``int``> arr = { 10, 8, 6, 5, 2, 1, 13, 12 };``    ``int` `n = arr.size();``    ``int` `K = 3;``    ` `    ``// Function Call``    ``cout << findkthElement(arr, n, K);``}` `// This code is contributed by mohit kumar 29`

## Java

 `// Java program for the above approach``class` `GFG{``    ` `// Function to find the Kth element in a``// sorted and rotated array at random point``public` `static` `int` `findkthElement(``int` `arr[], ``int` `n, ``int` `K)``{``    ` `    ``// Set the boundaries for binary search``    ``int` `l = ``0``;``    ``int` `h = n - ``1``, r;` `    ``// Apply binary search to find R``    ``while` `(l + ``1` `< h)``    ``{``        ` `        ``// Initialize the middle element``        ``int` `mid = (l + h) / ``2``;``        ` `        ``// Check in the right side of mid``        ``if` `(arr[l] >= arr[mid])``            ``l = mid;``            ` `        ``// Else check in the left side``        ``else``            ``h = mid;``    ``}``    ` `    ``// Random point either l or h``    ``if` `(arr[l] < arr[h])``        ``r = l;``    ``else``        ``r = h;``    ` `    ``// Return the kth smallest element``    ``if` `(K <= r + ``1``)``        ``return` `arr[r + ``1` `- K];``    ``else``        ``return` `arr[n - (K - (r + ``1``))];``}` `// Driver Code``public` `static` `void` `main(String args[])``{``    ` `    ``// Given Input``    ``int` `[]arr = { ``10``, ``8``, ``6``, ``5``, ``2``, ``1``, ``13``, ``12` `};``    ``int` `n = arr.length;``    ``int` `K = ``3``;``    ` `    ``// Function Call``    ``System.out.println(findkthElement(arr, n, K));``}``}` `// This code is contributed by SoumikMondal`

## Python3

 `# Python program for the above approach` `# Function to find the Kth element in a``# sorted and rotated array at random point``def` `findkthElement(arr, n, K):``  ` `      ``# Set the boundaries for binary search``    ``l ``=` `0``    ``h ``=` `n``-``1` `    ``# Apply binary search to find R``    ``while` `l``+``1` `< h:``      ` `          ``# Initialize the middle element``        ``mid ``=` `(l``+``h)``/``/``2` `        ``# Check in the right side of mid``        ``if` `arr[l] >``=` `arr[mid]:``            ``l ``=` `mid` `        ``# Else check in the left side``        ``else``:``            ``h ``=` `mid` `    ``# Random point either l or h``    ``if` `arr[l] < arr[h]:``        ``r ``=` `l``    ``else``:``        ``r ``=` `h` `    ``# Return the kth smallest element``    ``if` `K <``=` `r``+``1``:``        ``return` `arr[r``+``1``-``K]``    ``else``:``        ``return` `arr[n``-``(K``-``(r``+``1``))]`  `# Driver Code``if` `__name__ ``=``=` `"__main__"``:``  ` `      ``# Given Input``    ``arr ``=` `[``10``, ``8``, ``6``, ``5``, ``2``, ``1``, ``13``, ``12``]``    ``n ``=` `len``(arr)``    ``K ``=` `3``    ` `    ``# Function Call``    ``print``(findkthElement(arr, n, K) )`

## C#

 `using` `System.IO;``using` `System;` `class` `GFG {` `    ``// Function to find the Kth element in a``    ``// sorted and rotated array at random point``    ``public` `static` `int` `findkthElement(``int``[] arr, ``int` `n,``                                     ``int` `K)``    ``{` `        ``// Set the boundaries for binary search``        ``int` `l = 0;``        ``int` `h = n - 1, r;` `        ``// Apply binary search to find R``        ``while` `(l + 1 < h) {` `            ``// Initialize the middle element``            ``int` `mid = (l + h) / 2;` `            ``// Check in the right side of mid``            ``if` `(arr[l] >= arr[mid])``                ``l = mid;` `            ``// Else check in the left side``            ``else``                ``h = mid;``        ``}` `        ``// Random point either l or h``        ``if` `(arr[l] < arr[h])``            ``r = l;``        ``else``            ``r = h;` `        ``// Return the kth smallest element``        ``if` `(K <= r + 1)``            ``return` `arr[r + 1 - K];``        ``else``            ``return` `arr[n - (K - (r + 1))];``    ``}` `    ``static` `void` `Main()``    ``{``        ``// Given Input``        ``int``[] arr = { 10, 8, 6, 5, 2, 1, 13, 12 };``        ``int` `n = arr.Length;``        ``int` `K = 3;` `        ``// Function Call``        ``Console.WriteLine(findkthElement(arr, n, K));``    ``}``}` `// This code is contributed by abhinavjain194.`

## Javascript

 ``
Output:
`5`

Time Complexity: O(log(N))
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live

My Personal Notes arrow_drop_up