use O(n) algorithm