Optimized space handling

Removed an un-neccesary loop and the space consuming buffer arrays.

Improved the running time to O(n)