Validate Card Numbers With the Luhn Checksum and Detect the Brand
Last updated: November 29, 2026
Quick Overview
Given a card number string that may contain spaces or dashes, return whether it passes the Luhn checksum, which card brand its prefix and length indicate (Visa, Mastercard, American Express, Discover or unknown), and its last four digits.
Stripe
November 29, 20260
0
0 solved
Given a card number string that may contain spaces or dashes, return whether it passes the Luhn checksum, which card brand its prefix and length indicate (Visa, Mastercard, American Express, Discover or unknown), and its last four digits.
Stripe Elements validates card numbers client-side before any network call, and the same checks back up server-side validation. The interviewer uses this as a warm-up to see careful digit arithmetic, table-driven rules instead of a tangle of if statements, and good input hygiene.
What the Interviewer Expects
- Normalize input by removing spaces and dashes, then reject any other non-digit
- Implement Luhn by doubling every second digit from the right and subtracting 9 when over 9
- Express brand rules as data: prefix ranges plus allowed lengths
- Check longer, more specific prefixes in a way that cannot be shadowed by shorter ones
- Never log or return the full number; expose only the last four digits
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you add a new brand or a co-badged card without code changes?
- Why is a Luhn pass not proof that a card is real or usable?
- How would you format the number as the user types (4-4-4-4 versus 4-6-5 for Amex)?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Output (is_valid, brand, last4). A number is valid only if it is all digits after normalization, has a length the detected brand allows and passes Luhn. Brand rules: Visa starts with 4 (lengths 13, ...
High-Level Design
Each rule is (low, high, prefix_length, brand, lengths). Detecting the brand takes the first prefix_length digits as an integer and checks the range, so 2221 to 2720 is one rule instead of 500. Lu...