Implementing O(n) algorithm