Prefix cabinet: First qualifying slip
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. - Read
prefixTotalsfrom left to right. Find the first number that is at leastkand store that number, not its position, infirstMatch. - Complete
prefixCabinetFirstQualifyingSlipso it returnsfirstMatch. Return it, do not print it.
Example
If words is ["margin", "margin", "mam", "roller"] and k is 6, then prefixTotals is [14, 14, 7, 6] and prefixCabinetFirstQualifyingSlip returns 14.
Rules
- If no number is at least
k, return -1. k(a whole number from 1 to 8) is the threshold in task 2: compare each number with it.
Test data
TEST DATA 1: words is ["folio", "folside", "foir", "tray"] and k is 4.
TEST DATA 2: words is ["slip", "slip", "slie"] and k is 6.
Examples
Input: words = ["folio","folside","foir","tray"] k = 4 Output: 10
prefixTotals is [10, 12, 8, 4]. Here k is 4. The first number at least 4 is 10. Return that value.
Input: words = ["slip","slip","slie"] k = 6 Output: 11
prefixTotals is [11, 11, 10]. Here k is 6. The first number at least 6 is 11. Return that value.
Input: words = [] k = 8 Output: -1
prefixTotals is []. Here k is 8. No number is at least 8, so return -1.
Input limits
- 0 <= input size <= 64.
- k is a whole number from 1 to 8. 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.