Filter Valid Credit Card Numbers
StringsAuto-graded · 21 test casesLast 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:
- Length and Character Composition: The stripped string must consist of exactly 16 characters, and every character must be a decimal digit (
'0'through'9'). - Prefix: The first digit of the stripped string must be either
'4'or'5'. - 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
numbersis 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To solve this problem, we process each entry in the input list sequentially and verify all validation rules step by step:
- Type & Cleanup: Ensure the item is a string, then remove all space characters using
replace(' ', ''). - Length & Digits Guard: Check if the cleaned string has a length of exactly 16 and consists purely of numeric digits (
isdigit()). This prevents runtime exceptions when converting characters to integers later. - Prefix Guard: Confirm that the first character
number[0]is either'4'or'5'. - Luhn Checksum: Validate the string against the Luhn algorithm:
- Reverse the digit string or iterate backwards.
- For positions with odd 0-based indices from the right end (1st position from right is index 0, 2nd is index 1, etc.), double the digit.
- If the doubled value exceeds 9, subtract 9.
- Sum up all processed values and check if
total % 10 == 0.
- If all checks pass, append the original raw string to the result list.
Complexity Analysis
- Time Complexity: $\mathcal{O}(N \times L)$, where $N$ is the number of elements in
numbersand $L$ is the max length of a string (bounded at 100). For each 16-character string, all operations run in $\mathcal{O}(1)$ time. Thus, the total time complexity scales linearly with the input size. - Space Complexity: $\mathcal{O}(N)$ to store the filtered output list of valid card strings.
from typing import List
def luhn_ok(number: str) -> bool:
total = 0
# Process digits from right to left
for i, ch in enumerate(reversed(number)):
d = int(ch)
if i % 2 == 1: # Every second digit from the right
d *= 2
if d > 9:
d -= 9
total += d
return total % 10 == 0
def filter_cards(numbers: List[str]) -> List[str]:
result = []
for raw in numbers:
if not isinstance(raw, str):
continue
number = raw.replace(' ', '')
if len(number) != 16 or not number.isdigit():
continue
if number[0] not in ('4', '5'):
continue
if not luhn_ok(number):
continue
result.append(raw)
return result