Problem Description: 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.
For example:
Let's say you are given the array {1,2,3,4,3,2,1}:
Your function will return the index 3, because at the 3rd position of the array, the sum of left side of the index
({1,2,3}) and the sum of the right side of the index ({3,2,1}) both equal 6.
Let's look at another one.
You are given the array {1,100,50,-51,1,1}:
Your function will return the index 1, because at the 1st position of the array, the sum of left side of the index
({1}) and the sum of the right side of the index ({50,-51,1,1}) both equal 1.
Note: Please remember that in most programming/scripting languages the index of an array starts at 0.
Input:
An integer array of length 0 < arr < 1000. The numbers in the array can be any integer positive or negaive.
Output:
The index N such as the side to the left of N is equal to the side to the right of N. If you do not find an index
that fits these rules, then you will return -1.
Level:6kyu
Link To Kata: Equal Sides Of An Array
Another level 6 Kata. I believe I'm making progress. Here we need to find an index in an array where the sum of elements to the left of index is equal to sum of elements to the right of that index. If such an index is not possible then we return a value of -1.
We start solving this array by initializing an index variable to 1 and an answer variable to -1.
We loop through every element in the array and for every looping index we initialize two variables sum1 and sum2 to 0. We loop from the starting of array to just before the looping index and also from the element at index just after the index to the end of the array. In both cases we store the sum of elements in sum1 and sum2. We check if both these values are same and if they are then we change the value of answer to the index of the loop and break out of the loop. Otherwise we keep increasing the looping index.
In the end we return the value of answer variable as the solution to this Kata.
Please go through the code for a better understanding.
Here is a link to the code: Kata Day 39
Please mention your suggestions or your doubts in the comment below.
Happy coding. :)
No comments:
Post a Comment