# Solution to Tape-Equilibrium by codility

16 Jan

Question Name: TapeEquilibrium

The variable of head stores the sum of the heading part of the tape. And the variable of tail stores the sum of tailing part. Then, we move the index from 2nd position to the last 2nd position. Every time we move the index, we adjust both head and tail, compute and compare the difference.

### 75 Replies to “Solution to Tape-Equilibrium by codility”

1. Theo says:

Why is this solution wrong?

• Sheng says:

You should change the last for loop from “for(i=0;i<N;++i)” to “for(i=0;i<N-1;++i)”. Neither the head part nor the tail part could be empty here.
In addition, the if(N==1) is useless. The problem states that N >= 2.

• Gayan says:

I might be stupid here but could some one explain in line 17 why multiply the p by two?
sp=abs(sum-(2*p));

• Sheng says:

sum-(2*p) = sum – p – p = (sum – p) – p, where sum-p is the right part’s sum and p is the left part’s sum.

2. Theo says:

Thank you very much, it worked perfectly ! But why if the tail and the head part must not be counted should not change the for-loop to “for(i=1;i<N-1;++i)" ?
Theodoros (Theo)

• Sheng says:

When i == 0, the head part is A[0], and the tail part is the remaining part A[1] ~ A[N-1]
When i == N-2, the head part is A[0] ~ A[N-2], and the tail part is the last element A[N-1]
My pleasure to see my code be helpful!

3. Tape-Equilibrium by Codility : C Program

• Sheng says:

• Mert says:

Not 100% sure about compiler output, but in case it misbehaves:
last_minimum = (current_min < last_minimum) ? current_min : last_minimum;
will probably execute assignment no matter what..
if(current_min < last_minimum)
{
last_minimum = current_min;
}
will wave the execution of the rest if true

• Mert says:

Let me know if I’m being a dumb *ss lol

• Mert says:

🙁 Missing the last check in that case… But surely there is a way to stick the last check without executing the inner scope a billion times :))

• Sheng says:

Yes, your solution is right and kind of better.
“? :” is simple and clean. But it costs a little bit more time (should be very very little here). IMO, persons sometimes use this kind of “?:” to keep the code short.
BTW, thanks for your awesome discussion!

• Alex says:

last_minimum = abs(totalSum-A[0]-A[0]);
what does that mean?

• Sheng says:

totalSum-A[0] is the sum of the tail.
A[0] is the sum of the head
So last_minimum = abs(totalSum-A[0]-A[0]); is the difference between head and tail.

• Tai Vo says:

I think the first assigned value for last_minimal should be abs(A[0] – totalSum + A[0])

4. John Bryan says:

I keep getting 91% on this and I can’t figure out why:

It says that I’m getting the wrong answer on small elements. “Got 0 Expected 20”.
Any idea why?

• Sheng says:

My experience is, you would better to print out that test case, and debug according to that data.
Please do give us an update message, after you try to debug and fix it.
PS: what is the programming language? JavaScript?

• John Bryan says:

Yeah I used JavaScript. The problem is that they don’t give the specific test case that it’s failing. On the list that shows scores for correctness tests, it is labeled Small with a subheading of small elements. It says that it got 0 and was expecting 20.
I wish I simply knew what the test case was but it doesn’t say what data it is using. I was hoping someone would be able to see some obvious problem with this.

• Sheng says:

B gave the right fix. But for your information, as Codility says:
you can use console.log for debugging purposes, i.e. console.log(‘this is a debug message’);
So you could use the console.log to output ALL the test cases.

• B says:

in a small set your solution is going to far on line 16. Try something like
for(i = 1; i<len-2; i++){

• Sheng says:

Yeah! This is the right fix. Thank you!!!

5. bobby says:

Hi, could you please verify what’s wrong with this java code? I got 91% in the test.

• Sheng says:

Hello! FIrst of all, you can use “System.out.println(XXXX);” in your submission to show the input content A in the test. So you can debug locally, and find out your bug.
Both head and tail part must be NON-EMPTY. So you need to change

to

• bobby says:

Ah! that was really silly! Thanks anyway! got it now 🙂

• Sheng says:

You are welcome! And enjoy coding!

6. allen says:

Not sure why this is wrong 🙁

• Sheng says:

Line 2-4 can be rewritten as totalSum = sum(A)
I cannot find a good reason to initialize the currMin and maxMin as 1000, which may be the reason for failure.
To debug the submission on codility, please add a line at the very beginning of function as: print A. It will show you the test case. And you can debug locally.

7. Anshul says:

I wrote exactly same code as given in the blog. But after sometime i thought this is the wrong code. This will not give correct result for array which is mix of +ve and -ve numbers
example: int arr[] ={ 5 ,10, 1, -5, 5 , 3 ,4};

• Sheng says:

Why not? The answer for the { 5 ,10, 1, -5, 5 , 3 ,4} is 1 as the two parts are:
[5, 10, 1, -5] and [5, 3, 4].

8. Why loop on an index ? That is neither pythonic nor necessary.

P.S. Sorry, I can’t find how to format the code properly

• Sheng says:

I agree with you. Your solution is more pythonic. While mine is probably more readable to the non-Pythoner.

9. durm says:

Nice!

• Sheng says:

Kind of. Anyway, enjoy it!

10. calinutz says:

And the Pascal solution (100%)

• calinutz says:

there should be an edit-post in case there is something wrong with my formatting and I see it after posting. For example the “less than” sign… if I add it as “the sign” then it cuts all my following text, if I replace it with &lt then it is displayed exactly like that (less than). I am not too good with manually formatting code but it should not be that difficult… 🙁
Please correct my code and make it look like it should

• Sheng says:

You do not need to escape the (less than) token, as long as you include it in the pre or code block.

11. Leo says:

Here is a nice C++ solution for TapeEquilibrium from codility, which makes use of iterators. The solution will score you 100% on both correctness and performance. Have fun using it.

12. Jovan Damjanovic says:

Here’s my Java solution, for 100% on both correctness and performance. Didn’t find one here yet so I thought might as well post 🙂

• Sheng says:

Thanks 🙂

• Paulo says:

100% both:
PS: code was removed by admin.

• Sheng says:

Thanks very much for sharing! However, I cannot run your code on codility. And it does not follow the comment rules. Please read the comment guildline before posting.

13. Juaning says:

Got 100% solution

14. Paulo says:

• Sheng says:

Please post the full code with function signature. Thanks!

15. #test the method
A= [3,1,2,4,3]
print solution(A)
#Not sure why performance is 0% here. Detected O(N*N)?

• Sheng says:

Because sum(A[0:e+1]) is O(N).

• Sheng says:

Your other solution is incomplete. And I removed them.
If you want to post any comment, please read the guideline firstly on the right column.
In addition, if you have any bug question, stackoverflow might be a better place to ask. Thanks!

16. Ernesto Cabrera says:

Hi All,
I hope you like it,
erncab

———————————————————-
Hi All,
After some thoughts I implemented a second solution (100/100) https://codility.com/demo/results/demoR47NP2-Q5B/

which looks simpler than the previous one I implemented above https://codility.com/demo/results/demo7WFVZK-MP6/ (83/91)
Thanks in advance for any suggestions to improve it even further,
erncab

• Sheng says:

Thanks for your visiting and discussion!

17. alex says:

My solution

18. Michael Dalziel says:

=== Ruby ===

19. Rails says:

I didn’t see a solution like mine so sharing. It uses just one loop for calculating sum and min diff. It scored 100/100. As is often said thanks so much for this very helpful forum!

• Sheng says:

You are welcome! And enjoy coding!

20. zoc says:

Why is my

incorrect, but my

isn’t (apart from being O(N*N))? I can’t figure it out for the life of mine. Anyone?

• Sheng says:

I cannot see any difference between solution() and slow_solution(). I tried both, and both solutions got 100/100.

21. manu says:

Isn’t using a function like sum() kind of a cheat if you want to reach O(n) time complexity. It seems like a lower level way to achieve this would be to first make the total sum of the array using some kind of iteration but that would yield a O(2N) complexity no ?

• Sheng says:

Big O is used to measure the order of complexity, rather than the exact complexity. O(2N) is exactly the same as O(N).

22. Alex says:

My c# solution. 100% ok.
https://codility.com/demo/results/demo742QXH-MV7/

23. Hi, thank you for share your solution. I got 100% in correctnes but 0% in performance. I think that my problem was execute a slice twice in each loop iteration, looks:

What do you think that was my problem?

• Sheng says:

It’s because of the sum(). sum() takes O(N) complexity. Therefore the total time complexity of your solution is O(N^2).

24. Aram hmd says:

Hi Sheng,
Thank you for your help. i am fairly new to programming. I just don’t understand why instead of the index, the result is min? I thought the result should be the index that abs(head – tail) = 0 happens and that index would be the result. would you please kindly explain it ?
Thanks,
Aram

• Sheng says:

Hello Aram, it’s nothing about programming. The problem says: returns the minimal difference that can be achieved. The return value is not the index.

25. PHP solution 100%:

26. Hugo Beltran says:

I got this 100% on JavaScript (With a little help of reduce).

27. Maicon Matsubara says:

My C# version..

28. John Kowalsky says:

You can use:

29. Mustafa Ates says:

I got this 100% on Java

30. wan-kim says:

My Java solution 100%

31. Thanks for sharing your solution, it helped a lot. My solution is slightly different, with a small optimization:

Explanation: you don’t need to test every index in the array, going up to the middle element is enough because after it, you’re just swapping the right and the left elements. And abs(left – right) is the same as abs(right – left).

32. Mbugs says:

Why is this recursive solution slow?

33. Solution in overly bulky but comprehensible VB.

34. Mustafa Kirimli says:

https://app.codility.com/demo/results/trainingN2FUQA-EV7/

35. Amit Dhawan says:

My Codility Java 100% success solution:

36. Jay Bariya says:

My solution in Python. Detected time complexity O(N). 100%. The basic idea is to slice the list A at index i. Take the absolute value of subtraction of the sum of two sliced list A[:i] and A[i:]. Then return the minimum value. Instead of slicing and using for loop which makes time complexity O(N*N), a mathematical simplification of the form sum(A) – 2*sum(elements up to index i). Sum(A) is constant, whereas using just a for loop for 2*sum(elements up to index) leads to a time complexity of just O(N).