medium +20 pts

Base64 Encode/Decode

Implement RFC 4648 Base64 encoding and decoding without the standard library.

Implement two functions: 1. `encode_base64(s: str) -> str` — takes a Python string `s` (ASCII/UTF-8) and returns the Base64-encoded string as per RFC 4648 with standard alphabet `A-Za-z0-9+/` and padding with `=`. Encode the input string to bytes using UTF-8 before encoding to Base64. The output must include padding so the length is a multiple of 4. 2. `decode_base64(b64: str) -> str` — takes a valid Base64 string (standard alphabet, with or without padding) and returns the decoded original string. The input will always be valid, well-formed Base64 (non-alphabet characters are only `=` at the end). The function should convert the Base64 back to bytes and decode using UTF-8, returning the string. You must implement the encoding/decoding algorithm yourself without using the built-in `base64` module. You may use `ord`, `chr`, `int`, string operations, etc. Edge cases include empty string input and inputs whose length is not a multiple of 3 (for encoding) or not a multiple of 4 (for decoding, handle padding and unpadded inputs correctly). **Function Signatures:** ```python def encode_base64(s: str) -> str: def decode_base64(b64: str) -> str: ```

Constraints

- Input `s` for `encode_base64` is a string (ASCII). Length 0 ≤ |s| ≤ 1000. - Input `b64` for `decode_base64` is a valid Base64 string (standard alphabet, optional padding). Length 0 ≤ |b64| ≤ 2000. - Time complexity: O(n) for both functions, where n is the input length.

Example

>>> encode_base64("")
''
>>> encode_base64("Hello, World!")
'SGVsbG8sIFdvcmxkIQ=='
>>> decode_base64("SGVsbG8sIFdvcmxkIQ==")
'Hello, World!'
>>> decode_base64("SGVsbG8sIFdvcmxkIQ")
'Hello, World!'
>>> encode_base64("a")
'YQ=='
>>> decode_base64("YQ==")
'a'
20 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Group 3 bytes (24 bits) into 4 6-bit groups. Map each 6-bit value to a character using the Base64 alphabet.
If the input length is not a multiple of 3, pad with '=' characters: one for 1 remaining byte, two for 2 remaining bytes.
For decoding, use a lookup dict from character to index. Convert groups of 4 characters back to 3 bytes, but be careful with the last group when padding is present or missing.
Remember to handle empty input for both functions.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.