Catch the complexity

Shivam Sharma
1 min readDec 14, 2022

So I ask you what is the complexity for this algorithm:
We are given an array of strings, we sorted each string and then sorted the full array.

The quick reaction answer is N² Log N, but NO!
You are still thinking in terms of a singular unit. This is a string and N is what ? Look that we have a string with some characters with different lengths, a bunch of strings to be sorted. Thus a different variable for each term is required.

Solution:

Take, a as length of array of strings and s as the length of the longest string.

  1. We sort a single string that takes s log s , time and we do this for a such strings thus time complexity uptill here is => a*s log s.
  2. We sort the array, which takes a log a , time and we also compare the lengths of string which takes s time, thus the complexity of this step is => s * a log a.
  3. Since both are independent of each other we simply add them both and get the finally complexity of a*s (log a + log s) .

Thus, do not be fooled by a simple looking question as they might lead you towards a false assumption and make your answer wrong.

GOOD LUCK !

--

--