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
| Tool | What it answers | Problems here |
|---|---|---|
| Two indexes from both ends | reversing, comparing ends | Reverse String |
| Scan from the right | the longest prefix that ends in a certain way | Largest Odd Number |
| Column by column over many strings | shared prefixes | Longest Common Prefix |
| Two maps, one in each direction | one-to-one letter mappings | Isomorphic Strings |
s + s | rotations | Rotate String |
| Count array | duplicates, frequency order | Duplicates, Sort by Frequency |
| Running balance | equal 0s and 1s | Split 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
- Reverse Stringeasyguide ready
- Largest Odd Number in Stringeasyguide ready
- Longest Common Prefixeasyguide ready
- Isomorphic Stringseasyguide ready
- Rotate Stringeasyguide ready
- Find Duplicate characters in a stringeasyguide ready
- Write a Program to check whether a string is a valid shuffle of two strings or noteasyguide ready
- Split the Binary string into two substring with equal 0’s and 1’seasyguide ready
- Number of flips to make binary string alternateeasyguide ready
- Sort Characters By Frequencymediumguide ready