Skip to contentKEEP THE CRAFTTHE SANCTUARY

Same-direction Pointers

Separate a reader of source values from a writer of accepted values to compact a sequence without overwriting unread input. A trace of accepted runs and an in-place result have different output and memory contracts.

1 practice exercise5 interview problems

Recognize it when A sorted sequence must retain one representative of each adjacent equal-value run.

Checking your account…

Same-direction Pointers Code Labs

Preserve a Prefix While Reading Forward

Suppose a sorted list contains runs of equal values and the caller wants one value per run. Deleting duplicates during a forward scan shifts unread elements and complicates the cursor. Instead, keep the physical list length fixed and separate the next value to inspect from the next slot to fill.

Count Accepted Runs Before Moving Values

The trace Lab reports [read, write, value] after inspecting each value. Its write is the count of accepted runs; it does not itself mutate the list. A repeated neighbor leaves that count unchanged. This small model makes it possible to check decisions before combining them with assignments.

Trace Read and Write Pointers

Reference
def compact_trace(values):
    trace = []
    write = 0
    for read, value in enumerate(values):
        if read == 0 or value != values[read - 1]:
            write += 1
        trace.append([read, write, value])
    return trace
Practice

Implement compact_trace(values). values is sorted in nondecreasing order. Return [read, write, value] after each inspected value, where write counts accepted adjacent-value runs. This Lab records decisions and does not mutate or physically compact values.

Public tests

  • Trace the compacted prefix length

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Read and Write Pointers

def compact_trace(values):
    trace = []
    write = 0
    for read, value in enumerate(values):
        if read == 0 or value != values[read - 1]:
            write += 1
        trace.append([read, write, value])
    return trace

Watch the Writer Pause on a Duplicate

The adjacent trace Lab does not compact values physically. Its accepted-run counter on [2, 2, 5, 9] explains when an in-place writer would advance.

Step Executed statement State Why
Initialize write = 0 write=0, trace=[] No run has been accepted yet.
First value write += 1 read=0, value=2, write=1 The first value starts a run without reading a predecessor.
Repeated neighbor trace.append([read, write, value]) read=1, value=2, write=1 The equal predecessor means no additional run was accepted.
New run write += 1 read=2, value=5, write=2 5 differs from the previously read sorted value.
Another run trace.append([read, write, value]) read=3, value=9, write=3 The recorded count includes the run just accepted.
Return observations return trace [[0,1,2],[1,1,2],[2,2,5],[3,3,9]] The output records decisions, not a mutated prefix.
Print Output
print(compact_trace([2, 2, 5, 9])) [[0, 1, 2], [1, 1, 2], [2, 2, 5], [3, 3, 9]]

Write Only Behind the Reader

The compaction Lab writes an accepted value at values[write] and then advances write. The writer cannot pass the reader because at most one output value is accepted per source value. Overwriting a passed slot is safe; inserting or deleting would change which original value is read next. The returned length defines the answer, so a leftover duplicate in the physical suffix is not a failed compaction.

Compact Unique Values In Place

Reference
def compact_unique(values):
    write = 0
    for value in values:
        if write == 0 or values[write - 1] != value:
            values[write] = value
            write += 1
    return write
Practice

Implement compact_unique(values). Compact sorted values in place and return the new logical length.

Public tests

  • Preserve one copy in the prefix

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Compact Unique Values In Place

def compact_unique(values):
    write = 0
    for value in values:
        if write == 0 or values[write - 1] != value:
            values[write] = value
            write += 1
    return write

Decide Whether Sorted Adjacency Is Enough

Only sorted input guarantees that all equal values form one run. An unsorted sequence such as [2, 5, 2] has no equal neighbors but still contains a repeated value. Choose a seen set when global deduplication is required and extra memory is permitted. Choose a new list when preserving the input is more important than constant auxiliary space.

Explain Logical and Physical Lengths in an Interview

State the physical input length and the logical output length separately. One scan and constant assignments give O(n) time and O(1) working space for in-place compaction; collecting a trace or copying the result prefix adds output storage. Begin practice by predicting when write changes, then inspect only the returned prefix after executing the mutation Lab.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Read pointer and write pointer

Fast reads everything, slow writes the keepers.

You must remove or compact items in place and keep the order of the rest.

Trigger words

  • remove in place
  • remove duplicates from sorted
  • remove element
  • move zeroes
  • return the new length
def keep_non_zero(nums):
    write = 0
    for read in range(len(nums)):
        if nums[read] != 0:          # the knob: which items to keep
            nums[write] = nums[read]
            write += 1
    return write                     # nums[:write] holds the kept items

Spot it when

  • Remove duplicates or a value in place.
  • Move zeros to the end.
  • Return the new length.

Remember

  • write is always the next free slot; everything before it is final.
  • read moves every step, write moves only when you keep an item.

How problems bend it

  • Remove duplicates from a sorted array: Keep nums[read] when it differs from nums[write - 1].
  • Move zeros to the end: Swap nums[write] and nums[read] instead of copying.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Stable adjacent-run compactionO(n)O(n)Every source item is examined once and each accepted item causes one assignment.

Space

O(1) working space for compact_unique; compact_trace stores O(n) trace entries.

Assumptions

  • The in-place Lab returns a length; only the prefix before that length is valid output, and the remaining physical suffix is unspecified.
  • Python iteration over a list can observe mutations: these Labs overwrite earlier positions but never insert, delete or overwrite an unread position.

Invariants Worth Saying Aloud

  1. Before each source value, values[:write] contains exactly the accepted values from the processed source prefix.
  2. The write position never passes the source position; overwriting earlier slots leaves unread source values intact.

When To Use Or Avoid Same-direction Pointers

Use It When

  • Compact sorted duplicates while retaining the relative order of accepted values.
  • Filter in place when assignments to earlier positions cannot destroy unread values.

Choose Another Tool When

  • Use a new list when the caller forbids mutation or needs the original sequence afterward.
  • Use a set or a seen map for unsorted global deduplication; adjacent-run checks alone do not detect distant repeats.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Writing the previous accepted slot

A write frontier of 1 means slot 0 is already finalized. Writing a new value to write-1 destroys that value instead of extending the prefix.

Prevent it: Write at the next free slot, then increment write.

Avoid

values[write-1] = value
write += 1

Use instead

values[write] = value
write += 1

Treating the physical suffix as output

An in-place compaction can leave stale values after its returned length; printing the entire list reports duplicates that are outside the contract.

Prevent it: Use only values[:length] when materializing the result for display.

Avoid

result = values

Use instead

result = values[:length]

Deleting while moving a forward cursor

Deleting an equal item shifts the next equal item into the slot already passed by the cursor, leaving a duplicate behind.

Prevent it: Keep length fixed and use separate read/write positions. The shown new-list alternative avoids cursor shifts but allocates O(n) extra space; the recommended Lab keeps O(1) working space.

Avoid

for i in range(1,len(values)):
    if i < len(values) and values[i] == values[i-1]:
        del values[i]

Use instead

values[:] = [value for i,value in enumerate(values) if i == 0 or value != values[i-1]]

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.