Reputation: 53
Long story short, I am looking to verify if my time complexity for following code is correct.
class Solution {
public String reverseWords(String s) {
int len = s.length(); int i=len-1, j=0;
StringBuilder answer= new StringBuilder();
while(i!=-1) {
if(s.charAt(i)==' ') i--;
else {
j=i;
while(j-1!=-1 && s.charAt(j-1)!=' ' ) j--; //j++;
answer.append(s.substring(j, i+1)).append(' ');
i=j-1;
}
}
return answer.toString().trim(); //trim last index's space
}
}
Constraints:
1 <= s.length <= 10^4
s
contains English letters (upper-case and lower-case), digits, and spaces ' '.s
Assuming string length is N. My analysis is to further assume there are K spaces in string S and assume there are L different space separated words in it, as per given constraints we can conclude that L>=1 and K>=0.
Thus the average length of each word is N-K/L, outer loop runs thus, K+L times, and inner loop runs independent of outer for 2*(N-K)/L times making total complexity as 2(N-K)/L + K+L which is still order of O(N).
Am I making any wrong assumptions? Is there a way to simplify this formula of 2*(N-K)/L + K+L
Upvotes: 0
Views: 59
Reputation: 59
I'm pretty sure that the runtime is O(n).
Although I'm not too sure what the N in your formula is, the general rule for simplifying is looking at the largest value. I will assume that N is the largest for you. The "+K+L" is negligible so we have 2*(N-K)/L. Distributing: (2/L)N - (2/L)K. We drop constants and take the largest one so it would still be O(n)
In my opinion, an easier way to look at the runtime is to just look at how many times your code runs through the string. Your first while goes until it triggers the else. Starting from the index you stopped at, the second loop keeps counting until it stops. From there, you change the original i to the j and keep going through. I think the code looks at where i stops twice but that isn't enough to change the complexity (a fix would just be to set j to i - 1 since you know the char at i is not a space already).
As a short side note, N typically denotes the length of the input, whether it be string length or array size.
Upvotes: 1