Skip to content

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.

13 min read0/5 questions

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.

WordingTechniqueTypical cost
"substring" with a rule (distinct, at most k, contains all of)Sliding window with countsO(n)
"subsequence" of two strings (common, edit, transform)2D DP over prefixes of both stringsO(n · m)
"is s a subsequence of t"Two pointers, one per stringO(n + m)
"find pattern", "first occurrence", "repeated substring"Built-in search, then KMP or a rolling hash if askedO(n + m)
"palindromic substring" (longest, count)Expand around each centreO(n²)
"palindromic subsequence"Interval DP on dp[i][j]O(n²)
"valid palindrome", "after removing one character"Two pointers from both endsO(n)
"anagram", "permutation of"Count array of 26 or a CounterO(n)
"decode", "nested", "evaluate the expression"StackO(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 the pairs0/6 matched

Match each string prompt to the technique its deciding word points to.

Choose an item, then its match on the other side.

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.

ClueWhat it meansTechnique
"return the answer modulo 10^9 + 7"The true answer is astronomically large, so it is a countCounting DP or combinatorics, taking the mod at every step
"gcd", "lcm", "divides evenly", "simplify the fraction"Number theoryEuclid's algorithm, O(log min(a, b))
"prime", "count primes below n" with n up to 10^6 or 10^7Many primality answers at onceSieve of Eratosthenes
"is n prime" for one n up to 10^12One answerTrial division up to √n, about 10^6 steps
n up to 10^18, "n-th term", "power"No loop can reach nClosed formula, fast power, or matrix power
"without using *, / or %"Bit manipulationShifts and repeated doubling
"32-bit signed integer", "reverse the digits"Overflow is the real testCheck 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.

Predict the outputPython

What does this print?

print(-7 % 3, -7 // 3)
Need a nudge? Hints walk you through it.
Pythonstrings_and_math.py
import math def longest_palindrome(s: str) -> str: """Expand around each of the 2n - 1 centres. O(n^2) time, O(1) space.""" best = "" for centre in range(2 * len(s) - 1): lo, hi = centre // 2, (centre + 1) // 2 # odd centre, then even gap while lo >= 0 and hi < len(s) and s[lo] == s[hi]: lo, hi = lo - 1, hi + 1 if hi - lo - 1 > len(best): best = s[lo + 1:hi] return best def mod_pow(base: int, exp: int, mod: int) -> int: """Square and multiply: O(log exp) multiplications.""" result = 1 base %= mod while exp > 0: if exp & 1: result = result * base % mod base = base * base % mod exp >>= 1 return result MOD = 10**9 + 7 def n_choose_k_mod(n: int, k: int) -> int: """C(n, k) mod a prime, using Fermat's little theorem for the inverse.""" if k < 0 or k > n: return 0 fact = [1] * (n + 1) for i in range(1, n + 1): fact[i] = fact[i - 1] * i % MOD inverse = pow(fact[k] * fact[n - k] % MOD, MOD - 2, MOD) return fact[n] * inverse % MOD def primes_up_to(n: int) -> list[int]: """Sieve of Eratosthenes: O(n log log n).""" is_prime = [True] * (n + 1) is_prime[0:2] = [False, False] for p in range(2, math.isqrt(n) + 1): if is_prime[p]: is_prime[p * p::p] = [False] * len(range(p * p, n + 1, p)) return [i for i, ok in enumerate(is_prime) if ok] assert longest_palindrome("babad") in ("bab", "aba")assert longest_palindrome("cbbd") == "bb"assert longest_palindrome("a") == "a"assert mod_pow(2, 10, 1000) == 24assert mod_pow(3, 10**18, MOD) == pow(3, 10**18, MOD) # 60 steps, not 10^18assert n_choose_k_mod(1000, 500) == math.comb(1000, 500) % MODassert primes_up_to(30) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]assert math.gcd(84, 36) == 12print(longest_palindrome("forgeeksskeegfor"))print(n_choose_k_mod(10**5, 3))print(len(primes_up_to(10**6)), "primes below a million")
Output
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.

Quick check
'Count the distinct ways to climb n stairs taking 1, 2 or 3 steps. n is up to 10^5. Return the answer modulo 10^9 + 7.' What does the modulus tell you first?
Need a nudge? A hint rules out a wrong answer.

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 k with matrix[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.

Staircase search for 9 in a matrix with sorted rows and columns
14711
25812
36916
10131417

Start top-right at 11. It is the largest in its row and the smallest in its column, so it splits the search cleanly.

1/4

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:

ClueUsual 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 popA 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.

Pythonmatrices_and_design.py
import bisectimport random def search_sorted_matrix(matrix: list[list[int]], target: int) -> bool: """Rows and columns both sorted. Start top-right: O(m + n).""" if not matrix: return False r, c = 0, len(matrix[0]) - 1 while r < len(matrix) and c >= 0: value = matrix[r][c] if value == target: return True if value > target: c -= 1 # everything below in this column is bigger too else: r += 1 # everything left in this row is smaller too return False def rotate(matrix: list[list[int]]) -> None: """Rotate an n x n matrix 90 degrees clockwise in place.""" n = len(matrix) for i in range(n): for j in range(i + 1, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # transpose for row in matrix: row.reverse() class TimeMap: """'Time-based' design: key -> times and values kept in time order.""" def __init__(self) -> None: self.times: dict[str, list[int]] = {} self.values: dict[str, list[str]] = {} def set(self, key: str, value: str, ts: int) -> None: # The usual spec promises ts increases per key, so append keeps order. self.times.setdefault(key, []).append(ts) self.values.setdefault(key, []).append(value) def get(self, key: str, ts: int) -> str: i = bisect.bisect_right(self.times.get(key, []), ts) return self.values[key][i - 1] if i else "" class RandomizedSet: """'O(1) for every operation': hash map of value -> index, plus an array.""" def __init__(self) -> None: self.index: dict[int, int] = {} self.items: list[int] = [] def insert(self, x: int) -> bool: if x in self.index: return False self.index[x] = len(self.items) self.items.append(x) return True def remove(self, x: int) -> bool: if x not in self.index: return False i, last = self.index[x], self.items[-1] self.items[i], self.index[last] = last, i # move last into the hole self.items.pop() del self.index[x] return True def get_random(self) -> int: return random.choice(self.items) grid = [[1, 4, 7, 11], [2, 5, 8, 12], [3, 6, 9, 16], [10, 13, 14, 17]]assert search_sorted_matrix(grid, 9) and not search_sorted_matrix(grid, 15) m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]rotate(m)assert m == [[7, 4, 1], [8, 5, 2], [9, 6, 3]] tm = TimeMap()tm.set("price", "10", 1)tm.set("price", "12", 4)assert tm.get("price", 0) == "" and tm.get("price", 3) == "10" and tm.get("price", 9) == "12" rs = RandomizedSet()assert rs.insert(5) and rs.insert(7) and not rs.insert(5)assert rs.remove(5) and not rs.remove(5)assert rs.insert(9) and rs.remove(9) # removing the last element itselfassert rs.items == [7] and rs.index == {7: 0} and rs.get_random() == 7print("rotated:", m)print("all design checks pass")
Output
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 the pairs0/5 matched

Match each design prompt to the structures that meet every required cost.

Choose an item, then its match on the other side.

Constraint tells across all four groups

When the wording leaves two techniques open, the size limits usually close the gap.

ConstraintPoints 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 rangesInterval DP, O(n²) states with up to O(n) work each
n <= 1000 on a stringO(n²) is fine: centres, or 2D DP on two strings of that size
String length up to 10^5 or moreLinear: window, KMP, rolling hash, counts
Values up to 10^5 or 10^6A counting array or sieve indexed by value
n up to 10^9O(√n) or O(log n): trial division, binary search, formula
n up to 10^18O(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^3O(m · n) total, so each cell visited a constant number of times
Quick check
'Given a string s with length up to 1000, return the minimum number of cuts so every piece is a palindrome.' Which reading of the constraint is right?
Need a nudge? A hint rules out a wrong answer.
Key terms
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.