How to identify the bug:
Run it manually (in your head or with pen and paper)
Add prints which explain what's done step by step and check that output.
Get a very clear idea of how your code should be behaving and why that is a correct solution. Compare this understanding with your code.
Avoiding the situation:
Using better names would help you out, you should be able to read a line without having to read 3 other lines to figure out what the current one does. Name variables after what they represent. What is a "ti"? It's nonsense, so how do you reason about that? Well, you can't, rename it.
Comments can also help you. Write out the logic as comments, reading the comments on their own should be enough to understand what's done, and the code can then be compared to the comments. The comments should not be technical, more like if you were describing how a human would do the same thing.
Sometimes we can avoid indexes altogether which makes the program easier to reason about.
Perhaps you can do it in a completely different way, consider how you would phrase the solution in plain English, maybe there's a cleaner way to phrase it.