solution runs in O(n) time where n is the number of characters in the document.