Skip to content

Commit d18eefa

Browse files
committed
Add edge cases for equilibrium index
1 parent c6012e3 commit d18eefa

1 file changed

Lines changed: 50 additions & 15 deletions

File tree

Lines changed: 50 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,87 @@
1+
12
"""
23
Find the Equilibrium Index of an Array.
3-
Reference: https://www.geeksforgeeks.org/equilibrium-index-of-an-array/
44
5-
Python doctest can be run with the following command:
5+
Reference:
6+
https://www.geeksforgeeks.org/equilibrium-index-of-an-array/
7+
8+
Python doctest can be run with:
9+
610
python -m doctest -v equilibrium_index_in_array.py
711
8-
Given a sequence arr[] of size n, this function returns
9-
an equilibrium index (if any) or -1 if no equilibrium index exists.
12+
Given an array arr of size n, return an equilibrium index
13+
if one exists, otherwise return -1.
1014
11-
The equilibrium index of an array is an index such that the sum of
12-
elements at lower indexes is equal to the sum of elements at higher indexes.
15+
An equilibrium index is an index where the sum of all
16+
elements to the left equals the sum of all elements
17+
to the right.
1318
19+
Examples:
1420
21+
>>> equilibrium_index([-7, 1, 5, 2, -4, 3, 0])
22+
3
1523
16-
Example Input:
17-
arr = [-7, 1, 5, 2, -4, 3, 0]
18-
Output: 3
24+
>>> equilibrium_index([1, 2, 3, 4, 5])
25+
-1
1926
27+
>>> equilibrium_index([1, 1, 1, 1, 1])
28+
2
29+
30+
>>> equilibrium_index([2, 4, 6, 8, 10, 3])
31+
-1
2032
"""
2133

2234

2335
def equilibrium_index(arr: list[int]) -> int:
2436
"""
25-
Find the equilibrium index of an array.
37+
Find the first equilibrium index of an array.
2638
2739
Args:
28-
arr (list[int]): The input array of integers.
40+
arr: The input array of integers.
2941
3042
Returns:
31-
int: The equilibrium index or -1 if no equilibrium index exists.
43+
The first equilibrium index, or -1 if none exists.
3244
3345
Examples:
46+
>>> equilibrium_index([])
47+
-1
48+
49+
>>> equilibrium_index([5])
50+
0
51+
3452
>>> equilibrium_index([-7, 1, 5, 2, -4, 3, 0])
3553
3
54+
3655
>>> equilibrium_index([1, 2, 3, 4, 5])
3756
-1
57+
3858
>>> equilibrium_index([1, 1, 1, 1, 1])
3959
2
40-
>>> equilibrium_index([2, 4, 6, 8, 10, 3])
41-
-1
60+
61+
>>> equilibrium_index([0, 0, 0])
62+
0
63+
64+
>>> equilibrium_index([-1, -1, -1])
65+
1
66+
67+
>>> equilibrium_index([1, -1, 0])
68+
2
69+
70+
Time Complexity:
71+
O(n), where n is the length of the array.
72+
73+
Space Complexity:
74+
O(1), using only constant extra space.
4275
"""
4376
total_sum = sum(arr)
4477
left_sum = 0
4578

4679
for i, value in enumerate(arr):
4780
total_sum -= value
81+
4882
if left_sum == total_sum:
4983
return i
84+
5085
left_sum += value
5186

5287
return -1
@@ -55,4 +90,4 @@ def equilibrium_index(arr: list[int]) -> int:
5590
if __name__ == "__main__":
5691
import doctest
5792

58-
doctest.testmod()
93+
doctest.testmod()

0 commit comments

Comments
 (0)