Big O Gym › Problem

Big O Practice: String Concat

Time and space complexity practice in Python and JavaScript. Concept tested: hidden cost: immutable string concatenation.

def join_words(words):
    result = ''
    for w in words:
        result = result + w
    return result

Variables

  • n - total length of the concatenated result

Explanation

Looks linear - one `+=` per word - but each concatenation copies the entire result so far because strings are immutable. Summing 1 + 2 + ... + n character copies is **O(n²)**. Final string holds `n` chars, **O(n)** space. The fix is `"".join(words)` / `words.join("")` which is O(n).

More Big O practice problems · Today's daily problem