I am trying to check the time complexity of the below simple program.
The program replaces spaces in a string with '%20'.
-
The loop to count spaces (O(1) time)
foreach (char k in s) { if (k == ' ') { spaces_cnt++; } } -
The loop to replace the spaces (O(n) where n is size of string)
char[] c = new char[s.Length + spaces_cnt * 3]; int i = 0; int j = 0; while (i<s.Length) { if (s[i] != ' ') { c[j] = s[i]; j++; i++; } else { c[j] = '%'; c[j + 1] = '2'; c[j + 2] = '0'; j = j + 3; i++; } }
So I am guessing it is a “O(n) + O(1)” solution. Please correct me if I am wrong.
The loop to count spaces takes
O(n), notO(1), since you’re iterating over – and performing a check on – each of thencharacters in your string.As you stated, the replacement loop takes
O(n). TwoO(n)operations performed sequentially have a combined complexity ofO(n)(constant factors are discarded in Big-O notation).P.S. You know that you can achieve the equivalent of all your code using a single line?