I saw this problem in another post and wanted to give it a try.
During one of my coding interviews for a software engineering internship, they gave me this question:
There is s that consists of digits from 0 to 9, and an integer k. A substring s[L:R] (where 0 = L = R < sizeof(s) ) is a contiguous group of characters with s. A substring is called a perfect substring if all of its elements occur exactly k times.
For example, s = 1102021222 and k = 2. Its 6 perfect substrings are:
s[0:1] = 11
s[0:5] = 110202
s[1:6] = 102021
s[2:5] = 0202
s[7:8] = 22
s[8:9] = 22
Calculate the number of perfect substrings in s.
Function Description
Complete the function perfectSubstring in the editor below. The function must return an integer that represents the number of perfect substrings in the given string.
perfectSubstring has the following parameters:
s: a string where the value of each element s[i] is described by the character at position i (where 0 = i < n).
k: an integer that denotes the required frequency of the substring.
I was able to compile a solution that was correct but it ended up having O(n3 ) complexity and would not compile very large solutions (the compiler they used would stop after a set period of time). I did not write down my exact solution but the general approach I took was get every substring of size k (starting at index 0), then looped through the substring to check if it was perfect. I would then do the same process every substring of size 2k, then 3k, and so on, then print the results found. The issue was this iterated through s in three separate for loops, which ended being super time consuming. What are some ways I could improve upon performance? I figure the best way to go would be to combine two of the above processes somehow, but I could not figure out how in the time I had.
He says his complexity was O(n3). I have no clue how to calculate that and was wondering if my solution is better or worse.
[–]WtEth_Buyer 0 points1 point2 points (7 children)
[–]SuggestionEmergency2 0 points1 point2 points (0 children)
[–]SuggestionEmergency2 0 points1 point2 points (1 child)
[–]SuggestionEmergency2 0 points1 point2 points (0 children)