fixed from O(n) to O(1) to build the f