Promoted
Promoted
Solving array problems with two pointers
Topic: Algorithms
Two-pointers is a pretty common method to solve array problems in linear time with constant space. Two-pointers problems can be solved by traversing an array by either fast and slow pointers or by left and right pointers. Two-pointers problems can be used for sliding window problems. We can adjust window size sliding left or right pointers. Let's see some examples to get a clear idea of two problems.
When there is comparison of two numbers in an array | 0 | heading |
If there requires a comparison between two numbers in an array it will require O(n^2) brute force. This is because we will have to run two loops for comparing each number with another number. Look at following | 1 | paragraph |
Two Sum | 2 | subheading |
3 | image | |
If this problem is solved with brute force we require two loops.
for i in numbers:
For j in numbers
If i + j == target:
print(“Target is sum of”, i, j)
| 4 | code |
167. Two Sum II - Input array is sorted | 5 | link |
But we use two pointers that can be done in linear time O(n). | 6 | paragraph |
Promoted Promoted
| 7 | list |
def twoSum(numbers, target):
start = 0 #point start to left
end = len(numbers)-1 #point end to right. we use len-1 because array index starts with 0
sum = 0 #initial sum with 0
while start != end : #run loop until start and end point to same number
sum = numbers[start] + numbers[end]
if sum > target:
end -= 1 #look for smaller number
elif sum < target:
start +=1 #look for larger number
else:
return [start+1,end+1] #condition satisfied
return -1 | 8 | code |
Find the duplicates in the array | 9 | heading |
10 | link | |
11 | image | |
| 12 | list |
def findDuplicate(nums):
n = len(nums)
if n > 1:
slow = nums[0]
fast = nums[slow]
while slow != fast:
slow = nums[slow]
fast = nums[nums[fast]]
fast = 0
while fast != slow:
fast = nums[fast]
slow = nums[slow]
return slow
return -1 | 13 | code |
Related Posts