0% found this document useful (0 votes)
4 views

Two Pointer Approach in Programming

The document outlines several problems that can be solved using the two-pointer approach, including finding pairs with a given sum in a sorted array, moving zeros to the end of an array, checking if a string is a palindrome, partitioning 0s and 1s in a binary array, and finding the container with the most water. Each problem is accompanied by a key idea and a sample Python solution. The summary emphasizes the initialization, movement logic, and termination of the two-pointer strategy.

Uploaded by

sdas.cse21
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Two Pointer Approach in Programming

The document outlines several problems that can be solved using the two-pointer approach, including finding pairs with a given sum in a sorted array, moving zeros to the end of an array, checking if a string is a palindrome, partitioning 0s and 1s in a binary array, and finding the container with the most water. Each problem is accompanied by a key idea and a sample Python solution. The summary emphasizes the initialization, movement logic, and termination of the two-pointer strategy.

Uploaded by

sdas.cse21
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Assignment: Two-Pointer Approach

1. Pair with Given Sum in a Sorted Array


• Task: Given a sorted array of integers and a target value S, determine if there are two numbers
in the array whose sum is exactly S. If such a pair exists, print the pair. Otherwise, print that no
such pair exists.
• Key Idea:
1. Initialize one pointer (left) at the start of the array and another pointer (right) at the
end.
2. If the sum of the two pointed values is greater than S, move the right pointer one step
left.
3. If the sum is less than S, move the left pointer one step right.
4. If the sum matches S, you’ve found a valid pair.

Sample Solution (Python)


python
CopyEdit
def pair_with_sum_sorted(arr, S):
left, right = 0, len(arr) - 1
while left < right:
current_sum = arr[left] + arr[right]
if current_sum == S:
return (arr[left], arr[right])
elif current_sum < S:
left += 1
else:
right -= 1
return None

# Test
array = [1, 2, 4, 4, 7, 11, 15]
target = 8
result = pair_with_sum_sorted(array, target)
if result:
print(f"Pair found: {result}")
else:
print("No pair found with the given sum.")

2. Move Zeros to the End (or Start) of the Array


• Task: Given an unsorted array, move all zeroes to the end of the array while maintaining the
relative order of the non-zero elements.
• Key Idea:
1. Use one pointer (non_zero) to track the position where the next non-zero element
should be placed.
2. Use another pointer (i) to iterate through the array.
3. Whenever you encounter a non-zero element, swap it with the element at
arr[non_zero] and increment non_zero.
4. After one pass, all non-zero elements will be at the front, and zeroes will be at the end.

Sample Solution (Python)


python
CopyEdit
def move_zeros_to_end(arr):
non_zero = 0
for i in range(len(arr)):
if arr[i] != 0:
arr[non_zero], arr[i] = arr[i], arr[non_zero]
non_zero += 1
return arr

# Test
array = [0, 1, 0, 3, 12]
print("Before:", array)
result = move_zeros_to_end(array)
print("After: ", result)

3. Check if a String is a Palindrome


• Task: Given a string, determine whether it is a palindrome (reads the same backward and
forward). Consider only alphanumeric characters, ignoring cases if desired.
• Key Idea:
1. Use two pointers: one (left) at the start, and the other (right) at the end.
2. Move left pointer forward and right pointer backward, comparing corresponding
characters.
3. If at any point characters do not match, it is not a palindrome.
4. Continue until the pointers cross or match each other.

Sample Solution (Python)


python
CopyEdit
def is_palindrome(s):
# Optional: convert to lowercase and strip non-alphanumeric chars
s = ''.join(ch.lower() for ch in s if ch.isalnum())

left, right = 0, len(s) - 1


while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True

# Test
test_string = "A man, a plan, a canal: Panama"
print(f"'{test_string}' is a palindrome?" , is_palindrome(test_string))
4. Partition 0s and 1s in an Array
• Task: Given a binary array (containing only 0s and 1s), rearrange all 0s to appear before all 1s
(or vice versa). This is sometimes referred to as the "segregation" problem.
• Key Idea:
1. Use two pointers, left starting at index 0 and right at the end of the array.
2. Move left forward until you find a 1.
3. Move right backward until you find a 0.
4. Swap the elements at left and right.
5. Repeat until left >= right.

Sample Solution (Python)


python
CopyEdit
def partition_zeroes_ones(arr):
left, right = 0, len(arr) - 1
while left < right:
while left < right and arr[left] == 0:
left += 1
while left < right and arr[right] == 1:
right -= 1
if left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return arr

# Test
array = [0, 1, 1, 0, 1, 0]
print("Before:", array)
result = partition_zeroes_ones(array)
print("After: ", result)

5. Container With Most Water


• Task: You have n vertical lines drawn such that the two endpoints of the ith line are (i,0) and
(i,height[i]). Find two lines that, together with the x-axis, form a container that holds the most
water. (A classic LeetCode problem.)
• Key Idea:
1. Use two pointers: left = 0, right = n-1.
2. Calculate the area using the shorter line as the limiting height.
3. Update the maximum area if the current area is larger.
4. Move the pointer corresponding to the shorter line inward (because moving the pointer
at the taller line inward won’t increase the height factor).
5. Continue until left >= right.
Sample Solution (Python)
python
CopyEdit
def max_area(height):
left, right = 0, len(height) - 1
max_area_val = 0
while left < right:
# Calculate the current area
min_height = min(height[left], height[right])
width = right - left
current_area = min_height * width

# Update max_area if needed


max_area_val = max(max_area_val, current_area)

# Move the pointer that has the shorter line


if height[left] < height[right]:
left += 1
else:
right -= 1
return max_area_val

# Test
heights = [1,8,6,2,5,4,8,3,7]
result = max_area(heights)
print(f"Max area is: {result}")

Summary of Two-Pointer Approach


1. Initialization: Typically, one pointer starts from the left (beginning) and another from the right
(end), or you have a “fast” and “slow” pointer.
2. Movement Logic: Decide which pointer to move based on some condition (e.g., comparing
sums to a target, comparing elements to reorder, etc.).
3. Termination: Stop when the pointers meet or cross, which usually indicates you’ve checked all
valid combinations or rearranged the data.
Practice these problems to get familiar with the two-pointer strategy. Once comfortable, you can adapt
the approach to a wide variety of problems in array and string manipulation.

You might also like