Recently I got this problem as one of the questions in an online assessments.
Card numbers are 16 digit numbers like 4444 4444 4444 4444. BIN numbers are first few digits of card numbers like 4444 4444 44. The inputs given initially are card types for the range of BIN numbers. A cache has to be built initially and then given a card number, card type is to be returned, I assume in approximately O(1).
Ex:
Input:
BIN range object = [["4444 4444 11", "4444 4444 44", "Visa credit"], ["4500 0000 55", "4999 9999 00", "Visa debit"], ["4999 9999 99", "5555 0000 00", "Master credit"], ["6666 4444 11", "7777 0000 00", "Amex"]].
CardNumber: 4733 6109 7901 2139
Output: Visa debit
Explanation: BIN for 4733 6109 7901 2139 is 4733 6109 79 which falls between BIN range of visa debit (4500 0000 55 to 4999 9999 00).
BIN range object is an array of array where each internal array, array[0] is start of range, array[1] is end of range and array[2] is card type for that range. Note that different card types need not have continous BIN range - for example: if a cardNumber 6000 0000 0000 0000 is given, it does not belong to any card types and hence null is to be returned.
It was unclear in the question if BIN range given in BIN range object would always be 10 digits or there can BIN range of 9 digits or 12 digits or so on... I assumed it would be fixed to 10 digits and continued to code.
(Many card numbers will be given and respective card type or null is to be returned)
I could relate this to consistent hashing concept where you have a bucket for range of keys. But the trick here is BIN range is not continuous. There may be BIN ranges which do not belong to any of the card. I thought of two ways to tackle this -
Now each time a card number is given, I will have to traverse through the keys in map I have constructed, check the next key or range object depending on the method chosen and return the card type. Time complexity of both the methods would approximately be O(k) where k=number of card types.
I coded the second method and I could clear 6/10 test cases. I was getting invalid outputs for rest of the test cases and NOT TLE, so I assume this solution is somewhat optimal. However, I was not sure why the other test cases were failing :(
But are there any better approaches to this question? Any improvements to this or alternate solutions would be highly helpful to me and to the ones reading this! If there are any ambiguity about the question, do let me know.
Thanks and cheers!!!