File tree Expand file tree Collapse file tree 1 file changed +69
-0
lines changed
Python/Interviewbit/Arrays Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Problem Link: https://www.interviewbit.com/problems/balance-array/
3
+
4
+ Problem Description
5
+ Given an integer array A of size N. You need to count the number of special elements in the given array.
6
+ A element is special if removal of that element make the array balanced.
7
+ Array will be balanced if sum of even index element equal to sum of odd index element.
8
+
9
+ Problem Constraints
10
+ 1 <= N <= 105
11
+ 1 <= A[i] <= 109
12
+
13
+ Input Format
14
+ First and only argument is an integer array A of size N.
15
+
16
+ Output Format
17
+ Return an integer denoting the count of special elements.
18
+
19
+ Example Input
20
+ Input 1:
21
+ A = [2, 1, 6, 4]
22
+ Input 2:
23
+ A = [5, 5, 2, 5, 8]
24
+
25
+ Example Output
26
+ Output 1:
27
+ 1
28
+
29
+ Output 2:
30
+ 2
31
+
32
+ Example Explanation
33
+ Explanation 1:
34
+ After deleting 1 from array : {2,6,4}
35
+ (2+4) = (6)
36
+ Hence 1 is the only special element, so count is 1
37
+
38
+ Explanation 2:
39
+ If we delete A[0] or A[1] , array will be balanced
40
+ (5+5) = (2+8)
41
+ So A[0] and A[1] are special elements, so count is 2.
42
+ """
43
+ class Solution :
44
+ # @param A : list of integers
45
+ # @return an integer
46
+ def solve (self , A ):
47
+ right_even = right_odd = 0
48
+ for i in range (len (A )):
49
+ if i % 2 == 0 :
50
+ right_odd += A [i ]
51
+ else :
52
+ right_even += A [i ]
53
+
54
+ res = left_odd = left_even = 0
55
+ for i in range (len (A )):
56
+ if i % 2 == 0 :
57
+ right_odd -= A [i ]
58
+ else :
59
+ right_even -= A [i ]
60
+
61
+ if right_odd + left_even == left_odd + right_even :
62
+ res += 1
63
+
64
+ if i % 2 == 0 :
65
+ left_odd += A [i ]
66
+ else :
67
+ left_even += A [i ]
68
+
69
+ return res
You can’t perform that action at this time.
0 commit comments