Implement substring search and weighted sampling | Google Interview Question