nathanwailes

Two pointers

Mar 26th, 2024 (edited)
650
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. """
  2. # two pointers - need the object to search over and the target
  3.    # initialize the positions of the left and right pointers
  4.    # while the left pointer is to the left of the right pointer
  5.        # calculate what the potential match is with this combination
  6.        # if you've found the target, return these pointers,
  7.        # else if the target is to the left of the potential match, decrement the right pointer
  8.        # else the target is to the right of the potential match, so increment the left pointer
  9.    # if you reach here you haven't found a matching combination
  10. """
  11. def two_sum(arr, target):
  12.     l, r = 0, len(arr)-1
  13.     while l < r:
  14.         potential_match = arr[l] + arr[r]
  15.         if potential_match == target:
  16.             return [l, r]
  17.         elif target < potential_match:
  18.             r -= 1
  19.         else:
  20.             l += 1
  21.     return []
  22.  
  23. # Example usage
  24. arr = [2, 7, 11, 15]
  25. target = 9
  26. print(two_sum(arr, target))  # Output: [0, 1], because arr[0] + arr[1] = 2 + 7 = 9
  27.  
  28. """
  29. You might look at the pointer-moving logic and think, "Why do we just step to the right to decrease the current sum, when we could alternatively sometimes step to the left with the left pointer?" The answer is: because we only step inwards when we determine that a value at a given index *can't possibly* be part of the solution, because its partner doesn't exist on the other side of the array. We can draw this conclusion definitively because the array is sorted. So there's never a need to step back outwards on either side because those numbers have been definitively ruled out as being part of the solution.
  30.  
  31. So the essence of the two-pointer method is, "Can I rule out this index as being part of the solution? If so, step inwards."
  32. """
Advertisement
Add Comment
Please, Sign In to add comment