Skip to content
Visual explainer 8h to learn 6 steps

Arrays & strings

Solve prefix sums, in-place updates and string manipulation problems.

By Invicly Tech, , in Interview Preparation. About 10 minutes to read.

Topic 2 of 27

In short

Array and string problems test careful indexing, in-place updates and precomputation. Prefix sums and two-pass scans turn repeated work into a single O(n) pass.

Explained simply

An array is a row of boxes in memory, numbered from 0. Because the boxes sit side by side, the computer can jump to any box by its number instantly. A string is basically an array of characters. Many interview problems start here, because arrays are simple to explain and easy to get subtly wrong.

Most array tricks are about not repeating work. If you keep asking "what is the sum from here to there?", you can save running totals once and answer every question with one subtraction. If you need the best value so far, you carry it along in one variable instead of looking back.

"In place" means changing the array you were given instead of making a new one. It saves memory, but you must not overwrite a value before you have used it. A common trick is a write pointer that marks where the next value you keep should go.

Strings add one more trap: in Java and Python, strings cannot be changed. Every "change" builds a new copy. So for heavy editing, convert to a char array or use a StringBuilder, and turn it back into a string at the end.

Press Play on a diagram to walk through it one step at a time.

FlowPrefix sum pattern
  1. Step 1
    Start p = [0]

    p[i] will hold the sum of the first i items

  2. Step 2
    Add each item

    p[i + 1] = p[i] + nums[i]

  3. Step 3
    Answer a range

    sum(l..r) = p[r + 1] - p[l]

  4. Step 4
    Each query O(1)

    After an O(n) build

FlowProduct of array except self
  1. Step 1
    Left pass

    out[i] = product of everything left of i

  2. Step 2
    Right pass

    Multiply out[i] by product of everything right

  3. Step 3
    Return out

    O(n) time, no division needed

FlowRotate [1..7] right by 3 with three reversals
  1. 1
    Start

    [1, 2, 3, 4, 5, 6, 7], k = 3 (use k mod n)

  2. 2
    Reverse all

    [7, 6, 5, 4, 3, 2, 1]

  3. 3
    Reverse first k

    [5, 6, 7, 4, 3, 2, 1]

  4. 4
    Reverse the rest

    [5, 6, 7, 1, 2, 3, 4]

  5. 5
    Done

    O(n) time, O(1) extra space

In depth

The read pointer and the write pointer

Many in-place problems use two indexes moving in the same direction. The read pointer visits every element. The write pointer only moves when you decide to keep something. Everything before the write pointer is the finished answer.

To remove all zeros, the read pointer scans the array, and each non-zero value is copied to position write, then write moves on. At the end, the first write slots hold the kept values in their original order. Remove Duplicates from Sorted Array, Move Zeroes and Remove Element all use this exact shape, in O(n) time and O(1) extra space.

  • read visits every index
  • write marks the next free slot
  • Everything left of write is final
FlowRemoving zeros from [0, 1, 0, 3, 12]
  1. 1
    Start

    write = 0

  2. 2
    read 1

    Copy to index 0, write = 1

  3. 3
    read 3

    Copy to index 1, write = 2

  4. 4
    read 12

    Copy to index 2, write = 3

  5. 5
    Done

    First 3 slots: [1, 3, 12], order kept

Kadane's algorithm for the best subarray

Maximum Subarray asks for the contiguous run with the largest sum. Checking every start and end is O(n squared). Kadane's idea: the best subarray ending at this index either extends the best one ending at the previous index, or starts fresh here. So cur = max(x, cur + x), and the answer is the largest cur ever seen.

The reasoning matches the stock problem: carry a small summary of the past in a variable instead of looking back. It runs in O(n) time and O(1) space, and it handles all-negative arrays if you start cur and best at the first element rather than at 0.

Difference arrays: prefix sums in reverse

Prefix sums make range queries cheap. Difference arrays make range updates cheap. To add v to every element from l to r, do diff[l] += v and diff[r + 1] -= v. After all updates, one prefix-sum pass over diff rebuilds the real array.

So q range updates cost O(q + n) instead of O(q × n). This appears in problems like Car Pooling, Corporate Flight Bookings and "how many meetings are running at each minute".

  • Add v to l..r: diff[l] += v, diff[r + 1] -= v
  • Rebuild with one prefix-sum pass
  • Allocate n + 1 slots to avoid an index error
FlowAdd 2 to indexes 1..3 of a 5-item array
  1. Step 1
    diff with n + 1 slots

    [0, 0, 0, 0, 0, 0]

  2. Step 2
    diff[1] += 2

    [0, 2, 0, 0, 0, 0]

  3. Step 3
    diff[4] -= 2

    [0, 2, 0, 0, -2, 0]

  4. Step 4
    Prefix-sum pass

    [0, 2, 2, 2, 0]

Strings in Java without surprises

Java strings are immutable, so s += c in a loop creates a new string every time. Use a StringBuilder and call toString once at the end. Read with s.charAt(i), use s.toCharArray() when you want to sort or swap characters, and rebuild with new String(chars).

For letter counts, an int[26] indexed by c - 'a' is faster and clearer than a HashMap. Compare strings with equals, never with ==, because == only checks whether two references point at the same object. Character.isLetterOrDigit and Character.toLowerCase handle the cleaning that palindrome problems need.

Learn it in 6 short steps

About 1h 20m each. Track them with a timer in your plan.

  1. 1
    Learn in-place updates and swaps~1h 20m
  2. 2
    Build prefix sums for range queries~1h 20m
  3. 3
    Practise string building and parsing~1h 20m
  4. 4
    Practice: Two Sum, Best Time to Buy Stock~1h 20m
  5. 5
    Practice: Product of Array Except Self~1h 20m
  6. 6
    Solve 15 easy and medium problems~1h 20m

Key points

  • Prefix sums answer many range-sum queries in O(1) each after O(n) setup.
  • Track a running minimum or maximum to solve stock-style problems in one pass.
  • Build strings with a list and join; repeated concatenation can be O(n squared).
  • Always test empty input, one element, duplicates and negative numbers.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
def build_prefix(nums):
    p = [0]
    for x in nums:
        p.append(p[-1] + x)
    return p  # sum(nums[l..r]) = p[r + 1] - p[l]

def max_profit(prices):  # Best Time to Buy and Sell Stock
    best, low = 0, float('inf')
    for price in prices:
        low = min(low, price)
        best = max(best, price - low)
    return best  # O(n) time, O(1) space

Move Zeroes with a write pointer

Input [0, 1, 0, 3, 12], write = 0. read 0 sees 0: skip. read 1 sees 1: copy to index 0, write = 1. read 2 sees 0: skip. read 3 sees 3: copy to index 1, write = 2. read 4 sees 12: copy to index 2, write = 3. Now fill indexes 3 and 4 with zeros. Result [1, 3, 12, 0, 0]. Time O(n), space O(1), and the non-zero values keep their order.

java
void moveZeroes(int[] nums) {
    int write = 0;
    for (int read = 0; read < nums.length; read++) {
        if (nums[read] != 0) {
            nums[write++] = nums[read];
        }
    }
    while (write < nums.length) {
        nums[write++] = 0;
    }
}

Maximum Subarray with Kadane

Input [-2, 1, -3, 4, -1, 2, 1, -5, 4]. Start cur = best = -2. At 1: max(1, -1) = 1, best 1. At -3: max(-3, -2) = -2. At 4: max(4, 2) = 4, best 4. At -1: cur 3. At 2: cur 5, best 5. At 1: cur 6, best 6. At -5: cur 1. At 4: cur 5. The answer is 6, from [4, -1, 2, 1]. One pass, O(1) memory.

java
int maxSubArray(int[] nums) {
    int cur = nums[0], best = nums[0];
    for (int i = 1; i < nums.length; i++) {
        cur = Math.max(nums[i], cur + nums[i]);
        best = Math.max(best, cur);
    }
    return best;  // O(n) time, O(1) space
}

Quick reference

  • Range sum l..r from prefix p: p[r + 1] - p[l]
  • Range update l..r by v: diff[l] += v; diff[r + 1] -= v
  • Kadane: cur = max(x, cur + x); best = max(best, cur)
  • Read and write pointers compact an array in O(n) time, O(1) space
  • Rotate right by k: k %= n, reverse all, reverse first k, reverse the rest
  • Java: StringBuilder to build, equals to compare, int[26] for letter counts
  • Edge cases: empty, one element, all negative, duplicates, sums that overflow int (use long)

Common mistakes

  • Off-by-one errors in range bounds; write a tiny example and trace it.
  • Modifying an array while iterating over it.
  • Using division in Product Except Self, which breaks on zeros.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What does Kadane's algorithm keep at each index?

Question 2

2You must add 5 to every element from index 2 to 6, many times over. Which technique makes each update O(1)?

Question 3

3Why is s += c inside a loop slow in Java?

Question 4

4Rotating [1, 2, 3, 4, 5] right by 7 is the same as rotating it by:

Question 5

5Does Move Zeroes with a write pointer keep the order of the non-zero values?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Remove Duplicates from Sorted Array: remove duplicates in place and return how many unique values remain at the front.

  2. Exercise 2medium

    Subarray Sum Equals K: count contiguous subarrays whose sum is exactly k. Values can be negative.

  3. Exercise 3hard

    Trapping Rain Water: given bar heights, compute how much water is trapped after rain, in O(n) time and O(1) space.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Are arrays and lists the same in interviews?
Usually you can treat them the same. In Java, int[] has a fixed size while ArrayList grows; say which one you use and why.
When should I sort the array first?
When order does not matter for the answer and sorting unlocks two pointers or binary search. Remember that sorting costs O(n log n) and loses the original indexes.
How do I avoid off-by-one bugs?
Decide whether your ranges are inclusive or exclusive, write it as a comment, and trace a two or three element example by hand before running the code.

Go deeper

ShareXLinkedInWhatsApp