KatInterview

Filter Valid Credit Card Numbers

StringsAuto-graded · 21 test cases
EasyAuto-gradedStringsstringsarrays

Last updated

Validate a list of card number strings against length, prefix, digit-only, and Luhn checksum requirements.

Given a list of strings representing potential payment card numbers, filter and return a new list containing only the original raw strings that pass all validation criteria. The returned list must preserve the original input order.

A card string is valid if and only if it satisfies all of the following rules after all space characters (' ') are removed from it:

  1. Length and Character Composition: The stripped string must consist of exactly 16 characters, and every character must be a decimal digit ('0' through '9').
  2. Prefix: The first digit of the stripped string must be either '4' or '5'.
  3. Luhn Checksum: The stripped string must pass the standard Luhn algorithm validation:
    • Working from right to left (where the rightmost character is at index position 1 from the right), double the value of every second digit.
    • If doubling a digit produces a value greater than 9, subtract 9 from it (equivalent to summing its individual digits).
    • Add together all resulting values.
    • The card passes if the total sum is evenly divisible by 10 (total % 10 == 0).

Any input element that is not a string, contains non-digit non-space characters, fails the length requirement, starts with an unapproved prefix, or fails the Luhn checksum must be excluded.

Constraints

  • $0 \le \text{len}(numbers) \le 1000$
  • Each element in numbers is a string (or potentially another type in malformed inputs).
  • String lengths are between 0 and 100 characters.

Examples

Example 1

Input: filter_cards(['4111 1111 1111 1111', '4111 1111 1111 1112', '5500 0000 0000 0004', '6011 0000 0000 0004', '4111 1111 1111 116'])

Output: ['4111 1111 1111 1111', '5500 0000 0000 0004']

Hints

Hint 1

Strip all space characters before evaluating any of the validation conditions.

Hint 2

Ensure the stripped string contains exactly 16 characters and consists entirely of digits before attempting to run the Luhn algorithm or checking the prefix.

Hint 3

Pay attention to index parity in the Luhn algorithm: doubling happens on every second digit starting from the right (1-indexed from right), which corresponds to odd distance from the right end.