Skip to main content
1 of 2
svick
  • 10.2k
  • 1
  • 40
  • 54

As MichaelT explains in his answer, your code allocates O(n) strings. But it also allocates O(n2) bytes of memory and runs in O(n2) time.

It allocates O(n2) bytes, because the strings you're allocating have lengths 0, 1, 2, …, n-1, n, which sums to (n2 - n) / 2 = O(n2).

The time is also O(n2), because allocating i-th string requires copying of (i-1)-th string, which has length i-1. This means each allocated byte has to be copied, which will take O(n2) time.

Maybe this is what the interviewers meant?

svick
  • 10.2k
  • 1
  • 40
  • 54