Prefix cabinet: Boss receipt
Stuck or curious how this works? Visualize Binary Heap Operations ↗
Inputs
words is a list of words.
Your tasks
- Create a list
prefixTotals. A prefix is the start of a word. For example, "c", "ca", and "cat" are the prefixes with at least one letter of "cat". For each word inwords, look at all its prefixes with at least one letter. Count how many inputwordsstart with each prefix, then add those counts. Count repeated inputwordsseparately, and include the word itself. Put one total per word inprefixTotals, in input order. - Multiply each number in
prefixTotalsby its position, counting from 1: the first number by 1, the second by 2, and so on. - Add those products. Store the sum in
weightedTotal. - Complete
prefixCabinetBossReceiptso it returnsweightedTotal. Return it, do not print it.
Example
If words is ["tray", "tray", "trf", "lever"], then prefixTotals is [10, 10, 7, 5] and prefixCabinetBossReceipt returns 71.
Rules
- If
prefixTotalsis empty, return 0.
Test data
TEST DATA 1: words is ["ink", "inker", "inow", "typebar"].
TEST DATA 2: words is ["binder", "binder", "bindey"].
Examples
Input: words = ["ink","inker","inow","typebar"] Output: 80
prefixTotals is [8, 10, 8, 7]. Multiply by positions that start at 1: 1 * (8) + 2 * (10) + 3 * (8) + 4 * (7) = 80. Return 80.
Input: words = ["binder","binder","bindey"] Output: 99
prefixTotals is [17, 17, 16]. Multiply by positions that start at 1: 1 * (17) + 2 * (17) + 3 * (16) = 99. Return 99.
Input: words = [] Output: 0
prefixTotals is []. There are no numbers to multiply or add, so return 0.
Input limits
- 0 <= input size <= 64.
- Answers fit in a signed 32-bit integer: -2,147,483,648 through 2,147,483,647.
- There are at most 64 lowercase English words, each with 1 to 12 letters.
Efficiency goal
Big-O describes how the work or memory needed grows as the input gets larger.
Efficiency goal: time O(total characters); extra memory, including the helper list, O(n). n is the input length; total characters means all word lengths added together. These labels describe how work and memory grow with the input.
Practice focus
Build prefixTotals first, then return exactly what the tasks ask for. Follow the order, keep repeated values when the rule says so, and check the empty case.