admin管理员组文章数量:1125787
class Solution:
def countPrefixSuffixPairs(self, words: List[str]) -> int:
n = len(words)
count = 0
for i in range(n):
for j in range(i+1, n):
if words[j].startswith(words[i]) and words[j].endswith(words[i]):
count += 1
return count
I analyzed the code, expecting the time complexity to be O(n²) due to nested loops, but I'm unsure if slicing in startswith
changes it to O(n² * m) where m is the average length of string in the list.
class Solution:
def countPrefixSuffixPairs(self, words: List[str]) -> int:
n = len(words)
count = 0
for i in range(n):
for j in range(i+1, n):
if words[j].startswith(words[i]) and words[j].endswith(words[i]):
count += 1
return count
I analyzed the code, expecting the time complexity to be O(n²) due to nested loops, but I'm unsure if slicing in startswith
changes it to O(n² * m) where m is the average length of string in the list.
1 Answer
Reset to default 3First, a correction: Neither startswith
nor endswith
involve slicing; no copies are made. That said, both methods are O(n)
in the length of the pre-/|suff-ix(es) to check.
This doesn't make it O(n³)
though. It makes it O(n²m)
, where n
is the length of words
, while m
is the (median?) length of the strings within words
. Since the length of words
and the length of its component words are independent, it would be inappropriate to describe it as O(n³)
. Your title seems to recognize this when it refers to O(n²m)
, but you blurred it together in the body of your question by calling it O(n³)
.
That said, typically, when you're talking about a list
named words
, the length of the component strings is de minimis (defining the behavior as the length of a string approaches infinity is meaningless when talking about strings that don't get much longer than 40 characters on a bad day, and average less than 10), and you can treat it as a constant term, so O(n²)
remains correct enough if words
really does contain individual English words.
本文标签:
版权声明:本文标题:python - Does slicing in startswith and endswith make the time complexity O(n² * m) {where m is the average length of s 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736675005a1947134.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
itertools.combination
to replace the nested loops.for needle, haystack in itertools.combinations(words, 2):
, thenif haystack.startswith(needle) and haystack.endswith(needle):
would do the same thing, and push a lot more work to the C layer, avoid creating a bunch of unnecessaryint
s, reduce the indentation, and let you give more useful/descriptive names to variables. It won't affect the big-O at all, but it would reduce the constant factors meaningfully. – ShadowRanger Commented 2 days agowords = list(map(str, range(1000)))
I get around 45 ms with theirs, 35 ms with yours, and 15 ms with mine. – Stefan Pochmann Commented 2 days ago