Interview conceptCoding & Algorithms

Luhn Card Validation And Inference

Asked of: Software Engineer

Last updated

What's being tested

These problems test implementing the Luhn checksum, identifying card brands with ordered pattern matching, and handling wildcard strings without mixing validation rules. You must also reason about combinatorial completion counts and efficient single-digit correction, with clear complexity and edge-case choices.

Patterns & templates

  • Luhn validation — scan digits right-to-left, double alternating digits, subtract 9 when needed; valid when total % 10 == 0.

  • Normalize input deliberately: reject or strip separators according to the contract, then reject empty strings, nondigits, and unsupported lengths.

  • Separate identifyBrand, isValid, countCompletions, and recover so brand-pattern logic does not contaminate checksum code.

  • Use ordered brand predicates for overlapping prefixes; return UNKNOWN when no brand matches rather than guessing from Luhn validity.

  • For wildcards, enumerate only when bounded; otherwise use dynamic programming over positions and checksum residue in O(n * 10 * 10) time.

  • For one-error recovery, try each candidate digit or allowed edit, validate the result, and deduplicate; straightforward search is O(n * 10).

  • Preserve the original string’s positions and parity: inserting or deleting digits changes which positions Luhn doubles, a common off-by-one bug.

Common pitfalls

Pitfall: Doubling from the left instead of the right, or treating the check digit as doubled, produces consistently incorrect validations.

Pitfall: Assuming every syntactically plausible number belongs to a known network; enforce exact lengths and prefixes before returning a brand.

Pitfall: Counting wildcard assignments without filtering brand constraints, fixed digits, length, and duplicate recovered candidates.

Practice these

The practice cards below cover the canonical variants — solve all of them and time yourself.

Practice questions

Related concepts