Lesson 24 of 27Decode by category
Decode Strings, Math, Matrices and Design
Spot the deciding clue in string, math, matrix and class-design prompts, and use constraint sizes to confirm the technique before you code.
The earlier decoding lessons covered the big pattern families: windows and hashing, graphs, DP, backtracking and heaps. A good share of real interview questions sit in four smaller groups that get misread just as often: string problems that are not windows, math problems that hide behind a modulus, matrix problems that want something done in place, and "implement this class" design problems. Each group has a short list of words that decide the technique, and each has constraint sizes that confirm it. This lesson collects those clues so that "longest palindromic subsequence" and "return the answer modulo 10^9 + 7" trigger the right tool in the first minute, not the twentieth.
Strings: which word decides
String questions are mostly about one distinction you met in Decoding Arrays and Strings, contiguous or not, plus two string-only families: palindromes and pattern matching.
| Wording | Technique | Typical cost |
|---|---|---|
| "substring" with a rule (distinct, at most k, contains all of) | Sliding window with counts | O(n) |
| "subsequence" of two strings (common, edit, transform) | 2D DP over prefixes of both strings | O(n · m) |
"is s a subsequence of t" | Two pointers, one per string | O(n + m) |
| "find pattern", "first occurrence", "repeated substring" | Built-in search, then KMP or a rolling hash if asked | O(n + m) |
| "palindromic substring" (longest, count) | Expand around each centre | O(n²) |
| "palindromic subsequence" | Interval DP on dp[i][j] | O(n²) |
| "valid palindrome", "after removing one character" | Two pointers from both ends | O(n) |
| "anagram", "permutation of" | Count array of 26 or a Counter | O(n) |
| "decode", "nested", "evaluate the expression" | Stack | O(n) |
Three of these are worth a closer look.
Substring versus subsequence of palindromes. "Longest palindromic substring" wants a contiguous run, and there are only 2n − 1 possible centres (each character, and each gap between two characters), so expanding from every centre is O(n²) with O(1) space. "Longest palindromic subsequence" lets you skip characters, which breaks the centre trick. It becomes interval DP: dp[i][j] is the answer for s[i..j], built from shorter intervals. Same word "palindromic", completely different algorithm, and the one-word difference is the whole decode.
Pattern matching. In most interviews, using the language's built-in search (in, str.find, indexOf) is fine and expected. If the interviewer asks you not to, or the problem is really about the matching itself ("shortest palindrome by adding characters in front", "repeated substring pattern"), name KMP (a failure table so the search never moves backwards in the text) or Rabin-Karp (a rolling hash that updates in O(1) per shift, with a direct comparison to rule out collisions). You rarely need to code KMP from memory, but you should know what problem it solves: naive matching rescans text and is O(n · m) in the worst case.
Parsing. "Decode 3[a2[c]]", "basic calculator", "simplify a Unix path": anything with nesting is a stack, because the innermost open structure is the one that closes next.
Match each string prompt to the technique its deciding word points to.
Math: the clue is often in the output line
Math problems announce themselves in the constraints and in what the output must look like more than in the story.
| Clue | What it means | Technique |
|---|---|---|
| "return the answer modulo 10^9 + 7" | The true answer is astronomically large, so it is a count | Counting DP or combinatorics, taking the mod at every step |
| "gcd", "lcm", "divides evenly", "simplify the fraction" | Number theory | Euclid's algorithm, O(log min(a, b)) |
| "prime", "count primes below n" with n up to 10^6 or 10^7 | Many primality answers at once | Sieve of Eratosthenes |
| "is n prime" for one n up to 10^12 | One answer | Trial division up to √n, about 10^6 steps |
| n up to 10^18, "n-th term", "power" | No loop can reach n | Closed formula, fast power, or matrix power |
"without using *, / or %" | Bit manipulation | Shifts and repeated doubling |
| "32-bit signed integer", "reverse the digits" | Overflow is the real test | Check bounds before the step that could overflow |
The modulus clue deserves emphasis. When a prompt asks for "the number of ways" and adds "modulo 10^9 + 7", it is telling you the answer grows exponentially and that you are counting, not listing. That is a strong pointer away from backtracking and toward DP or a formula, as you saw in Decoding DP and Greedy. Take the mod after every addition and multiplication. Python integers never overflow, but numbers with thousands of digits make every operation slow. In JavaScript, the product of two values near 10^9 exceeds 2^53 − 1, so it silently loses precision unless you use BigInt.
Two language details cause real bugs in math problems. Python's % takes the sign of the divisor and // floors toward negative infinity. JavaScript's % takes the sign of the dividend. If your code computes indices or hashes with % on numbers that might be negative, check what your language does.
What does this print?
print(-7 % 3, -7 // 3)
Press Run (⌘ Enter) to see what happens.In an interview, Python's built-in three-argument pow(base, exp, mod) does fast modular power for you, and math.gcd, math.comb and math.isqrt are all standard. Use them, and be ready to explain the idea underneath: squaring the base halves the exponent, which is why 10^18 takes about 60 steps.
Matrices: in place, spiral, rotate, sorted
Grid problems that are really graphs (islands, shortest path through a maze) belong to Decoding Trees and Graphs. The matrix problems here are about index arithmetic, and their clues are specific.
- "Rotate 90 degrees, in place." Transpose, then reverse each row. Both steps are swaps, so the extra space is O(1). Counter-clockwise is transpose then reverse each column.
- "Spiral order." Keep four boundaries: top, bottom, left, right. Walk one edge, then move that boundary inward. The bug to watch for is a single remaining row or column being visited twice, so check the boundaries again before the third and fourth edges.
- "Set the row and column to zero, in place." Use the first row and first column as marker storage, with one extra flag for whether the first row itself had a zero.
- "Game of Life, in place." Encode the old and new state in the same cell (for example, 2 for "was alive, now dead") so neighbours can still read the old value.
- "Each row sorted, and each row starts after the previous row ends." The matrix is one sorted list in disguise. Binary search on index
kwithmatrix[k // cols][k % cols]: O(log(m · n)). - "Rows sorted and columns sorted" (but no promise between rows). Staircase search from the top-right corner: O(m + n).
The last two prompts read almost the same, which makes them a favourite contrast. The second has weaker sorting, so you cannot binary search the whole thing, but the corner trick works because from the top-right every step rules out a full row or a full column.
Start top-right at 11. It is the largest in its row and the smallest in its column, so it splits the search cleanly.
Design: "implement a class"
Design problems give you method names and ask for a class. The decode is the same as in Choosing Data Structures: list the operations, write the required cost next to each, and find structures that meet all of them at once. The clues:
| Clue | Usual combination |
|---|---|
| "O(1) for get and put, evict least recently used" | Hash map plus doubly linked list (or an ordered dict) |
| "insert, delete and get random, all O(1)" | Hash map of value to index plus an array, removing by swapping with the last element |
| "get the minimum in O(1)" alongside push and pop | A second stack of running minimums |
| "iterator", "next and hasNext" | Store a cursor and compute lazily; a stack for nested input |
| "time-based", "value at timestamp t" | Map of key to a time-sorted list, then binary search |
| "least frequently used" | Map of key to frequency plus a map of frequency to ordered keys |
| "hit counter in the last 5 minutes" | Queue of timestamps, drop from the front as time moves |
The pattern underneath almost every one: one structure finds things, another keeps order. A hash map gives O(1) lookup but no order. A list, linked list or heap gives order but slow lookup. Pairing them, and keeping both in sync on every operation, is the whole design.
Press Run (⌘ Enter) to see what happens.The RandomizedSet.remove trick is worth saying out loud in an interview: removing from the middle of an array is O(n), but if order does not matter you can move the last element into the hole and pop the end in O(1). You only have to update that one moved element's index. Delete the removed value's index after that update: when the removed value is itself the last element, doing it the other way round writes its stale index straight back. The test removes the last element on purpose to check this.
Match each design prompt to the structures that meet every required cost.
Constraint tells across all four groups
When the wording leaves two techniques open, the size limits usually close the gap.
| Constraint | Points to |
|---|---|
n <= 20 with "choose any subset" | Bitmask enumeration or bitmask DP: 2^20 is about a million |
n <= 500 on a single string or array, answer over ranges | Interval DP, O(n²) states with up to O(n) work each |
n <= 1000 on a string | O(n²) is fine: centres, or 2D DP on two strings of that size |
String length up to 10^5 or more | Linear: window, KMP, rolling hash, counts |
Values up to 10^5 or 10^6 | A counting array or sieve indexed by value |
n up to 10^9 | O(√n) or O(log n): trial division, binary search, formula |
n up to 10^18 | O(log n) only: fast power, matrix power, or a formula |
| "modulo 10^9 + 7" | Counting with DP or combinatorics |
Grid up to 10^3 x 10^3 | O(m · n) total, so each cell visited a constant number of times |
- expand around centre
- Finding palindromic substrings by growing outwards from each of the 2n − 1 centres, in O(n²) time and O(1) space.
- interval DP
- DP where the state is a range
[i, j], built from shorter ranges, often used for palindromic subsequences. - rolling hash
- A hash of a fixed-length window that updates in O(1) as the window slides, used by Rabin-Karp.
- fast power
- Computing a power in O(log n) multiplications by squaring the base and halving the exponent.
- sieve of Eratosthenes
- Marking multiples of each prime to list every prime up to n in O(n log log n).
- staircase search
- Searching a matrix with sorted rows and columns from a corner, ruling out a row or column per step.
- swap-remove
- Deleting from an unordered array in O(1) by moving the last element into the gap and popping the end.