Decode URL-Safe Base64 Tokens Without a Library
Last updated: November 29, 2026
Quick Overview
Implement a decoder for URL-safe base64 (alphabet A-Z, a-z, 0-9, -, _) as used in web tokens, accepting input with or without = padding, and rejecting invalid characters, impossible lengths, and non-canonical trailing bits.
0
0
0 solved
Implement a decoder for URL-safe base64 (alphabet A-Z, a-z, 0-9, -, _) as used in web tokens, accepting input with or without = padding, and rejecting invalid characters, impossible lengths, and non-canonical trailing bits.
Google sign-in and many Google APIs pass URL-safe base64 in tokens and page cursors, so a screen may ask you to decode it by hand. The interviewer is testing bit manipulation, the length rules for unpadded input, and whether you think about strictness as a security property.
What the Interviewer Expects
- Builds a character-to-value table for the URL-safe alphabet
- Groups input into 4-character blocks of 24 bits and emits 3 bytes each
- Handles final blocks of 2 or 3 characters and rejects a lone final character
- Checks that unused low bits are zero so each byte string has one encoding
- Tests by round-tripping random bytes against a reference encoder
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
- Write the encoder and make it streaming over a large file.
- Why does accepting non-canonical encodings matter for signed tokens?
- How would you vectorize decoding for throughput?
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: a string over
A-Z a-z 0-9 - _, optionally ending in=padding. - Output: the decoded bytes.
- Errors: characters outside the alphabet (including
+and/from standard base64), a lengt...
High-Level Design
Each character carries 6 bits, so four characters form 24 bits, which is three bytes. Strip padding, then process blocks of up to four characters, shifting each value into an integer. A full block yie...