Skip to content

Instantly share code, notes, and snippets.

@QuocCao-dev
Last active October 29, 2022 08:55
Show Gist options
  • Save QuocCao-dev/fae7141e7be9278de665bc25a82de73d to your computer and use it in GitHub Desktop.
Save QuocCao-dev/fae7141e7be9278de665bc25a82de73d to your computer and use it in GitHub Desktop.
Two Pointer

Introduce To 2 Pointers

image

const pair_with_targetsum = function (
  arr: number[],
  target_sum: number,
): number[] {
  // TODO: Write your code here
  return [-1, -1];
};

pair_with_targetsum([1,2,3,4,6], 6) // [1,3]
pair_with_targetsum([2,5,9,11], 11) // [0,2]

image

const remove_duplicates = function (arr: number) {
  // TODO: Write your code here
  return -1;
};
remove_duplicates([2,3,3,3,6,9,9]) // 4
remove_duplicates([2,2,2,11]) // 2

Solution

image

image

const make_squares = function (arr: number[]) {
  // TODO: Write your code here
  return ;
};

make_squares([-2,-1,0,2,3]) // [0,1,4,4,9]
make_squares([-3,-1,0,1,2]) // [0,1,1,4,9]

Solution

This is a straightforward question. The only trick is that we can have negative numbers in the input array, which will make it a bit difficult to generate the output array with squares in sorted order.

An easier approach could be to first find the index of the first non-negative number in the array. After that, we can use Two Pointers to iterate the array. One pointer will move forward to iterate the non-negative numbers, and the other pointer will move backward to iterate the negative numbers. At any step, whichever number gives us a bigger square will be added to the output array. For the above-mentioned Example-1, we will do something like this: image

Since the numbers at both ends can give us the largest square, an alternate approach could be to use two pointers starting at both ends of the input array. At any step, whichever pointer gives us the bigger square, we add it to the result array and move to the next/previous number according to the pointer. For the above-mentioned Example-1, we will do something like this: image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment