Two Pointer Approach in Programming
Two Pointer Approach in Programming
# 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.")
# Test
array = [0, 1, 0, 3, 12]
print("Before:", array)
result = move_zeros_to_end(array)
print("After: ", result)
# 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.
# Test
array = [0, 1, 1, 0, 1, 0]
print("Before:", array)
result = partition_zeroes_ones(array)
print("After: ", result)
# Test
heights = [1,8,6,2,5,4,8,3,7]
result = max_area(heights)
print(f"Max area is: {result}")