I am new to this community and I have a question regarding a problem I was trying to solve. Could anyone review my algorithm for solving this problem? I want to emphasize also that the algorithm must use the Quickselect algorithm (i.e. https://en.wikipedia.org/wiki/Quickselect).
The question is :
Given an array A[1..n], write an algorithm that checks if there are two elements satisfying the following conditions (Algorithm runtime should be O(n)):
- $ x < y $
- The value of x appears more than n/3 times
- The value of y appears more than n/4 times
The algorithm that I suggest for solving this problem is the following:
- Find the median of the array A[1..n] using QuickSelect and store its value inside a variable M.
- Partition the array around M.
- Find the median of the array A[1...n/2] using QuickSelect (left part of the partitioned array from above) and store its value inside a variable M1.
- Find the median of the array A[n/2...n] using QuickSelect (right part of the partitioned array from above) and store its value inside a variable M2.
- Partition the two sub-arrays from stages 3-4 around M1 and M2
- The elements must satisfy $x,y \in \{M, M1, M2\}$ because the array now is "almost sorted" and the distance between two medians is n/4 (here I am not sure if I can say it is correct because of the pigeonhole principle).
- Iterate over the array and count the occurrences of M,M1,M2 to check if they're satisfying the conditions of the question then return true if yes, or false otherwise.
EDIT:
To be more specific my main concern about this algorithm is in stage 6 where I claim that the elements we are searching for (i.e x,y) must satisfy $x,y \in \{M, M1, M2\}$.
In other words, this is equivalent to the question that if we are given an array A[1..n] and two elements x and y which occurs n/3 times and n/4 times respectively, can we find what those elements are by partitioning the array A[1..n] for the first time around the median of A[1..n] and then partitioning the 2 sub-arrays to the left of the median (A[1..n/2]) and to the right of the median (A[n/2..n]) around their median ?
My motivation behind this claim is the fact that x and y each occur more than n/4 which means that if nor x nor y "sitting" on the median of A[1..n] then the median must be an element such that x<M<y therefore if we split the 2 sub-arrays A[1..n/2] and A[n/2..n] around their medians we can say that their medians must be x and y (because each one of the sub-arrays is of size n/2 and the values x or y occur more than n/4 which is more than half of n/2).
Otherwise, if the median of A[1..n] is x or y (let's say x) then with pretty much similar reasoning we can say that one of the medians of the 2 sub-arrays must be y.
Will appreciate any clue or review for this algorithm, thanks!