Skip to content

Software interviews

Arrays and strings for coding interviews: patterns and practice problems

An array gives you constant-time access by position and slow changes in the middle, and a string behaves like an array of characters that you cannot edit in place. Most array and string problems fall to one of four moves: a prefix sum with a table of counts, two pointers on sorted data, a sliding window and a table of the last position of each character. This page gives the costs from the sources, the signals for each move, the edge cases and four original problems with recomputed answers.

Your first hour with George Li (60 minutes by video, $250) ends with a written plan within one working day.

Book your first hour ($250)

What the structures are and what they cost

NIST’s Dictionary of Algorithms and Data Structures defines an array as an assemblage of items that are randomly accessible by integers, the index. That is the whole point of one: you can reach any item by its position in the same time, whatever the size. Open Data Structures reports the same for an array-based list: reading or setting the item at position i takes constant time, and adding or removing at position i takes time proportional to n minus i, because later items shift. It also shows that growing the backing array costs a total of O(m) over m operations, so each operation costs O(1) amortized.

Python’s own documentation gives the figures for its lists, and the Python wiki page TimeComplexity now points to it. A search with `x in list` is O(n), and so is iteration. A sort is O(n log n) in the worst case. The documentation explains that the worst case for popping or inserting at an index is index 0, where the whole rest of the list has to be moved. Its tutorial says the same from the other side: appends and pops from the end of a list are fast, and inserts or pops from the beginning are slow because all the other elements have to be shifted by one, so for a queue it points to `collections.deque`.

Costs of Python lists and strings, from the Python documentation
OperationCostNote
Get or set an item by indexO(1)Constant time whatever the size
Append at the endO(1) amortizedAn occasional resize is spread over many appends
Insert or pop at index kO(n - k)The worst case is index 0
Get a slice from i to jO(j - i)The slice is a copy
x in listO(n)A linear scan
SortO(n log n)Worst case; near O(n) for input that is already sorted
Concatenate two stringsO(len(s) + len(t))Each concatenation builds a new string, so a loop of them is quadratic overall
Find a substringO(n)For the plain search, per the page’s note

Strings add one trait to remember. In Python a string cannot be changed in place, so any edit builds a new one, which is why collecting pieces in a list and joining them once is the standard way to build a long string.

The problem signals that call for each move

Signals in a problem statement and the technique each calls for
Signal in the statementWhat it usually meansTechnique
“Subarray with a given sum,” possibly with negativesDifferences of running totalsPrefix sums and a table of counts
“Pair that adds to a target,” in sorted dataMatch a small value with a large oneTwo pointers, one at each end
“Longest run with a property,” where adding only raises itA window that can shrink from the leftSliding window
“Longest substring without repeating”A window that must stay distinctA table of last positions and a left edge
“Count,” “first,” “duplicate”Lookups by valueA hash table of counts or positions
“In place,” “constant extra space”Rewrite the array without a copyTwo pointers that read and write

Pattern 1: prefix sums and a table of counts

A prefix sum is the running total up to each position. The sum of any subarray is the difference of two prefix sums, so counting subarrays with a target sum means counting pairs of prefix sums, earlier and later, that differ by the target. A table of how many times each prefix sum has appeared lets you answer for each position in constant time. The table shows why this beats checking every subarray.

Subarrays to check against steps for a prefix-sum pass
Elements (n)Subarrays, n (n + 1) / 2Steps in one prefix-sum pass
105510
1,000500,5001,000
100,0005,000,050,000100,000

The method works with negative numbers, where a growing and shrinking window does not, because a negative number can lower a sum as the window grows. Our first problem counts subarrays with a given sum in an array that holds negatives.

Pattern 2: two pointers on sorted data

When the array is sorted, put one pointer at each end. If the sum is too large, the larger value cannot pair with anything that remains, so move the right pointer in. If it is too small, move the left pointer. Each step discards one value for good, so the pass is O(n) after the sort. The case that decides the answer is duplicates: a run of equal values on each side multiplies, and when both pointers sit in one run, every pair inside it counts. Our second problem includes both.

Pattern 3: the sliding window

Grow the window one element at a time on the right, and when it breaks the rule, shrink it from the left until it is valid again. Record the best length as you go. Each element enters and leaves once, so the pass is O(n). This relies on a measure that adding an element can only raise and removing one can only lower, as with sums of non-negative numbers. Our third problem uses non-negative values for that reason, and a good answer says why.

Pattern 4: strings and a table of last positions

For the longest stretch with no repeated character, keep a left edge and a table of the last position of each character. When the next character was last seen at or after the left edge, move the edge to one past that position. The pass is O(n) and the table holds at most one entry per distinct character. Our fourth problem works through a short string.

Strings on their own: what changes from an array

A string looks like an array of characters, and most array patterns carry over, but three differences decide the cost of a solution. The first is whether you can change one in place. Python’s documentation says strings are immutable, and the Java documentation says that strings are constant, with values that cannot change once created. Java offers a StringBuilder, described as a mutable sequence of characters, for the job of building one up.

The second difference is the cost of building text. If every concatenation builds a new string, joining n pieces copies one character, then two, then three and so on. Collecting the pieces and joining once copies each character a single time.

Characters copied when n one-character pieces are joined (counted from the formulas)
Pieces (n)Repeated concatenation, n (n + 1) / 2One join, n
105510
1,000500,5001,000
100,0005,000,050,000100,000

Say this sentence in an interview and the interviewer hears that you know why a loop over a string can be slow even when it looks like a single pass.

Prefix trees, for questions about words that share a start

The NIST Dictionary of Algorithms and Data Structures defines a trie as a tree for storing strings in which there is one node for every common prefix. A trie suits questions such as which stored words begin with a given start, and the cost of a lookup depends on the length of the word, not on how many words are stored.

Take four words: car, card, care, cat. The distinct non-empty prefixes are c, ca, car, card, care, cat, which is 6 nodes below the root, although the four words hold 14 letters between them. The shared start “ca” is stored once.

Edit distance, for questions about turning one text into another

NIST defines the Levenshtein distance, also called edit distance, as the smallest number of insertions, deletions and substitutions that change one string into another, and notes that a table of m by n cells computes it for strings of lengths m and n. For “kitten” and “sitting” the distance is 3: substitute k with s, substitute e with i and insert g. The state is a pair of prefix lengths, the same table shape as the two-text problem in dynamic programming.

Four string questions and the tool each calls for
The question asksToolWhat to say about cost
Do two words use the same lettersA table of counts for each wordOne pass over each word, space bounded by the alphabet
Is a text a palindromeTwo pointers moving inwardOne pass, no extra space
Which stored words start with a given prefixA prefix treeTime follows the prefix length
How different are two wordsA table over prefix lengthsTime and space follow the product of the two lengths

Edge cases interviewers probe

  • An empty array or string. State what you return before you write the loop.
  • One element. Many loops assume at least two.
  • All negative numbers, or a target of zero. Both break the shortcuts that assume positive values.
  • Duplicates. Decide whether two pairs with equal values but different positions count separately.
  • Off-by-one at both ends of a window. Test the first and last positions by hand.
  • Building a string in a loop. Name the quadratic cost and use a list and a single join.
  • Large sums. In a language with fixed-size integers, say what happens when a sum is too big for the type.

A good habit is to run your solution on the smallest case that could break it, such as a single element or an array of equal values, before you say it is done.

Four practice problems, in order of difficulty

These are our own practice problems. Try each on paper first, then open the working. They run from prefix sums to a string window. These are our own practice problems, written for this site. If you have signed an agreement about an assessment, keep its contents to yourself, including in a coaching session.

Problem 1. An array holds 3, 4, -7, 1, 3, 3, 1, -4. A subarray is a run of one or more neighbouring elements. How many subarrays have a sum of exactly 7? Give an integer.

Show the answer and the working

Answer: 4

  1. Build prefix sums, where P[k] is the sum of the first k elements: 0, 3, 7, 0, 1, 4, 7, 8, 4. A subarray from position i to j has sum P[j] - P[i], so you want pairs of prefix sums, earlier and later, that differ by 7.
  2. Walk the prefix sums once and keep a count of each value seen so far. At each new prefix sum P, add the count of earlier prefix sums equal to P - 7.
  3. The prefix sum 7 at the second step finds one earlier 0. The prefix sum 7 at the sixth step finds two earlier 0 values. The prefix sum 8 at the seventh step finds one earlier 1. No other step finds a match, so the total is 1 + 2 + 1 = 4.
  4. A hash map of counts makes this one pass, O(n) time and O(n) space. Testing every pair of positions costs O(n^2), and a window that grows and shrinks does not work here because the array holds negative numbers.

Problem 2. A sorted array holds 1, 2, 2, 3, 4, 4, 5, 6, 6, 8. How many pairs of positions i < j have values that add up to 8? Two pairs that use different positions count separately, even when their values match. Give an integer.

Show the answer and the working

Answer: 6

  1. Put one pointer at each end. The values are 1 and 8, which add to 9, more than 8, so the larger value cannot be part of any pair with a value that remains. Move the right pointer in.
  2. Now the values are 1 and 6, which add to 7, less than 8. Move the left pointer right. The values are 2 and 6, which add to 8, a match.
  3. The value 2 appears twice and the value 6 appears twice, so these runs give 2 x 2 = 4 pairs. Move both pointers past their runs. The values are 3 and 5, which add to 8, so that is 1 pair.
  4. Move both again. The pointers now sit on the two 4 values, and the sum is 8. When both pointers are on the same value, every pair inside the run counts, which is 2 values giving 1 pair. The total is 4 + 1 + 1 = 6. One pass costs O(n) after the sort.

Problem 3. An array of non-negative integers holds 2, 1, 3, 1, 1, 4, 2, 1, 1, 2. What is the length of the longest run of neighbouring elements whose sum is at most 6? Give an integer.

Show the answer and the working

Answer: 4

  1. Because every value is non-negative, adding an element never lowers the sum and removing one never raises it. That makes a window that grows on the right and shrinks on the left correct.
  2. Grow the window one element at a time. Whenever the sum goes above 6, remove elements from the left until it is 6 or less, and record the length after each step.
  3. The window 1, 3, 1, 1 has sum 6 and length 4. Adding the 4 pushes the sum to 10, and removing from the left brings it back to the window 1, 1, 4, which has sum 6 and length 3. Later the window 2, 1, 1, 2 has sum 6 and length 4.
  4. No window of length 5 has a sum of 6 or less, so the answer is 4. Each element enters and leaves the window at most once, so the pass is O(n).

Problem 4. What is the length of the longest stretch of neighbouring characters in the string "pwwkewabcdbaxy" in which no character appears twice? Give an integer.

Show the answer and the working

Answer: 7

  1. Keep a window and a table of the last position of each character. When the next character was last seen inside the window, move the left edge to one past that position.
  2. Positions run from 0: p, w, w, k, e, w, a, b, c, d, b, a, x, y. The second w, at position 2, moves the left edge to 2. The third w, at position 5, was last seen at 2, which is inside the window, so the left edge moves to 3.
  3. From position 3 the window keeps growing through k, e, w, a, b, c, d, which is positions 3 to 9, a length of 7. The next b, at position 10, was last seen at position 7, so the left edge moves to 8 and the window shrinks.
  4. The window after that never beats 7: it reaches 6 characters, c, d, b, a, x, y. The answer is 7. One pass with a table of last positions is O(n), against O(n^2) or worse when you test every substring.

Every answer above is recomputed by a separate program when the site is built, and the program rebuilds each result by a different route from the written steps. A wrong answer would stop the build.

A longer ladder of arrays problems

Four worked problems are a start, and a longer list is worth having for the weeks before an interview. The table sorts 22 problem types that interviewers often use for arrays into three sets, with what each set trains. A coaching company that publishes a large question list on this topic sorts its own list by the stage where such questions tend to turn up: simpler ones on a phone screen, harder ones on a video call or onsite round, where you may get more time. We keep that idea and describe each type in our own words.

Arrays problem types in three sets, with a count of each
SetTypesProblems to look upWhat the set trains
Easy8merging two sorted arrays; removing duplicates in place; counting how often a value appears; finding a pair with a given sum; the largest or smallest value; the best sum of a contiguous run; adding one to a number held in digits; finding the one value that appears onceIndex arithmetic and counting, with a short loop
Medium7moving zeros to one end; rotating by a number of places; a product of all the other values; the shortest stretch that is out of order; the best circular run; fewest jumps to the end; duplicates in linear time with constant extra spaceTwo pointers, prefix and suffix sums and in-place edits
Hard7rotating a grid in place; the largest value in every window; the smallest missing positive number; the median of two sorted arrays; the largest rectangle under a histogram; trapped rain between bars; the longest increasing subsequenceA trick that removes a nested loop, and careful invariants

Do not try to read every solution. New questions appear every season, so the aim is to own the pattern behind a set, not the answer to each item. For each problem, set a timer, write your own attempt with no reference, and only then read a solution. When you get stuck, look at one solution, close it and redo the problem from a blank page the next day. A pile of read solutions teaches far less than a few redone from memory.

Interviewers say “array” as if it were one thing, but languages differ. A fixed-size array holds values of one type, while the growable list that most languages offer by default resizes behind the scenes. Say which one you are using, say what happens when you add at the end and what happens when you insert at the front, and your costs will match your code.

Questions

What is the time complexity of inserting into a Python list?

Python’s documentation lists inserting at position k as O(n - k), because the elements after it have to move, and appending at the end as O(1) amortized. Inserting at the front is the worst case.

When does a sliding window work?

A window that grows on the right and shrinks on the left works when adding an element can only raise a measure and removing one can only lower it, as with sums of non-negative numbers. With negative numbers, a prefix sum and a table of counts is the safer tool.

Why is building a string in a loop slow?

Python’s documentation notes that each concatenation builds a new object, so joining many pieces with repeated concatenation is quadratic in the total length. Collecting the pieces in a list and joining once avoids it.

How a session helps

A session with George is a place to work a problem aloud and have the reasoning questioned. You write every line of code and every answer yourself. An hour is $250, and a package of 5 sessions is $1,165 for a full interview season. Your first purchase is refundable for unused time within 7 days. Next, read the data structures checklist and the coding and complexity practice, and use the coding prep schedule to space your practice. The college students page and the packages page list the sessions.

Want help with your own applications? See internship interview coaching, a career coach for college internships, or resume review for internships.

Start with one hour

  • Your first purchase is refundable for unused time within 7 days. Nothing renews. Refund terms