BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Tokenization and NLP30 of 38 in topic

762. Encode a list of strings into one string and decode it back

EasyTokenization and NLP

Sending a batch of prompts over a channel that only carries one string, or writing them to one file field, needs a reversible encoding. Picking a separator character fails as soon as some string contains that character.

Write two functions. encode(strings) takes a list of strings and returns a single string. decode(s) takes a string produced by encode and returns the original list exactly. Strings may contain any characters, including digits, '#', ':', commas, newlines and nothing at all (the empty string). Do not use json, pickle, repr or eval.

Functiondef encode(strings)

Example 1

Input: decode(encode(['hello', 'wor:ld']))

Output: ['hello', 'wor:ld']

Example 2

Input: decode(encode([]))

Output: [] and decode(encode([''])) returns ['']

Example 3

Input: decode(encode(['3:abc', '', '12', '\n', '#,#', ':::']))

Output: ['3:abc', '', '12', '\n', '#,#', ':::']

Constraints

  • At most 10,000 strings.
  • Total length at most 1,000,000 characters.
Hint 1

Prefix each string with its length.

Hint 2

Use a delimiter only to end the length digits.

Hint 3

Slice by length when decoding instead of searching for the next delimiter.

Common mistakes
  • Joining with a separator such as ',' that can appear inside a string.
  • Losing empty strings or confusing [] with [''].
  • Searching for the delimiter inside the content while decoding.
Understand the idea

Framing is the problem of marking where one message ends and the next begins. Separators need escaping; length prefixes do not. The same idea appears in network protocols, record files and tokenizer vocab files.

Topics
Tokenization and NLP
Similar questions
  • Score words by TF-IDFEasy
  • Encode text with a byte fallback so no character is ever unknownEasy
  • Normalize text by lowercasing, stripping accents and collapsing spacesEasy
  • Count word n-grams and return the k most frequent with stable tiesEasy
All Tokenization and NLP problems
Report
762 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
9
def encode(strings):
# return one string
pass
​
​
def decode(s):
# return the original list
pass
​
decode(encode(['hello', 'wor:ld']))

This case uses generated data, so it runs as written. Press + to add your own case.

Run checks these cases in your browser, no sign-in needed. Submit checks all 6 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS