I'm looking at the following solution to this leetcode problem:
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. 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.
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.
The time complexity is worse than that due to this line inside the inner loop:
When you pass an iterable to the Set constructor, it will iterate over all elements of the iterator and add them to the Set. So, if the sliced string is 10 characters long, that's 10 operations. 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 loopO(n ^ 2), and the whole functionO(n ^ 3)in terms of time complexity.Space complexity is at least
O(n ^ 2)because that's how many Sets are created.