- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 76 lines of Python from the credited upstream file count-valid-word-occurrences.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import collections5 6 78class Solution(object):9 def countWordOccurrences(self, chunks, queries):10 """11 :type chunks: List[str]12 :type queries: List[str]13 :rtype: List[int]14 """15 def check(i, j):16 return (17 chunks[i][j].islower() or18 (chunks[i][j] == '-' and19 (curr and curr[-1].islower()) and20 ((j+1 < len(chunks[i]) and chunks[i][j+1].islower()) or (j+1 == len(chunks[i]) and i+1 < len(chunks) and chunks[i+1][0].islower()))21 )22 )23 24 curr = []25 cnt = collections.defaultdict(int)26 for i in xrange(len(chunks)):27 for j in xrange(len(chunks[i])):28 if check(i, j):29 curr.append(chunks[i][j])30 continue31 if curr:32 cnt["".join(curr)] += 133 curr = []34 if curr:35 cnt["".join(curr)] += 136 curr = []37 return [cnt[x] if x in cnt else 0 for x in queries]38 39 404142import collections43 44 4546class Solution2(object):47 def countWordOccurrences(self, chunks, queries):48 """49 :type chunks: List[str]50 :type queries: List[str]51 :rtype: List[int]52 """53 def check(i):54 return (55 s[i].islower() or56 (s[i] == '-' and57 (i-1 >= 0 and s[i-1].islower()) and58 (i+1 < len(s) and s[i+1].islower())59 )60 )61 62 s = "".join(chunks)63 curr = []64 cnt = collections.defaultdict(int)65 for i in xrange(len(s)):66 if check(i):67 curr.append(s[i])68 continue69 if curr:70 cnt["".join(curr)] += 171 curr = []72 if curr:73 cnt["".join(curr)] += 174 curr = []75 return [cnt[x] if x in cnt else 0 for x in queries]76