cswork / templatesOpen the Line 500 list

STOP 01 · LINEAR STRUCTURES

In-place Arrays and Sorting

Read/write pointers for in-place compaction O(n) time · O(1) space

Open the Line 500 list · stop 01 · 20 problems
Learn first
A starting stop: nothing to learn first.
Leads to
How often asked
asked by 5 companies · in 9 reportsMeta 3, Apple 2, Microsoft 2, Amazon 1, Walmart Labs 1

Warm up with this one

LC 26Remove Duplicates from Sorted ArrayEasy
Stuck? Peek at the approach

Maintain a deduplicated prefix with read and write pointers, and distinguish the returned length from the valid range.

Key points

  1. Everything left of the write pointer w is final; the read pointer only scans forward, so each pointer moves once.
  2. Decide whether to keep a value by comparing it with nums[w-k], the kept result, not with the previous raw element.
  3. When merging two sorted arrays in place, write from the back so you never overwrite unread data.

Common pitfalls

  • The judge reads only the first k slots; return the new length and never rely on anything past it.
  • Deleting while iterating (list.remove, ArrayList.remove) is O(n²) and skips elements.
  • A comparator written as a - b overflows near ±2^31; use Integer.compare or a plain < comparison.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Arrays · insert, delete, dedupe in place

Sorted array 1, 2, 2, 4, 4, 4, 6: insert 3, delete index 0, then dedupe

Try your own input
10
21
22
43
44
45
66
·7
CurrentDiscovered / computedAnswer
Length
7
Moves
0
w
—
r
—

A sorted array with one free slot (·) at the end. Arrays are contiguous, so inserting or deleting shifts the elements after it.

InvariantThe array always stays contiguous: inserting or deleting in the middle shifts what follows; while deduping, everything left of w is final.

Interactive demo · step by step

Quicksort · O(n log n) on average, O(n²) when sorted

Sort 2, 3, 1, 2, 3, 1 in ascending order

Try your own input
2#0
3#1
1#2
2#3
3#4
1#5
CurrentDiscovered / computedAnswer
Comparisons
0
Swaps/writes
0

The small #i is each number’s starting index: if equal values end with their #i out of order, the sort is not stable.

InvariantAfter a partition the pivot is in its final place: smaller values left of it, the rest right.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 26, with it.

Python
def keep_at_most(nums: list[int], k: int) -> int:
    """Sorted nums: keep each value at most k times, in place. Returns the new length."""
    w = 0  # nums[:w] is the kept prefix
    for x in nums:
        if w < k or nums[w - k] != x:
            nums[w] = x
            w += 1
    return w
C++
// Sorted nums: keep each value at most k times, in place. Returns the new length.
int keepAtMost(vector<int>& nums, int k) {
    int w = 0;  // nums[0, w) is the kept prefix
    for (int x : nums)
        if (w < k || nums[w - k] != x) nums[w++] = x;
    return w;
}
Java
class Solution {
    // Sorted nums: keep each value at most k times, in place. Returns the new length.
    int keepAtMost(int[] nums, int k) {
        int w = 0; // nums[0, w) is the kept prefix
        for (int x : nums)
            if (w < k || nums[w - k] != x) nums[w++] = x;
        return w;
    }
}
Go
// keepAtMost keeps each value of sorted nums at most k times, in place,
// and returns the new length.
func keepAtMost(nums []int, k int) int {
	w := 0 // nums[:w] is the kept prefix
	for _, x := range nums {
		if w < k || nums[w-k] != x {
			nums[w] = x
			w++
		}
	}
	return w
}

Common variants

Problems at this stop also need the 3 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Three-pointer Dutch flag partitionO(n) time · O(1) space

When the array holds three kinds of values (0/1/2, or less / equal / greater than a pivot) to split into three runs in place: everything left of lo is 0, right of hi is 2, and i scans the middle. After swapping with hi, i stays put because the value it received is unchecked. LC 75 (Sort Colors) is this, and so is quicksort's three-way partition.

Python
def sort_colors(nums: list[int]) -> None:
    """Sorts 0s, 1s and 2s in place in one pass."""
    lo, i, hi = 0, 0, len(nums) - 1  # nums[:lo] are 0, nums[lo:i] are 1, nums[hi+1:] are 2
    while i <= hi:
        if nums[i] == 0:
            nums[lo], nums[i] = nums[i], nums[lo]
            lo += 1
            i += 1
        elif nums[i] == 2:
            nums[i], nums[hi] = nums[hi], nums[i]
            hi -= 1  # i stays: the value swapped in is not checked yet
        else:
            i += 1
C++
// Sorts 0s, 1s and 2s in place in one pass.
void sortColors(vector<int>& nums) {
    int lo = 0, i = 0, hi = (int)nums.size() - 1;  // [0, lo) are 0, [lo, i) are 1, (hi, n) are 2
    while (i <= hi) {
        if (nums[i] == 0) swap(nums[lo++], nums[i++]);
        else if (nums[i] == 2) swap(nums[i], nums[hi--]);  // i stays: the value swapped in is not checked yet
        else i++;
    }
}
Java
class Solution {
    // Sorts 0s, 1s and 2s in place in one pass.
    void sortColors(int[] nums) {
        int lo = 0, i = 0, hi = nums.length - 1; // [0, lo) are 0, [lo, i) are 1, (hi, n) are 2
        while (i <= hi) {
            if (nums[i] == 0) swap(nums, lo++, i++);
            else if (nums[i] == 2) swap(nums, i, hi--); // i stays: the value swapped in is not checked yet
            else i++;
        }
    }

    private void swap(int[] a, int i, int j) {
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
}
Go
// sortColors sorts 0s, 1s and 2s in place in one pass.
func sortColors(nums []int) {
	lo, i, hi := 0, 0, len(nums)-1 // [0, lo) are 0, [lo, i) are 1, (hi, n) are 2
	for i <= hi {
		switch nums[i] {
		case 0:
			nums[lo], nums[i] = nums[i], nums[lo]
			lo++
			i++
		case 2:
			nums[i], nums[hi] = nums[hi], nums[i]
			hi-- // i stays: the value swapped in is not checked yet
		default:
			i++
		}
	}
}
In-place hashing: swap value v to index v - 1O(n) time (each swap homes one value) · O(1) space

When values lie in 1..n and a missing or repeated number must be found with O(1) extra space: keep swapping each value into its home slot, then scan once; the first slot not holding its own value is the answer. LC 41 (First Missing Positive), LC 448, LC 442 and LC 645 share this shape.

Python
def first_missing_positive(nums: list[int]) -> int:
    """Smallest positive integer not in nums, in O(1) extra space."""
    n = len(nums)
    for i in range(n):
        # Swap nums[i] home to index v - 1 until it is out of range or already there.
        while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]:
            v = nums[i]
            nums[i], nums[v - 1] = nums[v - 1], v
    for i in range(n):
        if nums[i] != i + 1:
            return i + 1
    return n + 1
C++
// Smallest positive integer not in nums, in O(1) extra space.
int firstMissingPositive(vector<int>& nums) {
    int n = nums.size();
    for (int i = 0; i < n; i++)
        // Swap nums[i] home to index v - 1 until it is out of range or already there.
        while (nums[i] >= 1 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) swap(nums[i], nums[nums[i] - 1]);
    for (int i = 0; i < n; i++)
        if (nums[i] != i + 1) return i + 1;
    return n + 1;
}
Java
class Solution {
    // Smallest positive integer not in nums, in O(1) extra space.
    int firstMissingPositive(int[] nums) {
        int n = nums.length;
        for (int i = 0; i < n; i++)
            // Swap nums[i] home to index v - 1 until it is out of range or already there.
            while (nums[i] >= 1 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
                int v = nums[i];
                nums[i] = nums[v - 1];
                nums[v - 1] = v;
            }
        for (int i = 0; i < n; i++)
            if (nums[i] != i + 1) return i + 1;
        return n + 1;
    }
}
Go
// firstMissingPositive returns the smallest positive integer not in nums, in O(1) extra space.
func firstMissingPositive(nums []int) int {
	n := len(nums)
	for i := range nums {
		// Swap nums[i] home to index v - 1 until it is out of range or already there.
		for nums[i] >= 1 && nums[i] <= n && nums[nums[i]-1] != nums[i] {
			v := nums[i]
			nums[i], nums[v-1] = nums[v-1], v
		}
	}
	for i, v := range nums {
		if v != i+1 {
			return i + 1
		}
	}
	return n + 1
}
Kadane: best sum ending at the current elementO(n) time · O(1) space

For the largest-sum contiguous subarray (LC 53): keep only the best sum ending at the current element, which either extends the previous one or restarts at itself, and take the best seen. With all negatives the answer is the largest negative, so start from nums[0], not 0.

Python
def max_subarray(nums: list[int]) -> int:
    """Largest sum of a non-empty contiguous subarray."""
    best = cur = nums[0]  # cur: best sum of a subarray ending at the current element
    for x in nums[1:]:
        cur = max(x, cur + x)  # extend, or start over at x
        best = max(best, cur)
    return best
C++
// Largest sum of a non-empty contiguous subarray.
long long maxSubarray(const vector<int>& nums) {
    long long best = nums[0], cur = nums[0];  // cur: best sum of a subarray ending here
    for (size_t i = 1; i < nums.size(); i++) {
        cur = max<long long>(nums[i], cur + nums[i]);  // extend, or start over
        best = max(best, cur);
    }
    return best;
}
Java
class Solution {
    // Largest sum of a non-empty contiguous subarray.
    long maxSubarray(int[] nums) {
        long best = nums[0], cur = nums[0]; // cur: best sum of a subarray ending here
        for (int i = 1; i < nums.length; i++) {
            cur = Math.max(nums[i], cur + nums[i]); // extend, or start over
            best = Math.max(best, cur);
        }
        return best;
    }
}
Go
// maxSubarray returns the largest sum of a non-empty contiguous subarray.
func maxSubarray(nums []int) int {
	best, cur := nums[0], nums[0] // cur: best sum of a subarray ending here
	for _, x := range nums[1:] {
		cur = max(x, cur+x) // extend, or start over at x
		best = max(best, cur)
	}
	return best
}

Why it works

  1. Invariant: at the start of each step, nums[0..w) holds exactly the kept elements of the scanned part nums[0..r), in their original order. Keeping nums[r] writes it at w and advances w, so the invariant holds again; when r reaches the end, nums[0..w) is the answer.
  2. A write never destroys unread data: w ≤ r at all times, so every write lands on a cell that has already been read.
  3. Merging from the back: the write index is k = i + j + 1, so while nums2 still has elements (j ≥ 0), k > i and the unread part of nums1 is never overwritten.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
这类题我用读写双指针。读指针 r 从左到右扫一遍,写指针 w 左边永远是已经确定的结果。遇到要保留的元素就写到 w 再右移 w,因为 w 不会超过 r,所以不会覆盖还没读的数据。整体一遍扫描,时间 O(n),额外空间 O(1)。
English
I use a read pointer and a write pointer. The read pointer scans left to right once, and everything left of the write pointer is final. When an element should be kept, I copy it to the write position and advance it; since the write pointer never passes the read pointer, nothing unread is overwritten. That is one pass, O(n) time and O(1) extra space.

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

5 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

5 questions
  1. Inserting one element at index 0 of a dynamic array (such as a Python list) holding n elements costs?
  2. Why does a dynamic array grow by a constant factor (say, doubling its capacity) instead of by a fixed amount (say, 100 more slots)?
  3. What is the time complexity of this code (n = len(a), tightest bound)?
    def reverse_copy(a):
        out = []
        for x in a:
            out.insert(0, x)
        return out
  4. What is the time complexity of this code (tightest bound)?
    def build(n):
        a = []
        for i in range(n):
            a.append(i)
        return a
  5. What is the time complexity of this code (n = len(a), tightest bound)?
    def normalize(a):
        return [x / max(a) for x in a]

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

Practice by stage

This stop's 20 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Foundation 7

#ProblemApproachRating
26Remove Duplicates from Sorted ArrayMaintain a deduplicated prefix with read and write pointers, and distinguish the returned length from the valid range.
27Remove ElementCompare overwriting and swapping with the last element when deletion need not preserve order.
88Merge Sorted ArrayMerge two sorted arrays from the back to avoid overwriting unread values.
283Move ZeroesCompact nonzero values stably, then fill the tail; distinguish stability from extra-space requirements.
350Intersection of Two Arrays IICompare frequency hashing with sorting and two pointers for multiset intersection, retaining multiplicities.
169Majority ElementIdentify a majority element by cancellation and explain the assumption that a majority exists.
645Set MismatchLocate one repeated value and one missing value using frequencies or in-place marking.

Core 10

#ProblemApproachRating
80Remove Duplicates from Sorted Array IIExtend deduplication to keep at most two copies of each value while maintaining the write-pointer invariant.
75Sort ColorsMaintain contiguous regions below, equal to, and above the pivot with three-way partitioning.
48Rotate ImageRotate in place through transposition and reversal, checking the mapping between row and column indices.
229Majority Element IIExtend majority voting and verify the candidates in a second pass; candidates are not automatically answers.
238Product of Array Except SelfSeparate prefix and suffix products to avoid division, including when the input contains zeros.
448Find All Numbers Disappeared in an ArrayUse the correspondence between values and indices to mark presence in place.
442Find All Duplicates in an ArrayDetect duplicates through in-place sign marking and explain what revisiting a position means.
912Sort an ArrayImplement a reliable sort and compare merge sort and quicksort in stability, space use, and worst-case complexity.
334Increasing Triplet SubsequenceMaintain the smallest one-element and two-element candidates to detect an increasing triplet online.
53Maximum SubarraySubtract the smallest earlier prefix sum to find the maximum subarray, including all-negative input.

Advanced 3

#ProblemApproachRating
41First Missing PositivePlace positive integers at their corresponding positions to find the first missing value in constant extra space.
287Find the Duplicate NumberView array mappings as a functional graph and find the duplicate with slow and fast pointers without modifying the array.
324Wiggle Sort IICombine median partitioning with virtual indexing to construct a strict alternating arrangement.

Core Skills

Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.