|
2 | 2 | Find the Equilibrium Index of an Array.
|
3 | 3 | Reference: https://www.geeksforgeeks.org/equilibrium-index-of-an-array/
|
4 | 4 |
|
5 |
| -Python doctests can be run with the following command: |
| 5 | +Python doctest can be run with the following command: |
6 | 6 | python -m doctest -v equilibrium_index.py
|
7 | 7 |
|
8 | 8 | Given a sequence arr[] of size n, this function returns
|
|
20 | 20 | """
|
21 | 21 |
|
22 | 22 |
|
23 |
| -def equilibrium_index(arr: list[int], size: int) -> int: |
| 23 | +def equilibrium_index(arr: list[int]) -> int: |
24 | 24 | """
|
25 | 25 | Find the equilibrium index of an array.
|
26 | 26 |
|
27 | 27 | Args:
|
28 |
| - arr : The input array of integers. |
29 |
| - size : The size of the array. |
| 28 | + arr (list[int]): The input array of integers. |
30 | 29 |
|
31 | 30 | Returns:
|
32 | 31 | int: The equilibrium index or -1 if no equilibrium index exists.
|
33 | 32 |
|
34 | 33 | Examples:
|
35 |
| - >>> equilibrium_index([-7, 1, 5, 2, -4, 3, 0], 7) |
| 34 | + >>> equilibrium_index([-7, 1, 5, 2, -4, 3, 0]) |
36 | 35 | 3
|
37 |
| - >>> equilibrium_index([1, 2, 3, 4, 5], 5) |
| 36 | + >>> equilibrium_index([1, 2, 3, 4, 5]) |
38 | 37 | -1
|
39 |
| - >>> equilibrium_index([1, 1, 1, 1, 1], 5) |
| 38 | + >>> equilibrium_index([1, 1, 1, 1, 1]) |
40 | 39 | 2
|
41 |
| - >>> equilibrium_index([2, 4, 6, 8, 10, 3], 6) |
| 40 | + >>> equilibrium_index([2, 4, 6, 8, 10, 3]) |
42 | 41 | -1
|
43 | 42 | """
|
44 | 43 | total_sum = sum(arr)
|
45 | 44 | left_sum = 0
|
46 | 45 |
|
47 |
| - for i in range(size): |
48 |
| - total_sum -= arr[i] |
| 46 | + for i, value in enumerate(arr): |
| 47 | + total_sum -= value |
49 | 48 | if left_sum == total_sum:
|
50 | 49 | return i
|
51 |
| - left_sum += arr[i] |
| 50 | + left_sum += value |
52 | 51 |
|
53 | 52 | return -1
|
54 | 53 |
|
|
0 commit comments