简体   繁体   English

计算具有恰好 K 个唯一字符的子串数量的时间和空间复杂度?

[英]Time and space complexity of counting number of substrings with exactly K unique characters?

I'm looking at the following solution to this leetcode problem :我正在研究这个 leetcode 问题的以下解决方案:

 function SubstringsKDistinct(str, k) { let start = 0; let end = 0; let result = []; let len = str.length; while (start < len && end < len) { while (end <= len) { if (str.slice(start, end).length > 1) { let set = new Set(str.slice(start, end)); if (set.size == k) { result.push(str.slice(start, end)); } } end++; } start++; end = start; } return result.length; }

At a glance it seems to me to be O(N^2) time complexity, considering we have one outer while loop where the number of operations is bound to the size of the input string, as well as another inner while loop with the number of operations bound to the size of the input string.乍一看,它似乎是 O(N^2) 时间复杂度,考虑到我们有一个外部 while 循环,其中操作数绑定到输入字符串的大小,以及另一个内部 while 循环与数字操作绑定到输入字符串的大小。 In terms of space complexity I'm assuming O(N) because the size of the results array will also depend on size of the input string.就空间复杂度而言,我假设 O(N),因为结果数组的大小也取决于输入字符串的大小。

Could someone chime in here with thoughts?有人可以在这里插话吗? I'm relatively new to DS & Algos and trying to wrap my head around how to think about these operations during interviews.我对 DS & Algos 比较陌生,并且试图在面试中思考如何思考这些操作。

The time complexity is worse than that due to this line inside the inner loop:由于内部循环内的这条线,时间复杂度比那个差:

let set = new Set(str.slice(start, end));

When you pass an iterable to the Set constructor, it will iterate over all elements of the iterator and add them to the Set.当您将一个可迭代对象传递给 Set 构造函数时,它将遍历迭代器的所有元素并将它们添加到 Set 中。 So, if the sliced string is 10 characters long, that's 10 operations.因此,如果切片字符串的长度为 10 个字符,则为 10 次操作。 This number is (on average, over all the loops) directly proportional to the number of characters in the input - so it's another O(n) operation inside the inner loop, making the whole inner loop O(n ^ 2) , and the whole function O(n ^ 3) in terms of time complexity.这个数字(平均而言,在所有循环中)与输入中的字符数成正比 - 所以它是内部循环内的另一个O(n)操作,使得整个内部循环O(n ^ 2) ,并且就时间复杂度而言,整个 function O(n ^ 3)

Space complexity is at least O(n ^ 2) because that's how many Sets are created.空间复杂度至少为O(n ^ 2) ,因为这就是创建了多少个 Set。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM