|
| 1 | +""" |
| 2 | +Find the Equilibrium Index of an Array. |
| 3 | +Reference: https://www.geeksforgeeks.org/equilibrium-index-of-an-array/ |
| 4 | +
|
| 5 | +Python doctests can be run with the following command: |
| 6 | +python -m doctest -v equilibrium_index.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. |
| 13 | +
|
| 14 | +
|
| 15 | +
|
| 16 | +Example Input: |
| 17 | +arr = [-7, 1, 5, 2, -4, 3, 0] |
| 18 | +Output: 3 |
| 19 | +
|
| 20 | +""" |
| 21 | + |
| 22 | + |
| 23 | +def equilibrium_index(arr: list[int], size: int) -> int: |
| 24 | + """ |
| 25 | + Find the equilibrium index of an array. |
| 26 | +
|
| 27 | + Args: |
| 28 | + arr : The input array of integers. |
| 29 | + size : The size of the array. |
| 30 | +
|
| 31 | + Returns: |
| 32 | + int: The equilibrium index or -1 if no equilibrium index exists. |
| 33 | +
|
| 34 | + Examples: |
| 35 | + >>> equilibrium_index([-7, 1, 5, 2, -4, 3, 0], 7) |
| 36 | + 3 |
| 37 | + >>> equilibrium_index([1, 2, 3, 4, 5], 5) |
| 38 | + -1 |
| 39 | + >>> equilibrium_index([1, 1, 1, 1, 1], 5) |
| 40 | + 2 |
| 41 | + >>> equilibrium_index([2, 4, 6, 8, 10, 3], 6) |
| 42 | + -1 |
| 43 | + """ |
| 44 | + total_sum = sum(arr) |
| 45 | + left_sum = 0 |
| 46 | + |
| 47 | + for i in range(size): |
| 48 | + total_sum -= arr[i] |
| 49 | + if left_sum == total_sum: |
| 50 | + return i |
| 51 | + left_sum += arr[i] |
| 52 | + |
| 53 | + return -1 |
| 54 | + |
| 55 | + |
| 56 | +if __name__ == "__main__": |
| 57 | + import doctest |
| 58 | + |
| 59 | + doctest.testmod() |
0 commit comments