You are given a 16-digit credit card number. Mask the first 12 digits and display only the last four digits. If the input contains any non-numeric characters, treat it as invalid.
💡 Model Answer
To solve this problem, first validate that the input string is exactly 16 characters long and consists only of digits. If validation fails, return an error or an empty string. For a valid input, iterate over the string and replace the first 12 characters with a masking character such as ''. The last four characters should remain unchanged. In many languages, you can achieve this with string slicing: masked = '' 12 + card[-4:]. This approach runs in O(n) time, where n is the length of the string (constant 16 in this case), and uses O(1) additional space. If you need to support variable-length inputs, you can generalize by masking all but the last four characters: masked = '' * (len(card)-4) + card[-4:]. The key points are input validation, correct masking, and efficient string manipulation.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500