Skip to content

Commit b163e39

Browse files
Create Most Frequent Element Explanation.txt
1 parent 3172e48 commit b163e39

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
If there is a segment of length K > (R - L + 1)/2, it will necessarily pass through the middle element.
2+
3+
The middle element is the only candidate for this.
4+
5+
Precompute the first unequal element on the left and right with a linear sweep and then find the length of the
6+
segment containing the middle element.
7+
Check if it is >= K
8+
9+
-----
10+
11+
int main()
12+
{
13+
int no_of_elements, no_of_queries;
14+
cin >> no_of_elements >> no_of_queries;
15+
16+
vector <int> A(no_of_elements + 5);
17+
for(int i = 1; i <= no_of_elements; i++)
18+
{
19+
cin >> A[i];
20+
}
21+
22+
vector <int> left_equal(no_of_elements + 1);
23+
for(int i = 1; i <= no_of_elements; i++)
24+
{
25+
left_equal[i] = (A[i] == A[i - 1] ? left_equal[i - 1] : i);
26+
}
27+
28+
vector <int> right_equal(no_of_elements + 1);
29+
for(int i = no_of_elements; i >= 1; i--)
30+
{
31+
right_equal[i] = (A[i] == A[i + 1] ? right_equal[i + 1]: i);
32+
}
33+
34+
for(int i = 1; i <= no_of_queries; i++)
35+
{
36+
int left, right, k;
37+
cin >> left >> right >> k;
38+
39+
int mid = left + (right - left)/2;
40+
int segment_left = max(left, left_equal[mid]);
41+
int segment_right = min(right, right_equal[mid]);
42+
int segment = segment_right - segment_left + 1;
43+
44+
cout << (segment < k ? -1 : A[mid]) << "\n";
45+
}
46+
47+
return 0;
48+
}

0 commit comments

Comments
 (0)