Who holds the copyright if I did research at one university and write a thesis at another? I worked for a research project on the migration of a prototype to a low-level consumable solution. I am also co-author of a paper that describes the math used for that project (my contribution was not the math, but the tests used to evaluate the performance of the algorithm). According to the work agreement I signed, the copyright of the paper and the code belongs to university A (although it acknowledges the author's attribution).

I am also writing a thesis for an academic program at university B (paying the tuition by myself). The main researcher of university A gave me permission to use the algorithm as the basis of my individual research. I also have some ideas that can improve the overall performance.

If I base my work on the algorithm of university A (which was already published) and write a different implementation (even in a different language), could I still lose ownership of my thesis? (I am trying to avoid any infringement)

PS: the abstract of the paper of university A was accepted and exposed in a conference, but the final document has not been sent yet (as usually done in these kinds of events).
You confuse two different things: The copyright attaches to the written work (in your case the thesis). The intellectual property attaches to the content of the contribution (in your case, the algorithm).

Likely (though I'm not qualified to give legal advice), the copyright for your thesis resides with you and/or university B, whereas the intellectual property in the algorithm resides with university A.