Time Complexity of Common String Operations (Interview Co...

Interview Concept: Time Complexity of Common String Operations

Interviewers often expect a candidate to know the real cost of basic string operations, not just how to call them, since assuming O(1) where it is actually O(n) is a common source of accidentally quadratic solutions.

Operation costs

OperationTypical costWhy
Access character by indexO(1)Strings are stored as contiguous arrays of characters.
Length checkO(1)Length is stored, not recomputed by scanning.
Concatenation (s1 + s2)O(n + m)A new string is allocated and both inputs are copied into it.
Substring extractionO(k)Where k is the length of the extracted piece; a new string is copied out.
Equality comparisonO(n) worst caseCharacters are compared until a mismatch or the end is reached.
Search for a substring (naive)O(n · m)Every starting position may need up to m character comparisons.

Example: the hidden cost

for i in range(len(s)):
    prefix = s[:i]          # O(i) to copy this prefix
    process(prefix)         # if process is O(1), the loop overall
                            # still costs O(1+2+...+n) = O(n^2),
                            # purely from the repeated substring copies

Why this matters in interviews

  • A solution that looks O(n) on paper can secretly be O(n²) if it repeatedly builds new strings or substrings inside a loop.
  • Being able to name the real cost of an operation, and explain why, signals a deeper understanding than simply producing working code.

Complexity

Most single string operations cost time proportional to the length of the string or substring involved, not O(1), except for indexing and length lookups. Recognising this is what separates a correct-looking solution from one that is actually efficient at scale.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.