Validate a Card Number and Detect Its Card Network
Last updated: November 29, 2026
Quick Overview
Write a function that takes a raw card number string, strips spaces and dashes, verifies it with the Luhn checksum, and returns VISA, MASTERCARD, AMEX, DISCOVER, or INVALID based on prefix and length rules.
Onepay
November 29, 20260
0
0 solved
Write a function that takes a raw card number string, strips spaces and dashes, verifies it with the Luhn checksum, and returns VISA, MASTERCARD, AMEX, DISCOVER, or INVALID based on prefix and length rules.
OnePay lets users add external debit cards to fund their account and pay in the wallet, so client-side card validation is a natural assessment task. The grader looks for a correct Luhn implementation, careful prefix ranges (including the Mastercard 2-series), and input cleaning that never trusts the raw string.
What the Interviewer Expects
- Normalize input by removing spaces and dashes and reject other characters
- Implement Luhn by doubling every second digit from the right
- Check both prefix and length per network
- Handle the Mastercard 2221 to 2720 range correctly
- Explain that client validation is a UX aid, not a security control
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 show the network logo as the user types, before the number is complete?
- Why should the server still validate, and what does it check that the client cannot?
- How would you format the input field (4-4-4-4 versus 4-6-5 for Amex) without breaking cursor position?
- How do you keep full card numbers out of client logs and analytics events?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input is whatever the user typed. Output is the network name or INVALID. Rules: Visa starts with 4 and is 13, 16, or 19 digits; Mastercard is 51 to 55 or 2221 to 2720 with 16 digits; Amex is 34 or 37 ...
High-Level Design
Normalize, reject non-digits, run Luhn, then test network rules in order. Network rules are data-like, so in a real codebase I would put them in a table of (name, prefix ranges, lengths) so a new netw...