Learn / Strings

Strings basics and frequency

A string is an array of characters, so most array tricks work on it: two indexes, one pass with a running value, and counting. A count array of size 26 (or 256) answers most "which characters, how many times" questions in O(n).

How to recognise it

  • The question is about which characters appear, how often, or in what order.
  • Two strings must be compared character by character (prefix, rotation, mapping).
  • The string is made of only 0s and 1s, and the answer depends on a running balance or a pattern like 0101.

The idea in one picture

Think of a string as a row of letter tiles with index numbers under them. Reversing, comparing, and scanning are the same moves as on an array of numbers. The one new tool is the count array: 26 small boxes, one per letter, where each tile drops a counter in its box.

Tools you will use

ToolWhat it answersProblems here
Two indexes from both endsreversing, comparing endsReverse String
Scan from the rightthe longest prefix that ends in a certain wayLargest Odd Number
Column by column over many stringsshared prefixesLongest Common Prefix
Two maps, one in each directionone-to-one letter mappingsIsomorphic Strings
s + srotationsRotate String
Count arrayduplicates, frequency orderDuplicates, Sort by Frequency
Running balanceequal 0s and 1sSplit the Binary String

Template: counting characters

count = array of 256 zeros
for each character c in s: count[c] = count[c] + 1
for each character c in s (or each box in order):
    use count[c]

The second pass decides the order of the answer: walking s keeps first-appearance order, and walking the boxes gives alphabetical order.

Building strings

In Java use StringBuilder, in Python collect pieces in a list and "".join them, and in C++ use += on a std::string, which grows in place. Each gives O(n) for building a string of length n.

Common mistakes

  • Building with + in a Java loop, which turns O(n) into O(n²).
  • Indexing a count array with a character that is outside its range (an uppercase letter in a 26-slot array).
  • Mapping letters in one direction only when the question needs a one-to-one mapping.
  • Comparing strings in Java with ==, which compares references, not letters.

Problems

0 of 10 solved

Check yourself

Why is building a string with + inside a loop slow in Java?

s = "abcde" and goal = "cdeab". Which check tells you goal is a rotation of s?

Which structure counts lowercase letters in O(1) per letter with no hashing?

For a binary string, you keep balance = (0s so far) - (1s so far). What does balance == 0 at index i mean?