Home > Back-end >  Time Complexity of printing an Array of String
Time Complexity of printing an Array of String

Time:09-28

Given the Pseudocode -

function PrintColours(): 
    colours = { "Red", "Green", "Blue", "Grey" } 
    
    foreach colour in colours: 
        print(colour) 

What should be the Overall Time Complexity of the Code. Is it O(n) or O(n^2) ?

Does it take longer time to print a longer string, or is it the same for all (as is the case in integers) ?

CodePudding user response:

Technically, the time complexity would be O(n) because strings have a max length so O(k*n) (k being the max string length) works out to be O(n).

But to answer your question, yes, longer strings take longer to print.

CodePudding user response:

O(k*n) is the correct time complexity because it has to iterate only the numbers of data it has. O(n^2) usually applies if you are having a loop inside a loop or an array inside an array or a multidimensional array.

Now talking about strings it is a kinda multidimensional array that consists of a character array and an array of those character arrays. But you see the size of the array can differ so it cant be O(n^2). Instead, we can use O(k*n) where k refers to the max_length of string you have.

Now you can clearly see how much string takes time to execute vs how much int takes time to execute.

  • Related