Ali Durul - Portfolio

Two Pointers

Two pointers is a technique where you use two pointers that either move towards each other or move in the same direction. The technique is often used to search for a pair of indices satisfying some constraint in linear time.

When:

  • String or array questions
  • Satisfy a constraint
  • "Find a set of elements that satisfy some constraint"
  • Substring/subarray questions

Cases:

  • Two pointers one starting at the beginning and one at the end moving towards each other
  • One pointer moving in the same direction, one slow and one fast.

Valid Palindrome

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Example 1:

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.

Example 2:

Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.

Example 3:

Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome.

Constraints:

  • 1 <= s.length <= 2 * 105
  • s consists only of printable ASCII characters.
  const isPalindrome = function(s) {

    // turn string to lowercase and use regex to remove non-alphanumeric
    s = s.replace(/[^p{L}p{N}]/giu, '');
    s = s.toLowerCase()

    let a = 0, b = s.length - 1
    
    while(a < b){
      if(s[a] !== s[b]) return false
      a++
      b--
    }
    return true
  };

Explanation:

  1. Get rid of non alphanumeric values and turn string to lowercase
  2. Pointer 'a' points at the beginning of the string and pointer 'b' points at the end of the string
  3. While 'a' is less than 'b', if the values at 'a' and 'b' are not equal, return false
  4. If the values at 'a' and 'b' are equal, increment 'a' and decrement 'b'
  5. If the loop finishes, return true

Assign Cookies

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.

Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.

Example 1:

Input: g = [1,2,3], s = [1,1]
Output: 1
Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.

Example 2:

Input: g = [1,2], s = [1,2,3]
Output: 2
Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children.

Constraints:

  • 1 <= g.length <= 3 * 104
  • 0 <= s.length <= 3 * 104
  • 1 <= g[i], s[j] <= 231 - 1
  const findContentChildren = function(g, s) {
    g.sort((a, b) => a - b);
    s.sort((a, b) => a - b);
    
    let childIndex = 0;
    let cookieIndex = 0;

    let count = 0;

    while (childIndex < g.length && cookieIndex < s.length) {
      if (s[cookieIndex] >= g[childIndex]) {
        count++;
        childIndex++; 
      }
      cookieIndex++;
    }

    return count;
  };

Explanation:

  1. Sort greed factors (g) and cookie sizes (s) ascending so we can match smallest cookie to smallest greed first.
  2. Two pointers: childIndex = current child, cookieIndex = current cookie.
  3. While both pointers are in range: if the cookie satisfies the child (s[cookieIndex] >= g[childIndex]), assign it (count++, move both). Otherwise try the next cookie (cookieIndex++).
  4. Return the number of content children.

Remove Duplicates from Sorted Array

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

Consider the number of unique elements in nums to be k. After removing duplicates, return the number of unique elements k.

The first k elements of nums should contain the unique numbers in sorted order. The remaining elements beyond index k - 1 can be ignored.

Example 1:

Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2:

Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,,,,,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).

Constraints:

  • 1 <= nums.length <= 3 * 104
  • -100 <= nums[i] <= 100
  • nums is sorted in non-decreasing order.
  function removeDuplicates(nums) {
    if (nums.length === 0) return 0;

    let k = 1;
    let lastUniquePointer = 0;

    for (let i = 1; i < nums.length; i++) {
      if (nums[i] !== nums[lastUniquePointer]) {
        lastUniquePointer += 1;
        nums[lastUniquePointer] = nums[i];
        k++;
      }
    }

    return k;
  }

Explanation:

  1. Empty array edge case: return 0.
  2. Two pointers: lastUniquePointer tracks the last unique value's index; k counts unique elements (starts at 1 since first element is always unique).
  3. Loop from index 1: when nums[i] differs from nums[lastUniquePointer], advance lastUniquePointer, copy nums[i] there, and increment k.
  4. Return k (number of unique elements). The first k elements of nums hold the unique values in order.

Remove Duplicates from Sorted Array II

Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Input: nums = [1,1,1,2,2,3]
Output: 5, nums = [1,1,2,2,3,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2:

Input: nums = [0,0,1,1,1,1,2,3,3]
Output: 7, nums = [0,0,1,1,2,3,3,,]
Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).

Constraints:

  • 1 <= nums.length <= 3 * 104
  • -104 <= nums[i] <= 104
  • nums is sorted in non-decreasing order.
  function removeDuplicates(nums) {
    let k = 2;

    for (let i = 2; i < nums.length; i++) {
      if (nums[i] !== nums[k - 2]) {
        nums[k] = nums[i];
        k++;
      }
    }

    return k;
  }

Explanation:

  1. First two elements are always valid (at most 2 allowed per value), so k starts at 2.
  2. From index 2: compare nums[i] with nums[k - 2]. If different, we're not exceeding 2 of the same value in the result, so write nums[i] at k and increment k.
  3. If nums[i] === nums[k - 2], we would have 3 of that value; skip (do not write, do not increment k).
  4. Return k. First k elements hold the result with each value appearing at most twice.
main*
Go Live