easy +8 pts

Decode base64 string

Decode a base64 encoded string back to its original UTF-8 text, implementing the algorithm manually.

Write a function `decode_base64(data: str) -> str` that takes a base64 encoded string and returns the decoded string. The input is always a valid base64 string (possibly with padding). You must decode it as UTF-8 text. Do NOT use the built-in `base64` module or any third-party libraries. Implement the decoding algorithm manually using the base64 alphabet. Base64 alphabet: `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/` Decoding steps: for each group of 4 characters (after ignoring any '=' padding), convert each character to its 6-bit value (0-63) using the alphabet. Concatenate the 6-bit values into a buffer. Then split the buffer into 8-bit bytes to get the original bytes. The number of '=' characters indicates how many bytes are omitted from the final group: one '=' means the last group has only 2 bytes, two '=' means only 1 byte. Finally, decode the bytes as UTF-8. You may assume the input string length is a multiple of 4 (including padding) and contains only valid base64 characters, with up to two '=' at the end. The decoded output is guaranteed valid UTF-8.

Constraints

Input length is between 0 and 10,000 characters (if non-empty, a multiple of 4). The decoded output is valid UTF-8. Complexity should be O(n) where n is the length of the input.

Example

>>> decode_base64('SGVsbG8=')
'Hello'
>>> decode_base64('V29ybGQ=')
'World'
>>> decode_base64('')
''
>>> decode_base64('SGVsbG8sIFdvcmxkIQ==')
'Hello, World!'
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Create a dictionary mapping each base64 character to its 6-bit value (0-63).
Process groups of 4 characters. For each group, calculate the combined 24-bit integer by shifting and ORing the 6-bit values.
Extract bytes from the 24-bit integer using bit shifts. Use the number of '=' characters in the group to know how many bytes to output.
Handle the empty string case separately and return ''.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.