Skip to content

Commit 6a0fb7a

Browse files
authored
Create EquiLeader.md
1 parent 9f951b6 commit 6a0fb7a

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed

EquiLeader.md

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
2+
Task description
3+
A non-empty zero-indexed array A consisting of N integers is given.
4+
5+
The leader of this array is the value that occurs in more than half of the elements of A.
6+
7+
An equi leader is an index S such that 0 ≤ S < N − 1 and two sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N − 1] have leaders of the same value.
8+
9+
For example, given array A such that:
10+
11+
```
12+
A[0] = 4
13+
A[1] = 3
14+
A[2] = 4
15+
A[3] = 4
16+
A[4] = 4
17+
A[5] = 2
18+
```
19+
we can find two equi leaders:
20+
21+
* 0, because sequences: (4) and (3, 4, 4, 4, 2) have the same leader, whose value is 4.
22+
* 2, because sequences: (4, 3, 4) and (4, 4, 2) have the same leader, whose value is 4.
23+
24+
The goal is to count the number of equi leaders.
25+
26+
Write a function:
27+
28+
```
29+
function solution(A);
30+
```
31+
32+
that, given a non-empty zero-indexed array A consisting of N integers, returns the number of equi leaders.
33+
34+
For example, given:
35+
36+
```
37+
A[0] = 4
38+
A[1] = 3
39+
A[2] = 4
40+
A[3] = 4
41+
A[4] = 4
42+
A[5] = 2
43+
```
44+
the function should return 2, as explained above.
45+
46+
Assume that:
47+
48+
* N is an integer within the range [1..100,000];
49+
* each element of array A is an integer within the range [−1,000,000,000..1,000,000,000].
50+
51+
Complexity:
52+
53+
* expected worst-case time complexity is O(N);
54+
* expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
55+
Elements of input arrays can be modified.
56+
57+
```javascript
58+
function solution(A) {
59+
var pos = 0;
60+
var count = 0;
61+
62+
for (var i = 0; i < A.length; i++) {
63+
if (A[pos] == A[i]) {
64+
count++;
65+
} else {
66+
count--;
67+
if (count == 0) {
68+
pos = i;
69+
count++;
70+
}
71+
}
72+
}
73+
74+
var ret = 0;
75+
var cand = A[pos];
76+
77+
var E = [];
78+
var N = [];
79+
80+
var ec = 0;
81+
var nc = 0;
82+
for (var i = 0; i < A.length; i++) {
83+
if (A[i] == cand) {
84+
ec++;
85+
} else {
86+
nc++;
87+
}
88+
E[i] = ec;
89+
N[i] = nc;
90+
}
91+
92+
for (var i = 0; i < A.length; i++) {
93+
if (E[i] > N[i] && ((nc - N[i]) < (ec - E[i]))) {
94+
ret++;
95+
}
96+
}
97+
98+
return ret;
99+
}
100+
```

0 commit comments

Comments
 (0)