Search code examples
phpmysqlalgorithmtrie

How can I efficiently check if a promotional code is valid?


A component of a website I'm building requires a user to enter a unique code in a form which is then verified as being a valid code by comparing it against a predetermined list of several million generated codes. How can I do this to provide instant feedback to the user?

Originally I was planning to check all of the submissions in a batch job overnight, but the client would like users to be informed whether they have a valid code immediately.

Is it more efficient to build a trie structure, store the generated codes in a database table, or use some other approach?


Solution

  • Using a MySQL table for this purpose is absolutely the right thing to do. MySQL has no problem looking up an entry in a few milliseconds from a multi-million-row table if you index it correctly. In fact, a MySQL table index is pretty close to a pre-programmed trie structure, with all the hard work, concurrency, edge cases, and debugging done for you.

    If you build some other kind of lookup system, you'll have to sort out such things as persistence, maintenance of the data, and all.