Array - One trick problems

Writing test cases for array problems:

1. Trapping Rain water

https://neetcode.io/problems/trapping-rain-water
Sum += if ( min(maxLeft, maxRight) - height[i] ) > 0

##2. Group Anagram
https://neetcode.io/problems/anagram-groups
A-Z or a-z words don't need to be sorted in nlog(n)
They can be made O(1) strings and then handled
And yeah, don't forget .charChodeAt method

3. No duplicate records/tuples/answer:

Sort the array and skip the equal values.
{901B4E47-B2EF-413F-88B6-10AE96CA2C79}.png

4. 3Sum - mug up

https://neetcode.io/problems/three-integer-sum
two things to notice:

5. Median of Two Sorted Array

https://neetcode.io/problems/median-of-two-sorted-arrays

const findMedianSortedArrays = (nums1, nums2) => {

  let A = nums1;

  let B = nums2;

  

  let total = nums1.length + nums2.length;

  

  if (nums1.length > nums2.length) {

    A = nums2;

    B = nums1;

  }

  

  let half = Math.floor(total / 2);

  

  let l = 0;

  let r = A.length - 1;

  

  while (true) {

    let midA = Math.floor((l + r) / 2);

    let midB = half - midA - 2;

  

    let ALEFT = midA >= 0 ? A[midA] : -Infinity;

    let ARIGHT = (midA + 1) < A.length ? A[midA + 1] : Infinity;

  

    let BLEFT = midB >= 0 ? B[midB] : -Infinity;

    let BRIGHT = (midB + 1) < B.length ? B[midB + 1] : Infinity;

  

    if (ALEFT <= BRIGHT && BLEFT <= ARIGHT) {

      if (total % 2 !== 0) {

        return Math.min(ARIGHT, BRIGHT);

      } else {

        return ((Math.max(ALEFT, BLEFT)) + Math.min(ARIGHT, BRIGHT)) / 2;

      }

    } else if (ALEFT > BRIGHT) {

      r = midA - 1;

    } else {

      //BLEFT > ARIGHT

      l = midA + 1;

    }

  }

}

  

console.log(findMedianSortedArrays([1, 3], [2]) === 2);

console.log(findMedianSortedArrays([1, 2], [3, 4]) == 2.5);

console.log(findMedianSortedArrays([1, 2, 3, 4], [5,6,7])===4);
  1. Subarray Sum Equals K - Explanation
    https://www.youtube.com/watch?v=ph0v80-rRtQ

How to create Array of a particular dimensions:

1D:

const arr = Array.from({ length: 4 });

This creates [undefined, undefined, undefined, undefined].

const arr = Array.from({ length: 4 }, () => 0);

Result: [0, 0, 0, 0]

2D:

 this.prefixSum = Array.from({ length: ROWS }, () => Array(COLS).fill(0));