A chat app wants to estimate how small a message log could get with the best prefix-free binary code: every distinct character gets a code of 0s and 1s, no code is the start of another code, and common characters can get shorter codes.
Write encodedBits(text) that returns the fewest total bits needed to encode text with such a code (the sum, over every character in text, of its code length). Many codes can tie for best, but they all give the same total. If text has only one distinct character, it still needs a 1-bit code, so the answer is text.length. An empty text needs 0 bits.
Input: text = "aaabbc" Output: 9
Codes a = 0, b = 10, c = 11 give 3 * 1 + 2 * 2 + 1 * 2 = 9 bits.
Input: text = "abcd" Output: 8
Four characters seen once each get 2-bit codes: 4 * 2 = 8.
0 <= text.length <= 100000text contains printable ASCII characters.Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.
Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).
I'm here to help with #600 Bits to Encode a Chat Log. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.