Skip to content
Advertisement

Trying to find element in an array from which the sum of elements on the left side is equal to elements on the right. Could you optimise my approach?

def balancedSums(arr):
    n = len(arr)
    for i in range(0, n):
        lsum = sum(arr[0 : i])
        rsum = sum(arr[i + 1 : n])
        if lsum == rsum:
            return "YES"
    return "NO"

I am getting all test cases but two, failing due to timeout. What are my options?

Advertisement

Answer

You can do something like that:

def balancedSums(arr):
    lsum = 0
    rsum = sum(arr)
    n = len(arr)
    for i in range(0, n):
        rsum -= arr[i]
        if lsum == rsum:
            return "YES"
        lsum += arr[i]
    return "NO"

The time-complexity of this is O(n)

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement