Does slicing in startswith and endswith make the time complexity O(n3), or is it O(n2) since nested loops dominate the operations? /u/Nyctophilic_enigma Python Education

I analyzed the code, expecting the time complexity to be O(n2) due to nested loops, but I’m unsure if slicing in startswith changes it to O(n3).

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 

submitted by /u/Nyctophilic_enigma
[link] [comments]

​r/learnpython I analyzed the code, expecting the time complexity to be O(n2) due to nested loops, but I’m unsure if slicing in startswith changes it to O(n3). 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 submitted by /u/Nyctophilic_enigma [link] [comments] 

I analyzed the code, expecting the time complexity to be O(n2) due to nested loops, but I’m unsure if slicing in startswith changes it to O(n3).

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 

submitted by /u/Nyctophilic_enigma
[link] [comments] 

Leave a Reply

Your email address will not be published. Required fields are marked *