forked from mbobesic/algorithms-playground
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEquiLeader.py
More file actions
71 lines (53 loc) · 1.6 KB
/
Copy pathEquiLeader.py
File metadata and controls
71 lines (53 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# link: https://codility.com/demo/take-sample-test/equi_leader
# name: EquiLeader
__author__ = 'mislav'
def solution(A):
# write your code in Python 2.7
stack = []
counts = {}
n = len(A)
candidates = [None] * n
rev_candidates = [None] * n
for index in xrange(n):
count = 0
value = A[index]
if value in counts:
count = counts[value]
counts[value] = count + 1
if len(stack) > 0 and value != stack[-1]:
stack.pop()
else:
stack.append(value)
if len(stack) > 0:
candidates[index] = stack[-1]
stack = []
for index in xrange(n - 1, -1, -1):
if len(stack) > 0 and A[index] != stack[-1]:
stack.pop()
else:
stack.append(A[index])
if len(stack) > 0:
rev_candidates[index] = stack[-1]
result = 0
prefix_counts = {}
for index in xrange(n-1):
count = 0
value = A[index]
if value in prefix_counts:
count = prefix_counts[value]
prefix_counts[value] = count + 1
if candidates[index] is None:
continue
if candidates[index] != rev_candidates[index+1]:
continue
candidate = candidates[index]
if prefix_counts[candidate]*2 <= index + 1:
continue
if (counts[candidate] - prefix_counts[candidate])*2 <= n - index - 1:
continue
result += 1
return result
print solution([1,2,1,1,2,1])
print solution([5,6,7,1,1,1,1,1,1,1,9,8,3])
print solution(range(100))
print solution([4,3,4,4,4,2])