Course outline

Data Structures & Algorithms / Contracts, sequences, and search / Lesson 7

Two pointers on a sorted array

Find a pair with a target sum using a shrinking interval and prove why each discarded boundary is safe.

About 21 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • State the sorted-input and distinct-index contract.
  • Explain the pointer movement invariant.
  • Test duplicates, absence, and empty input.
  • Prove endpoint elimination and termination for a sorted distinct-index pair search.
  • Validate pair results and account for preparation, duplicate policy, and output costs.

Define the problem

Given numbers sorted in nondecreasing order, find two distinct indices whose values add to a target, or return None if no pair exists. This version returns one valid pair, not every pair or a particular duplicate. The sorted precondition matters: pointer movement uses the ordering to discard impossible candidates. If input is not sorted, either reject it or sort a copy while retaining any original-index mapping required by the caller.

Shrink the candidate interval

Start at both ends. If the sum is too small, pairing the left value with any remaining value cannot reach the target, because the right value is the largest remaining candidate; advance left. If the sum is too large, pairing the right value with any remaining value cannot reach the target; decrease right. When the sum matches, return the two distinct indices. The interval shrinks on every non-returning iteration.

python Search with two pointers
def pair_sum_sorted(values, target):
    left, right = 0, len(values) - 1
    while left < right:
        total = values[left] + values[right]
        if total == target:
            return (left, right)
        if total < target:
            left += 1
        else:
            right -= 1
    return None

Each movement removes a boundary that cannot participate in a remaining solution.

Check boundary examples

The assertions use the function from the first block in the same Python file. They cover a match, an absent target, an empty array, and equal values at two different indices. A single element cannot supply two distinct indices. If a contract asks for all pairs or original positions after sorting, this function is insufficient and needs a different output and duplicate policy.

python Check representative cases
assert pair_sum_sorted([1, 2, 4, 7], 6) == (1, 2)
assert pair_sum_sorted([1, 2, 4, 7], 20) is None
assert pair_sum_sorted([], 6) is None
assert pair_sum_sorted([3, 3], 6) == (0, 1)

The cases exercise absence, empty input, and equal values at distinct indices.

Reason about cost

Each pointer moves inward at most the length of the array, so the search uses linear time and constant auxiliary space for the given sorted input. Sorting an unsorted input has its own cost and may require extra storage or index tracking; do not omit that work from an end-to-end claim. Integer overflow behavior is language-dependent, so implementations in fixed-width languages should also choose a safe numeric policy.

Verify the invariant

For each iteration, verify that no discarded index can form an unexamined valid pair with the remaining interval. Compare the result with a simple quadratic reference on small sorted arrays, including duplicates and negative values. Assert that returned indices are distinct, in range, and sum to the target; when None is returned, verify that the reference finds no pair. Test the sorting precondition separately.

Define the pair and the ordering

The basic problem receives a nondecreasing sequence and a target and returns one pair of distinct indices whose values sum to the target, or None when no pair exists. The two indices refer to the supplied sorted sequence. Equal values can form a valid pair if they occur at different positions; a single element cannot be used twice. A find-one contract does not promise every pair, a lexicographically minimal pair, or a specific duplicate unless those requirements are separately specified and proved.

Sortedness is a precondition for the elimination argument. If a caller supplies an unsorted list, the API must reject it or use another design; sorting a copy changes index positions unless original indices are retained with values. A validation scan costs O(n) under a bounded-comparison model and is separate from the search itself. Specify numeric types and overflow policy for the implementation language. Python 3.12 integers have arbitrary precision, while a fixed-width implementation must avoid or handle overflow when adding endpoints. Define input mutation and absence behavior explicitly.

Justify each discarded endpoint

Initialize left = 0 and right = n - 1, and continue only while left < right. The candidate interval is inclusive at both ends. For a sorted sequence, if values[left] + values[right] is too small, values[right] is the largest remaining partner for left; every other remaining partner gives a sum no larger, so left cannot participate in a remaining solution and can advance. If the sum is too large, values[left] is the smallest remaining partner for right; every other remaining partner gives a sum no smaller, so right can retreat.

The invariant is that any not-yet-excluded solution lies entirely within the current candidate interval. Each non-returning iteration discards a boundary only after proving it cannot participate in a remaining solution. The distance right - left strictly decreases, providing termination. When left >= right no two distinct positions remain, so None follows if no match was returned. This proof depends on nondecreasing order and the current interval; moving a pointer in the opposite direction can discard a valid pair. Test the branch and invariant together rather than memorizing movements.

Duplicates and output policies

Duplicates do not invalidate the sorted-order proof. In [3, 3] with target 6, indices 0 and 1 are distinct even though their values are equal. In [3] the loop never has two indices, so None is correct under the distinct-position contract. An empty sequence starts with right = -1 and also terminates without indexing. A target outside the possible sum range may require several pointer moves before the interval closes; do not claim a particular returned pair when the contract allows more than one.

Counting or returning all pairs changes the problem. With repeated values, skipping duplicates may preserve unique value pairs but lose distinct positional pairs. Decide which identity matters and account for output size, which may be quadratic. If sorting an unsorted input is permitted, keep (value, original_index) pairs and define how ties and output order are handled. Verify each returned index is in bounds, distinct, and maps to the intended original input; sorting alone does not preserve original positions. A correct find-one algorithm cannot be advertised as an all-pairs solution without new bookkeeping and proof.

Count movements and preparation

For already sorted random-access input of length n, each non-returning iteration moves one endpoint inward, so at most O(n) iterations occur and the iterative search uses O(1) auxiliary variables. This assumes bounded-cost indexing, addition, and comparison. Python’s arbitrary-size integers can require bit-cost accounting for unusually large values; a different representation may have different access costs. Returning one pair has constant-size output, whereas returning all positional pairs can require quadratic output space.

Include precondition validation, sorting, index mapping, and any output construction in an end-to-end cost claim. Sorting a copy commonly costs O(n log n) comparisons and requires additional storage, so an O(n) search phase does not make the whole operation linear from arbitrary input. A quadratic brute-force reference can still be useful for small tests because its simpler enumeration is independent of the elimination strategy. These operation models are not measured execution times; workload and implementation details matter for empirical performance.

Test the proof and contract separately

A differential test can enumerate small sorted arrays including duplicates and negative values, compare whether a candidate finds a pair with a simple i < j reference, and validate any returned pair. Check both indices are distinct and in bounds and their values sum to the target. When multiple pairs are valid, do not require an arbitrary exact pair unless the API promises its selection policy. When None is returned, ensure the reference finds no pair. Test empty and singleton arrays and a value equal to half the target explicitly.

A bounded test can reveal an error but does not prove the general invariant or termination. Trace too-small and too-large cases and show the excluded endpoint cannot participate with any remaining partner. Check sortedness and original-index mapping as separate API obligations. Preserve the original input if the contract forbids mutation. The course baseline is Python 3.12 and standard-library operations. The synthetic traces below are illustrative and unexecuted in this environment; no benchmark or tool output is claimed.

20 worked examples

1. Empty input

Problem: Determine the result without indexing an empty sequence.

  1. left is not less than right at initialization.
  2. The loop does not execute and returns None.
text Empty input
values = []; target = 4
left = 0; right = -1

left is not less than right at initialization. The loop does not execute and returns None. This synthetic trace was not executed.

Expected result: result = None

Why this result follows: No two distinct positions exist in the empty input.

2. Singleton half-target

Problem: Determine whether one value can form a pair.

  1. The only index is both endpoints.
  2. left < right is false, so it cannot be used twice.
text Singleton half-target
values = [3]; target = 6
left = 0; right = 0

The only index is both endpoints. left < right is false, so it cannot be used twice. This synthetic trace was not executed.

Expected result: result = None

Why this result follows: The contract requires two distinct positions.

3. Equal values, distinct indices

Problem: Determine the pair in this duplicate fixture.

  1. The endpoint values sum to six.
  2. Their indices zero and one are different.
text Equal values, distinct indices
values = [3, 3]; target = 6
left = 0; right = 1

The endpoint values sum to six. Their indices zero and one are different. This synthetic trace was not executed.

Expected result: result = (0, 1)

Why this result follows: Equal values may satisfy a distinct-position contract.

4. Too-large endpoint sum

Problem: Determine the first pointer movement.

  1. The endpoint sum eight is above the target six.
  2. The right value paired with any remaining value is at least eight.
text Too-large endpoint sum
values = [1, 2, 4, 7]; target = 6
left = 0; right = 3; sum = 8

The endpoint sum eight is above the target six. The right value paired with any remaining value is at least eight. This synthetic trace was not executed.

Expected result: right becomes 2

Why this result follows: Sortedness justifies discarding the current right endpoint.

5. Too-small endpoint sum

Problem: Determine the next movement in this candidate interval.

  1. The endpoint sum five is below six.
  2. No remaining partner larger than values[2] exists in the interval.
text Too-small endpoint sum
values = [1, 2, 4, 7]; target = 6
left = 0; right = 2; sum = 5

The endpoint sum five is below six. No remaining partner larger than values[2] exists in the interval. This synthetic trace was not executed.

Expected result: left becomes 1

Why this result follows: The current left endpoint cannot form a remaining solution.

6. Matching endpoints

Problem: Determine the returned pair in this interval.

  1. Values two and four sum to six.
  2. Indices one and two are distinct and in bounds.
text Matching endpoints
values = [1, 2, 4, 7]; target = 6
left = 1; right = 2; sum = 6

Values two and four sum to six. Indices one and two are distinct and in bounds. This synthetic trace was not executed.

Expected result: result = (1, 2)

Why this result follows: A matching pair satisfies the find-one contract.

7. Negative and positive

Problem: Determine the endpoint pair with a negative value.

  1. The endpoint values are negative five and six.
  2. Their sum is one at distinct positions zero and three.
text Negative and positive
values = [-5, -1, 2, 6]; target = 1
left = 0; right = 3; sum = 1

The endpoint values are negative five and six. Their sum is one at distinct positions zero and three. This synthetic trace was not executed.

Expected result: result = (0, 3)

Why this result follows: The sorted elimination method does not require nonnegative values.

8. Too large with negatives

Problem: Determine the safe movement for this mixed-sign fixture.

  1. The endpoint sum one exceeds zero.
  2. The current right value cannot reach zero with a larger remaining partner.
text Too large with negatives
values = [-4, -1, 2, 5]; target = 0
left = 0; right = 3; sum = 1

The endpoint sum one exceeds zero. The current right value cannot reach zero with a larger remaining partner. This synthetic trace was not executed.

Expected result: right becomes 2

Why this result follows: The same ordered argument applies across negative values.

9. Duplicate zeros

Problem: Trace the move before finding two zero positions.

  1. The first endpoint sum one is too large.
  2. Retreating right selects the second zero at a distinct index.
text Duplicate zeros
values = [0, 0, 1]; target = 0
left = 0; right = 2; sum = 1

The first endpoint sum one is too large. Retreating right selects the second zero at a distinct index. This synthetic trace was not executed.

Expected result: right becomes 1; then pair = (0, 1)

Why this result follows: Duplicate values remain valid distinct candidates.

10. Target too large

Problem: Trace the elimination until no pair remains.

  1. The first sum 1 + 7 is eight, so left advances.
  2. The next sum 4 + 7 is eleven, still too small; left meets right.
text Target too large
values = [1, 4, 7]; target = 20
endpoint sums along search: 8, 11

The first sum 1 + 7 is eight, so left advances. The next sum 4 + 7 is eleven, still too small; left meets right. This synthetic trace was not executed.

Expected result: result = None

Why this result follows: No two distinct candidates remain after safe exclusions.

11. Target too small

Problem: Trace the right boundary until the interval closes.

  1. The first sum eight exceeds zero, so right retreats.
  2. The next sum five also exceeds zero and right meets left.
text Target too small
values = [1, 4, 7]; target = 0
endpoint sums along search: 8, 5

The first sum eight exceeds zero, so right retreats. The next sum five also exceeds zero and right meets left. This synthetic trace was not executed.

Expected result: result = None

Why this result follows: Each excluded right endpoint is too large with all remaining partners.

12. Multiple valid pairs

Problem: Identify a permitted find-one result.

  1. Both endpoint values one and four sum to five.
  2. The interior values two and three also form a valid pair.
text Multiple valid pairs
values = [1, 2, 3, 4]; target = 5
valid pairs = [(0, 3), (1, 2)]

Both endpoint values one and four sum to five. The interior values two and three also form a valid pair. This synthetic trace was not executed.

Expected result: find-one may return (0, 3)

Why this result follows: A find-one result does not promise to enumerate all valid pairs.

13. All positional pairs

Problem: Count all distinct-position pairs for equal values.

  1. Every two different positions hold values summing to four.
  2. Three positions give three unordered pairs.
text All positional pairs
values = [2, 2, 2]; target = 4
indices = [0, 1, 2]

Every two different positions hold values summing to four. Three positions give three unordered pairs. This synthetic trace was not executed.

Expected result: all positional pairs = [(0, 1), (0, 2), (1, 2)]

Why this result follows: Skipping equal values can lose positional multiplicity.

14. Preserve original positions

Problem: Map a sorted endpoint match back to the source.

  1. Sorted endpoint values one and seven sum to eight.
  2. Their retained original indices are one and zero.
text Preserve original positions
original = [7, 1, 4]
sorted value-index pairs = [(1, 1), (4, 2), (7, 0)]
target = 8

Sorted endpoint values one and seven sum to eight. Their retained original indices are one and zero. This synthetic trace was not executed.

Expected result: original indices = (1, 0)

Why this result follows: Value-index pairs preserve the requested original-position meaning.

15. Unsorted input

Problem: Determine whether the elimination proof applies here.

  1. The first value seven is followed by smaller one.
  2. The input is not nondecreasing.
text Unsorted input
values = [7, 1, 4]
target = 8
precondition: nondecreasing input

The first value seven is followed by smaller one. The input is not nondecreasing. This synthetic trace was not executed.

Expected result: precondition fails

Why this result follows: A successful-looking trace cannot replace the sorting precondition.

16. Validate a returned pair

Problem: Check indices and sum for this fixture.

  1. Indices zero and two are distinct and in bounds.
  2. Their values one and five sum to six.
text Validate a returned pair
values = [1, 3, 5]
target = 6
returned pair = (0, 2)

Indices zero and two are distinct and in bounds. Their values one and five sum to six. This synthetic trace was not executed.

Expected result: pair is valid

Why this result follows: All parts of the returned-pair contract are satisfied.

17. Reject self-pair

Problem: Classify the proposed pair despite its sum.

  1. The values at index one sum to six if reused.
  2. The two indices are equal, violating distinctness.
text Reject self-pair
values = [1, 3, 5]
target = 6
returned pair = (1, 1)

The values at index one sum to six if reused. The two indices are equal, violating distinctness. This synthetic trace was not executed.

Expected result: pair is invalid

Why this result follows: A correct sum alone does not establish a valid pair.

18. Progress measure

Problem: Calculate the candidate distance after one move.

  1. Initially right - left is four minus one, or three.
  2. Advancing left once makes the distance two.
text Progress measure
candidate interval: left = 1, right = 4
non-returning step: left += 1

Initially right - left is four minus one, or three. Advancing left once makes the distance two. This synthetic trace was not executed.

Expected result: distance decreases from 3 to 2

Why this result follows: Each inward move strictly decreases the finite interval.

19. Brute-force reference

Problem: Determine whether a direct positional oracle finds a solution.

  1. The distinct positions zero and two contain one and four.
  2. Their sum equals five.
text Brute-force reference
values = [1, 2, 4]
target = 5
reference pairs = [(0, 2)]

The distinct positions zero and two contain one and four. Their sum equals five. This synthetic trace was not executed.

Expected result: reference finds a pair

Why this result follows: A simple i < j oracle can check candidate existence.

20. Movement cost model

Problem: Classify the search phase under stated assumptions.

  1. The finite distance between endpoints decreases on each non-returning step.
  2. Only a constant number of pointer and total variables are retained.
text Movement cost model
n = 5 sorted values
model: each non-returning step moves one endpoint inward

The finite distance between endpoints decreases on each non-returning step. Only a constant number of pointer and total variables are retained. This synthetic trace was not executed.

Expected result: at most O(n) search iterations; O(1) auxiliary variables

Why this result follows: The claim excludes sorting, validation, and materialized output.

Common errors and fixes

A valid pair is skipped

Why it happens
The pointer moved in the wrong direction for the current sum.
How to fix it
Derive movement from the sorted-order invariant.
Prevent it next time
Trace a small example and compare with a brute-force reference.

One element is used twice

Why it happens
The loop permits left and right to be the same index.
How to fix it
Require left < right for a distinct-index pair.
Prevent it next time
Test a one-element array whose doubled value equals the target.

Original positions are reported incorrectly

Why it happens
The input was sorted without preserving original indices.
How to fix it
Retain value-index pairs or change the documented output.
Prevent it next time
Test an unsorted fixture with known original positions.

20 practice exercises

1. Find a pair summing to 6 in [1, 2, 4, 7].

Show hint

Compare the endpoint sum to six before each move.

Show worked solution

The endpoints sum to 8, so move the right pointer left. Values 2 and 4 then sum to 6 at indices 1 and 2 after advancing the left pointer from 1 when needed; the returned indices are distinct.

The first endpoints 1 and 7 sum to 8, so move right to index 2. The sum 1 + 4 = 5 is too small, so move left to index 1; 2 + 4 = 6 gives the distinct pair (1, 2).

Check your solution

  • The moves are right then left
  • The returned pair is (1, 2)

2. Why can the left endpoint be discarded when its sum with the right endpoint is too small?

Show hint

Use the largest remaining partner for the current left value.

Show worked solution

The right endpoint is the largest remaining value. Pairing the left value with any other remaining value cannot produce a larger sum, so none can reach the target.

If left plus right is too small, every other remaining partner is at most the right value because the input is sorted. None can raise that left value’s sum to the target, so discarding left preserves every remaining possible solution.

Check your solution

  • The right value bounds remaining partners above
  • The discarded left endpoint cannot form a remaining solution

3. Prove both endpoint movements for sorted [1, 3, 5, 9]: target 15 at the first step, then target 6 at the first step.

Show hint

Compare each endpoint with every remaining partner.

Show worked solution

For target 15, 1 + 9 = 10 is too small, so 1 cannot pair with any remaining value and left advances. For target 6, the same sum is too large, so 9 cannot pair with any remaining value and right retreats.

Check your solution

  • Target 15 advances left
  • Target 6 retreats right

4. Write a find-one pair contract specifying input order, distinctness, absence, and whether the source is mutated.

Show hint

A result contract must include preconditions.

Show worked solution

Require a stable nondecreasing sequence, return two distinct in-bounds indices whose values sum to the target, or None if none exist, and leave input unchanged. Do not promise a particular pair among several unless separately defined.

Check your solution

  • Sortedness and distinct indices are specified
  • Absence and mutation behavior are specified

5. A sorted pair search receives [1,2,6,9] and target 8. Verify that returned indices (0,3) are incorrect without running the search.

Show hint

Check both the bounds and the sum.

Show worked solution

Both indices are in range and distinct, but their values sum to 1+9=10, not 8. A valid alternative is indices (1,2), whose values 2+6 equal 8.

Check your solution

  • The proposed sum is 10.
  • A valid alternative is (1,2).

6. Find a three-value sum of 9 in sorted [1,2,3,4] by fixing one index and searching the remaining suffix.

Show hint

Fix 2 and seek a pair totaling 7.

Show worked solution

Fix the value 2 at index 1; the remaining distinct indices 2 and 3 hold 3 and 4, whose sum is 7. Together the values 2,3,4 sum to 9, without reusing the fixed index.

Check your solution

  • The chosen indices are 1,2,3.
  • The total is 9.

7. A candidate returns (0, 3) for [1, 2, 4] and target 5. Identify every relevant validity check and classify it.

Show hint

Check bounds before indexing.

Show worked solution

Index 3 is outside the three-element array, so reject the pair before reading it. A valid result must also use distinct indices and sum to the target; an out-of-bounds pair cannot satisfy the full contract.

Check your solution

  • Index 3 is out of bounds
  • The candidate pair is invalid

8. For original [4,1,4] and target 8, preserve original indices while searching a sorted copy.

Show hint

Equal values may still have different original positions.

Show worked solution

Sort value-index pairs to [(1,1),(4,0),(4,2)]. The two 4 values use distinct original indices 0 and 2, giving a valid target-8 pair even though their values are equal.

Check your solution

  • The original indices are 0 and 2.
  • The two occurrences sum to 8.

9. For [1,1,2,2] and target 3, compare unique value pairs with all positional pairs.

Show hint

Every 1 occurrence can pair with every 2 occurrence.

Show worked solution

There is one unique value pair (1,2), but two choices of 1 and two choices of 2 give four distinct positional pairs. Deduplicating by values therefore loses multiplicity required by the second contract.

Check your solution

  • The unique value-pair count is one.
  • The positional-pair count is four.

10. Count all positional pairs summing to 2 in sorted [0,1,1,2,2]. Separate equal and unequal runs.

Show hint

Count 0–2 cross-pairs and the 1–1 pair.

Show worked solution

The single zero pairs with each of two twos, giving two pairs. The two ones form one distinct-position pair, so the total is three; counting only distinct value pairs would give two.

Check your solution

  • The 0–2 runs contribute two pairs.
  • The total positional count is three.

11. A search moves right inward when its endpoint sum is too small. Use [1, 2, 5, 8] and target 10 to show the risk and repair the rule.

Show hint

The right endpoint is already the largest remaining partner.

Show worked solution

The endpoints sum to 9, below 10. Moving right discards 8 and misses the valid pair 2 + 8; advance left instead because the current 1 cannot reach 10 with any remaining partner.

Check your solution

  • The valid pair is 2 + 8
  • A too-small sum advances left

12. Give an unsorted input where moving a pointer using sorted-order reasoning can miss a valid pair, and explain the invalid assumption.

Show hint

The right endpoint need not be the largest value.

Show worked solution

For [1, 8, 2] with target 9, the first endpoint sum is 3 and a sorted-input rule advances left, discarding 1 even though 1 + 8 is valid. The right endpoint was not the largest remaining value.

Check your solution

  • The valid pair is at indices 0 and 1
  • The sortedness precondition fails

13. For candidate endpoints left = 2 and right = 6, show how each non-returning branch changes the termination measure.

Show hint

Use right - left.

Show worked solution

The initial distance is 4. Advancing left to 3 or retreating right to 5 makes it 3, so either non-returning branch decreases the finite measure by one.

Check your solution

  • The initial distance is 4
  • Either move decreases it to 3

14. Compare the modeled search work of two pointers and brute force on sorted n-element input, and identify their different roles in testing.

Show hint

Count endpoint moves versus positional pairs.

Show worked solution

Two pointers uses O(n) endpoint iterations under bounded-cost random access; brute force checks up to n(n-1)/2 pairs, O(n²). The slower enumeration can serve as a simple reference on small inputs.

Check your solution

  • The candidate search is O(n)
  • The reference can check O(n²) pairs

15. A service sorts a copy before each single query. Explain why the search phase’s O(n) cost is not the entire cost.

Show hint

Include sorting and copied index records.

Show worked solution

The operation also creates and sorts value-index pairs, typically O(n log n) comparisons plus additional storage, before the O(n) scan. Measure the actual workload and reuse policy rather than claiming a linear end-to-end operation.

Check your solution

  • Sorting and mapping costs are included
  • The O(n) scan is only one phase

16. A fixed-width implementation adds two large endpoint integers. Explain the safety concern and a suitable policy.

Show hint

The addition can overflow before comparison.

Show worked solution

The endpoint sum may be unrepresentable even when both operands are valid. Use checked or sufficiently wider arithmetic with documented bounds, and handle failure; Python’s arbitrary-size integer behavior should not be assumed in another language.

Check your solution

  • Addition is checked or bounded
  • Overflow behavior is documented

17. A caller requires the original sorted input unchanged. Describe how to test a candidate implementation for this property.

Show hint

Save a separate reference copy before the call.

Show worked solution

Copy the input fixture before calling the candidate, then assert the original list still equals the copy after both success and None paths. This checks the mutation contract independently of pair validity.

Check your solution

  • Input is unchanged after success
  • Input is unchanged after absence

18. Design a bounded differential test for the find-one search that allows any valid pair.

Show hint

Compare existence against an i < j oracle.

Show worked solution

Enumerate short nondecreasing arrays with negatives and duplicates and targets in a small range. Compare None versus reference existence; for any returned pair verify distinct in-bounds indices and target sum rather than demanding one arbitrary pair.

Check your solution

  • Existence matches the reference
  • Every returned pair is valid

19. A test expects exactly (1, 2) but the API promises any valid pair and returns (0, 3) for [1, 2, 3, 4], target 5. Evaluate the test.

Show hint

Check the returned pair against the actual contract.

Show worked solution

Both pairs are distinct in-bounds positions summing to 5. The exact-pair assertion is too restrictive unless the API promises a selection policy; assert validity and existence instead.

Check your solution

  • The returned pair is valid
  • The test does not invent an ordering promise

20. A public API validates sortedness before searching. State the overall worst-case work under a unit-cost array model and explain why.

Show hint

Include the validation pass.

Show worked solution

Validation scans up to n elements and the two-pointer search moves at most O(n) steps. Their combined worst-case work is O(n), not just the cost of an individual pointer move; a validation error should be documented.

Check your solution

  • Validation and search are both O(n)
  • The full worst-case bound is O(n)

Key takeaways

  • Use sorted order to justify each pointer movement.
  • State output and duplicate policies and verify against a simple reference.
  • Sorted order justifies each inward pointer movement.
  • Equal values can form a pair only at distinct positions.
  • Find-one, all-pairs, and original-index contracts require different guarantees.

Official references