|
1 | 1 | """ |
2 | 2 | Find the Equilibrium Index of an Array. |
3 | | -Reference: https://www.geeksforgeeks.org/equilibrium-index-of-an-array/ |
4 | 3 |
|
5 | | -Python doctest can be run with the following command: |
6 | | -python -m doctest -v equilibrium_index_in_array.py |
7 | | -
|
8 | | -Given a sequence arr[] of size n, this function returns |
9 | | -an equilibrium index (if any) or -1 if no equilibrium index exists. |
10 | | -
|
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. |
| 4 | +Reference: |
| 5 | +https://www.geeksforgeeks.org/equilibrium-index-of-an-array |
13 | 6 |
|
| 7 | +Python doctest can be run with: |
14 | 8 |
|
| 9 | +python -m doctest -v equilibrium_index_in_array.py |
15 | 10 |
|
16 | | -Example Input: |
17 | | -arr = [-7, 1, 5, 2, -4, 3, 0] |
18 | | -Output: 3 |
| 11 | +Given an array arr of size n, return an equilibrium index |
| 12 | +if one exists; otherwise return -1. |
19 | 13 |
|
| 14 | +An equilibrium index is an index where the sum of all |
| 15 | +elements to the left equals the sum of all elements |
| 16 | +to the right. |
20 | 17 | """ |
21 | 18 |
|
22 | 19 |
|
23 | 20 | def equilibrium_index(arr: list[int]) -> int: |
24 | 21 | """ |
25 | | - Find the equilibrium index of an array. |
26 | | -
|
| 22 | + Find the first equilibrium index of an array. |
27 | 23 | Args: |
28 | | - arr (list[int]): The input array of integers. |
29 | | -
|
| 24 | + arr: The input array of integers. |
30 | 25 | Returns: |
31 | | - int: The equilibrium index or -1 if no equilibrium index exists. |
32 | | -
|
| 26 | + The first equilibrium index, or -1 if none exists. |
33 | 27 | Examples: |
| 28 | + >>> equilibrium_index([]) |
| 29 | + -1 |
| 30 | + >>> equilibrium_index([5]) |
| 31 | + 0 |
34 | 32 | >>> equilibrium_index([-7, 1, 5, 2, -4, 3, 0]) |
35 | 33 | 3 |
| 34 | + >>> equilibrium_index([2, 4, 6, 8, 10, 3]) |
| 35 | + -1 |
36 | 36 | >>> equilibrium_index([1, 2, 3, 4, 5]) |
37 | 37 | -1 |
38 | 38 | >>> equilibrium_index([1, 1, 1, 1, 1]) |
39 | 39 | 2 |
40 | | - >>> equilibrium_index([2, 4, 6, 8, 10, 3]) |
41 | | - -1 |
| 40 | + >>> equilibrium_index([0, 0, 0]) |
| 41 | + 0 |
| 42 | + >>> equilibrium_index([-1, -1, -1]) |
| 43 | + 1 |
| 44 | + >>> equilibrium_index([1, -1, 0]) |
| 45 | + 2 |
| 46 | +
|
| 47 | + Time Complexity: |
| 48 | + O(n), where n is the length of the array. |
| 49 | +
|
| 50 | + Space Complexity: |
| 51 | + O(1), using only constant extra space. |
42 | 52 | """ |
43 | 53 | total_sum = sum(arr) |
44 | 54 | left_sum = 0 |
45 | | - |
46 | 55 | for i, value in enumerate(arr): |
47 | 56 | total_sum -= value |
48 | 57 | if left_sum == total_sum: |
49 | 58 | return i |
50 | 59 | left_sum += value |
51 | | - |
52 | 60 | return -1 |
53 | 61 |
|
54 | 62 |
|
|
0 commit comments