Pattern Recognition — How to Spot Two Sum II in Interviews

Signals / keywords to listen for

  • "sorted array", "ascending order", "input array is sorted" — key signal for two-pointer approach.
  • "return indices" — means you must respect the 1-indexed requirement.
  • "exactly one solution exists" — allows early exit once the pair is found.
  • "constant extra space" — avoid hash maps; think O(1) space approaches.

Pattern Mapping Table

CluePattern / ApproachWhy it fits
Sorted input Two-pointer (left, right) Scan from both ends to find sum efficiently in O(n) time and O(1) space
Return 1-indexed indices Map left/right pointer to +1 positions Ensures indices align with problem requirement
Exact one solution Early exit when sum == target Optimizes loop; no need to continue
Need all pairs / variant Modified two-pointer with duplicate skipping Ensures no repeated pairs while keeping O(n) or O(n²) depending on output

ASCII Flow — Two-pointer Method

numbers: [2, 3, 4, 7, 11, 15]   target = 9
indices :  1  2  3  4   5   6   (1-indexed)

Initial pointers:
 l=0 (2)     r=5 (15) -> sum=17 >9 -> r--
 l=0 (2)     r=4 (11) -> sum=13 >9 -> r--
 l=0 (2)     r=3 (7)  -> sum=9 == target -> return [l+1, r+1] = [1,4]

Explanation:
- Left pointer starts at smallest number.
- Right pointer starts at largest number.
- Move pointers based on sum comparison:
   - sum < target → l++
   - sum > target → r--
- Found sum? Return indices immediately (early exit).
    

Comparison with Two Sum 1 (Unsorted)

FeatureTwo Sum 1 (Unsorted)Two Sum II (Sorted)
Array type Unsorted Sorted (ascending)
Indexing 0-indexed (typical) 1-indexed (LeetCode 167 requirement)
Optimal Approach One-pass hash map O(n) time, O(n) space Two-pointer O(n) time, O(1) space
Space Usage Extra O(n) for map Constant extra space
Pattern signal "two numbers sum to target", "return indices" "sorted array", "target sum", "constant space"

Interview Prompt — What to Ask

  • Is the array already sorted? → Yes, enables two-pointer.
  • Are indices 1-indexed or 0-indexed?
  • Exactly one solution or multiple pairs?
  • Are negative numbers or zeros allowed?

Key Takeaways for Pattern Recognition

  • Sorted arrays immediately hint **two-pointer** techniques.
  • Always check whether indices are 1-indexed — very common FAANG trap.
  • Early exit is allowed because exactly one solution exists.
  • Variants with duplicates or all pairs require slight modifications but follow same scanning logic.

Interview-Focused — Short Answer to Deliver (Two Sum II)

"Start by stating brute-force checks all pairs (O(n²)) for correctness. Then mention the optimized two-pointer approach: initialize left and right, compute sum = nums[left] + nums[right]. Move pointers toward each other based on sum comparison. Return the first valid pair. This achieves O(n) time and O(1) space. Mention handling of duplicates, minimal array size, negatives, and confirm sorted input."

One-minute checklist to say

  • Restate problem and confirm constraints (sorted, indices, duplicates).
  • Explain why brute-force is slow (O(n²)).
  • Explain two-pointer approach, pointer movements, and early return.
  • Do a dry-run on a sample array (e.g., [2,7,11,15], target=9).
  • Mention edge cases and potential follow-ups: duplicates, negatives, multiple pairs.
  • Highlight O(n) time and O(1) space efficiency.

Interview Script & What to Say (Two Sum II — Sorted Array)

Step-by-step script (word-for-word suggestions)

  1. "I'll restate the problem: given a sorted array nums and target, return the 1-indexed positions of two numbers that sum to target. Are duplicates possible and do I return the first valid pair?"
  2. "Since the array is sorted, a brute-force approach of checking all pairs is O(n²). It's correct but not optimal for large inputs."
  3. "A better approach is two-pointer. Initialize left=0, right=nums.length-1. Compute sum = nums[left] + nums[right]. If sum == target, return [left+1, right+1]. If sum < target, move left++. If sum > target, move right--. This runs in O(n) time and O(1) space."
  4. Dry-run a small example out loud: nums=[2,7,11,15], target=9.
  5. "Edge cases: minimal array size (2), duplicates, negatives, and multiple valid pairs. Always confirm array is sorted before assuming two-pointer."

What the interviewer hears

  • Clear problem restatement and constraints check.
  • Recognition of input properties (sorted array) and optimal approach.
  • Ability to communicate pointer movement strategy, dry run, and early exit.
  • Consideration of edge cases and follow-up questions.

Solution Approach — Two Sum II (step-by-step, beginner-friendly)

Step 0: Clarify Constraints

Before coding, confirm the following:

  • Array is sorted in ascending order (Two Sum II requirement).
  • Return 1-indexed positions of the two numbers.
  • Exactly one solution exists.
  • Do we need to use constant extra space? (Yes, aim for O(1) space using two-pointer).

Step 1: Two-Pointer Method (Optimal)

Use two pointers: left starting at 0, right starting at n-1. Check the sum:

  • If sum == target, return [left+1, right+1].
  • If sum < target, increment left to increase sum.
  • If sum > target, decrement right to decrease sum.
  • Stop as soon as the sum equals target (early exit guaranteed).

Annotated JavaScript — Two-pointer (O(n) time, O(1) space)

JavaScript — Two-pointer approach

function twoSumSorted(numbers, target) {
  let left = 0;
  let right = numbers.length - 1;

  while (left < right) {
    const sum = numbers[left] + numbers[right];
    if (sum === target) {
      // return 1-indexed positions as required
      return [left + 1, right + 1];
    } else if (sum < target) {
      left++;  // need larger sum
    } else {
      right--; // need smaller sum
    }
  }

  return []; // per constraints, should never reach here
}
    

Step 2: Dry-run (ASCII Flow, beginner-friendly)

Example: numbers = [2,3,4,7,11,15], target = 9

Initial pointers:
l=0 (2)      r=5 (15) -> sum=17 >9 -> r--
l=0 (2)      r=4 (11) -> sum=13 >9 -> r--
l=0 (2)      r=3 (7)  -> sum=9 == target -> return [1,4]

Step by step:
1. sum = 2+15=17 > 9 → decrement right
2. sum = 2+11=13 > 9 → decrement right
3. sum = 2+7 =9 == target → return indices (1-indexed)
    

Step 3: Handling Edge Cases

  • Minimal size: numbers.length == 2 → always valid; early exit.
  • Negative numbers: works because sum comparison still valid.
  • Duplicates: two-pointer naturally handles duplicates without extra checks.
  • Zeros: sum comparisons handle zero naturally.

Step 4: Complexity Analysis

MetricValueReasoning
Time O(n) Each pointer moves at most n steps; total iterations ≤ n
Space O(1) No extra data structures; only two pointers and a sum variable

Step 5: Interview Notes & What to Say

  • "Array is sorted, so I can use two-pointer technique for O(n) time and O(1) extra space."
  • "Initialize left and right pointers at both ends. Move pointers based on sum comparison."
  • "Early exit is allowed because exactly one solution exists."
  • "Edge cases: minimal size, zeros, negatives, duplicates are naturally handled."
  • Optional: compare with Two Sum 1 — uses hash map, O(n) time but O(n) space.

Key Takeaways

  • Sorted array → always think two-pointer.
  • O(1) space is achievable with two-pointer; no map needed.
  • Dry-run small examples with ASCII flow during interview to communicate clearly.
  • Always return indices as required (1-indexed for LeetCode 167).

Deep Dive — Two Sum II (in-depth reasoning for interviews)

Correctness invariant (pointer logic)

At any point during iteration:

  • left points to the smallest unused element in the sorted array.
  • right points to the largest unused element in the sorted array.
  • Sum = numbers[left] + numbers[right]. Invariant: If sum < target → all sums with current left and any index < right are smaller → safe to increment left. If sum > target → all sums with current right and any index > left are larger → safe to decrement right.
  • When sum == target, the pair [left, right] is guaranteed correct because the array is sorted and exactly one solution exists.

ASCII Flow for Pointer Invariant

numbers = [2,3,4,7,11,15], target = 9

Initial:
l=0 (2), r=5 (15) -> sum=17 > 9 → decrement r
l=0 (2), r=4 (11) -> sum=13 > 9 → decrement r
l=0 (2), r=3 (7)  -> sum=9 == target → solution found

Invariant reasoning:
- left always points to candidate for smaller sum
- right always points to candidate for larger sum
- sum comparison safely moves pointers without missing any pair
  

Variants & trade-offs (what interviewers may ask)

  • Return all pairs: Two-pointer still works; skip duplicates by incrementing/decrementing while same value occurs.
  • Memory-constrained: Two-pointer is O(1) space vs hash-map O(n) (Two Sum 1).
  • Streaming input: Cannot apply two-pointer directly because array is sorted and fully available. Hash-map approach may be needed for incremental processing.
  • Indices requirement: LeetCode 167 is 1-indexed; remember to add +1 when returning values.

Micro-optimizations you can mention

  • Early exit as soon as sum == target; no need to continue iteration.
  • Pointer comparison uses < instead of <= to avoid unnecessary checks.
  • In JavaScript, avoid repeated array accesses: store numbers[left] and numbers[right] in variables before sum computation if in hot loops.
  • Optionally compare performance with hash-map approach: O(n) time + O(n) space vs O(n) time + O(1) space.

Proof Sketch (why two-pointer always finds correct pair)

  1. Array is sorted: numbers[0] ≤ numbers[1] ≤ ... ≤ numbers[n-1].
  2. left starts at 0, right starts at n-1; all sums between left < right are checked implicitly by pointer moves.
  3. Sum < target → left++ → all smaller values with current right cannot form target, safe to move left.
  4. Sum > target → right-- → all larger values with current left cannot form target, safe to move right.
  5. When sum == target → immediately return indices. By sorting and single-pass pointer movement, no valid pair is skipped.

Comparison: Two Sum I vs Two Sum II

AspectTwo Sum ITwo Sum II (sorted)
InputUnsortedSorted
MethodOne-pass hash mapTwo-pointer
TimeO(n)O(n)
SpaceO(n)O(1)
Indices0-indexed1-indexed (per LeetCode 167)
Edge case handlingDuplicates, negatives, zerosDuplicates handled naturally; negatives/zeros work

Key Takeaways for Interviews

  • Pointer invariant reasoning shows correctness; explain clearly.
  • Two-pointer is optimal for sorted arrays (O(n) time, O(1) space).
  • Edge cases naturally handled, early exit possible.
  • Be ready to compare with hash-map approach for unsorted array variant.

Common Pitfalls — Two Sum II (and how to explain fixes in interview)

Pitfall Why it fails How to explain fix in interview
Off-by-one errors with 1-indexed result Returning 0-indexed array leads to wrong answer on LeetCode 167 Always add +1 to left and right when returning indices; explain to interviewer.
Moving pointers incorrectly (left++ or right--) Sum comparison not properly implemented → may skip valid pair or run into infinite loop Explain invariant: sum < target → left++, sum > target → right--; sum == target → return indices.
Confusing duplicates handling Increment/decrement pointers incorrectly → may double-count or miss duplicates Explain that for Two Sum II returning first correct pair, duplicates naturally handled; for “all pairs” variant, skip repeated values while moving pointers.
Comparing with Two Sum I hash-map approach incorrectly Using O(n) space hash-map on sorted array wastes memory; unnecessary complexity Explain why two-pointer is optimal for sorted arrays: O(n) time, O(1) space vs hash-map O(n) space.
Incorrect initialization of pointers Starting pointers at wrong indices → misses solution or index misalignment Start left = 0, right = numbers.length - 1 and check sum in each iteration; explain reasoning.
Failing to early exit on sum == target Continues scanning array → unnecessary iterations Explain early return improves efficiency, demonstrates clear understanding of pointer invariant.

Comparison with Two Sum I pitfalls

  • Two Sum I: Mistakes often around hash-map insert order, self-match, duplicates, negative numbers, and O(n²) brute-force edge cases.
  • Two Sum II: Mistakes shift to pointer management, off-by-one indexing (1-indexed), and incorrect sum comparison logic.
  • Interview tip: Always articulate why the chosen approach avoids pitfalls naturally and mention differences with unsorted array (Two Sum I).

ASCII Example of Pointer Pitfall

numbers = [2,3,4,7,11,15], target=9

Common mistake:
l=0, r=5 -> sum=17 > 9
Incorrect: l++ instead of r-- → misses correct pair

Correct:
l=0, r=5 -> sum=17 > 9
r-- -> r=4
...
l=0, r=3 -> sum=9 -> return [1,4] (+1 for 1-index)
  

Interview Explanation Strategy

  • Describe each pointer movement and why sum comparison works.
  • Show how off-by-one is corrected with 1-indexed result.
  • Compare briefly with Two Sum I hash-map reasoning.
  • Optional: mention “all pairs” variant and how duplicates are skipped safely.

Edge Cases & Suggested Interview Demos — Two Sum II

Common Edge Cases to Mention

  • Minimal size: numbers.length == 2 — always check this simplest case in interview to ensure logic works for the smallest input.
  • Target equals sum of first & last: numbers = [1,2,3,4], target=5 — validates pointer initialization and early exit.
  • Duplicate values: numbers = [2,3,3,4], target=6 — shows pointers handle duplicates naturally, returns first valid pair.
  • All elements same: numbers = [3,3,3,3], target=6 — confirms 1-indexing and correct pair selection.
  • Negative numbers: numbers = [-3,-1,0,2,4], target=1 — demonstrates sum comparison works with negative values.
  • No valid pair (if variant allows): explain early return or empty result handling.
  • Large input: numbers.length ~ 10⁵ — mention O(n) pointer approach handles it efficiently, no extra space used.

ASCII Pointer Flow Example

numbers = [2,3,4,7,11,15], target=9
1-indexed result

Initialize pointers:
l=0, r=5

Iteration 1: sum=2+15=17 > 9 -> move r--
l=0, r=4 -> sum=2+11=13 > 9 -> move r--
l=0, r=3 -> sum=2+7=9 -> found pair -> return [1,4] (add +1 for 1-index)
  

Another ASCII Example with Duplicates

numbers = [2,3,3,4], target=6

l=0, r=3 -> sum=2+4=6 -> return [1,4] (first valid pair)
l=1, r=2 -> sum=3+3=6 -> also valid pair for "all pairs" variant
Pointers handle duplicates naturally
  

Suggested Live Interview Demos

  1. [2,3,4,7,11,15], target=9 → expect [1,4]
  2. [1,2,3,4], target=5 → expect [1,4]
  3. [2,3,3,4], target=6 → expect [1,4] for first valid pair
  4. [-3,-1,0,2,4], target=1 → expect [2,5]
  5. [3,3,3,3], target=6 → expect [1,2]

Interview Explanation Tips

  • Always mention edge-case consideration first to demonstrate completeness of your solution.
  • Walk through pointer movements with ASCII to show correct logic.
  • Explain handling of duplicates, negatives, minimal input, and large input efficiently.
  • Highlight 1-index adjustment if required by the problem.

Time & Space Complexity — Two Sum II

Time Complexity

The Two Pointer approach scans the array from both ends. Each iteration moves either the left or right pointer closer. Since pointers never move backward and each moves at most n steps:

  • 1 pass maximum across the array → O(n) time.
  • No nested loops required, unlike brute-force O(n²).
  • Efficient for large inputs (up to 10⁵ elements) during interviews.

Space Complexity

The Two Pointer solution uses only two pointers and a few scalar variables. There is no extra array or map:

  • Left and right pointers → O(1) extra space.
  • Variables for sum calculation → O(1).
  • No dynamic data structures needed, so memory remains minimal even for large arrays.

JavaScript Example — Illustrating Space Usage

JavaScript — Two Pointer

function twoSumII(numbers, target) {
  let left = 0, right = numbers.length - 1; // O(1) space for pointers

  while (left < right) {                    // O(n) time: each pointer moves at most n steps
    const sum = numbers[left] + numbers[right]; // O(1) space
    if (sum === target) return [left + 1, right + 1]; // 1-indexed result
    else if (sum < target) left++;
    else right--;
  }
  return []; // no valid pair
}
    

Step-by-Step Example for Clarity

numbers = [2,3,4,7,11,15], target = 9
left=0, right=5

Iteration 1: sum=2+15=17 > 9 -> move right--
Iteration 2: left=0, right=4 -> sum=2+11=13 > 9 -> move right--
Iteration 3: left=0, right=3 -> sum=2+7=9 -> found -> return [1,4]

Time: 3 pointer moves (<< n)
Space: only left, right, sum → O(1)
  

Why This is Interview-Preferred

  • O(n) time is optimal for sorted array input without extra memory.
  • O(1) space shows efficiency and understanding of constraints.
  • Simple, clean logic is easy to explain in interviews with ASCII/pointer diagrams.

Comparison with Two Sum I

ProblemTimeSpaceNotes
Two Sum I (unsorted)O(n) with hash mapO(n)Extra hash map needed for complement lookup
Two Sum II (sorted)O(n) with two pointersO(1)No extra space; pointer movement is sufficient

Language-Specific Notes

Implementation details for the fixed sliding window solution vary by language. Select to view optimizations.

FAQs — Two Sum II (Sorted Array) — Interview-Ready Answers

Q: Walk me through your approach for Two Sum II.

A: "Given a sorted array, I use the two-pointer approach. Initialize left=0 and right=nums.length-1. Compute sum = nums[left] + nums[right]. If sum == target, return positions [left+1, right+1] (1-indexed). If sum < target, increment left; if sum > target, decrement right. Repeat until pointers meet. This runs in O(n) time and O(1) space. Edge cases like duplicates, minimal array size, and negative numbers are handled naturally."

Q: Why not use hash map as in Two Sum I?

A: "Hash map works, but since the array is sorted, two pointers are more optimal — O(1) extra space and linear time. Hash map would still work in O(n) time but uses O(n) space. In interviews, showing the pointer approach demonstrates pattern recognition and optimization."

Q: How do you handle duplicates?

A: "Two Sum II naturally handles duplicates because pointers only consider current positions. If the problem asked for all unique pairs, I would skip over duplicate values while moving pointers to avoid repeated results."

Q: Can you do this in O(1) extra space?

A: "Yes, the two-pointer approach is O(1) space since we only maintain two variables for pointers. Unlike hash maps, no extra memory is needed."

Q: What micro-optimizations do you consider?

A: "I can check early: if nums[left] + nums[right] == target on the first iteration, return immediately. Avoid unnecessary computations inside the loop. Also, be mindful of integer overflow in languages like Java, though in JS it's handled natively."

Q: How to dry-run this in interview?

A: "Use an example like nums = [2,7,11,15], target=9. Start with left=0, right=3: sum=2+15=17 > 9, decrement right → 2+7=9 → found pair. Walk through each pointer move to clearly demonstrate understanding."

Quick interviewer follow-ups (practice these answers)

  • If array has negative numbers, the same two-pointer logic works.
  • Explain why the approach is O(n) time and O(1) space.
  • Be ready to discuss differences with Two Sum I (unsorted array + hash map).
  • If asked about 1-indexed vs 0-indexed output, clarify implementation choice.
  • For arrays with duplicates or multiple valid pairs, discuss pointer skipping strategies.