Search code examples
c#time-complexitystringbuilder

Time-complexity of looking at item in stringbuider - C#


I have some long text saved in StringBuilder and I want to get some specific item

StringBuilder builder = new StringBuilder();
//fill builder
int i = someNumber();
char ch = builder[i];

what is the time-complexity of the last instruction (char ch = builder[i])? Is it constant

O(1)

or is it linear?

O(i)


Solution

  • It is a constant as you are giving exact location to get the element.So in this case O(1). More details here What is the complexity of this simple piece of code?