Skip to content

    Strings

    DSA · Beginner

    Definition

    A string is an ordered sequence of characters, usually immutable, supporting indexing, slicing and searching.

    Most interview problems on parsing, palindromes and anagrams are string problems.

    Diagram

    hello

    Flowchart

    Read the stringIndex or slice charactersCount with a hash mapBuild a new string for changesReturn the result

    Example: Check a palindrome

    s = 'racecar'
    print(s == s[::-1])

    Output: True

    Complexity

    Access O(1) · Concatenation in loop O(n²) · join O(n)

    Key points

    • Python strings are immutable
    • Use ''.join() to build strings
    • Counter solves anagram checks

    Interview questions

    How do you check two anagrams?

    Compare character counts, e.g. Counter(a) == Counter(b).

    Why avoid += in a loop?

    Each concatenation copies the string, giving O(n²) total.

    More DSA topics