Skip to the code
cf.
+25 XP

#600 Bits to Encode a Chat Log

medium

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.

Example 1

Input: text = "aaabbc"
Output: 9

Codes a = 0, b = 10, c = 11 give 3 * 1 + 2 * 2 + 1 * 2 = 9 bits.

Example 2

Input: text = "abcd"
Output: 8

Four characters seen once each get 2-bit codes: 4 * 2 = 8.

Constraints

  • 0 <= text.length <= 100000
  • text contains printable ASCII characters.
Saved in this browser

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).