Find index if values in single array on either side are equal when summed

Viewed 124

I have a whiteboard question that I think is way beyond my skill and so don't even know how to approach this.

I want to iterate through each value and sum the elements on left/right side and if they're equal return the index value.

So:

[1, 2, 3, 4, 3, 2, 1]; // return 3

The official question:

You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1.

Is anyone kind enough to help me out? I've looked at array_map() and array_filter() and while helpful I can't think of how to traverse back and forth between the current index when iterating the array.

1 Answers

This can be done with a simple for loop over the full range of an array combined with array_slice and array_sum.

function doSomething(array $data): int {
    for ($i = 0, $count = count($data); $i < $count; $i++) {
        $left = $i > 0 ? array_slice($data, 0, $i) : [ $data[0] ];
        $right = $i > 0 ? array_slice($data, $i + 1) : $data;
    
        $left_result = array_sum($left);
        $right_result = array_sum($right);
    
        if ($left_result === $right_result) {
            return $i;
        }
    }

    return -1;
}

This small piece of code loops over the whole array and sums up the left and the right of the current position of the array. The results will be compared and if the results are the same, the key of the array will be returned.

For huge arrays you can try to reduce memory consumption by using a yield or an Iterator instance.

Related