O(N+Q)