Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Find a pair with target sum in a sorted arrayE02. Count unique values in a sorted arrayE03. Move zeros to the end while preserving orderE

Problem No 1

Find a pair with target sum in a sorted array

Easy

6 minute session

Summary

Use the two-pointer technique to determine if any two numbers in a sorted array sum to a target.

Problem statement

Given a sorted list of integers (ascending) and a target integer, determine if there exists any pair of distinct elements in the list whose sum is equal to the target. Return True if such a pair exists, otherwise return False. Use the two-pointer technique to achieve O(n) time and O(1) extra space.

Task

Implement an efficient O(n) two-pointer solution that checks for a pair summing to a given target in a sorted list.

Examples

Basic example

Input

arr = [1, 2, 3, 4], target = 5

Output

True

Explanation

1 and 4 (or 2 and 3) sum to 5, so the function should return True.

Input format

A sorted list of integers 'arr' and an integer 'target'. The function signature: pair_with_target(arr, target).

Output format

Return True if a pair exists that sums to target, otherwise False.

Constraints

0 <= len(arr) <= 10^5. Array is sorted in non-decreasing order. Aim for O(n) time and O(1) extra space.

Samples

Sample input 0

[1, 2, 3, 9], 8

Sample output 0

False

Explanation 0

No two numbers in the array sum to 8.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:45 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.