criskgl

Public Snippets 110

Count Triplets

https://www.youtube.com/watch?v=KZ8k9-22JmQ&ab_channel=CodingCart
# Complete the countTriplets function below.
def countTriplets(arr, r):
    bef = {}
    aft = {}
    count = 0
    
    #Populate after
    for v in arr:
        if v in aft:
            aft[v] += 1
        else:
            aft[v] = 1
    
    # Go through array calculating 
    for v in arr:
        # Take current, remove it from after dictionary
        aft[v] -= 1
        # Check conditions to see if we can add to count
        if v/r in bef and v%r == 0 and v*r in aft:
            count +=

Return values from async function

Return values from async function
```
dffd
```

LRU Cache

/*************NODE CLASS*********************/
public class ListNode {
	int key;
	int value;
	ListNode next;
	ListNode prev;
	
	public ListNode(){
		
	}
	
	public ListNode(int key, int value){
		this.key = key;
		this.value = value;
	}
}
/*******************************************/
class LRUCache {
	
	int capacity;
	int size;
	
	ListNode head;//Dummy head
	ListNode tail;//Dummy tail
	HashMap<Integer, ListNode> keyToNode;
	
	public LRUCache(int capacity){
		this.capacity = capacity;
		this.keyTo

K closest points to origin

  public int[][] kClosest(int[][] points, int K) {
    int N = points.length;
    int[] dists = new int[N];
    for (int i = 0; i < N; ++i)
        dists[i] = dist(points[i]);
 
    Arrays.sort(dists);
    int distK = dists[K-1];
 
    int[][] ans = new int[K][2];
    int t = 0;
    for (int i = 0; i < N; ++i)
        if (dist(points[i]) <= distK)
            ans[t++] = points[i];
    return ans;
  }
 
  public int dist(int[] point) {
    return point[0] * point[0] + point[1] * point[1];
  }
}

Drone Flying

public static class Wrapper{
    public static ArrayList<ArrayList<Integer>> paths; 
    public static ArrayList<Integer> mins;
    public static int max;
}
public static int maxScore2D(int[][] grid){
    Wrapper.paths = new ArrayList<ArrayList<Integer>>();
    Wrapper.mins = new ArrayList<Integer>();
    Wrapper.max = 0;
    ArrayList<Integer> path = new ArrayList<>();
    getMins(grid, 0, 1, grid[0][1], path);
    path.clear();
    getMins(grid, 1, 0, grid[1][0], path);
    return Wrapper.max;

AO2-Treasure Island

/*BREADTH FIRST SEARCH TO MINIMUM PATH WITH OBSTACLES*/
public static int findMin(char[][] island){
    int rows = island.length;
    int cols = island[0].length;
    Queue<Integer> qRows = new LinkedList<>();
    Queue<Integer> qCols = new LinkedList<>();
    qRows.add(0);
    qCols.add(0);
    boolean[][] visited = new boolean[rows][cols];
    int steps = 0;
    while(!qRows.isEmpty() && !qCols.isEmpty()){
        for(int i = 0; i < qRows.size(); i++){
            int row = qRows.poll();
     

Distance to node from root

//CALCULATE DISTANCE FROM ROOT TO ANY NODE IN THE TREE
public int calculateDistance(TreeNode root, TreeNode q){
    if(root == null) return -1;
    if(root.val == q.val) return 0;
    
    int d1 = calculateDistance(root.left, q);
    int d2 = calculateDistance(root.right, q);
    if(d1 == -1 && d2 == -1) return -1;
    return 1 + Math.max(d1,d2);
}

Subarrays with K distinct characters

public static int subarraysWithKDistinct(int[] arr, int k) {
    if(k==0) return 0;
    int n = arr.length;
    Map < Integer, Integer > map = new HashMap < > ();
    int i = 0, j = 0, total = 0;
    while (j < arr.length) {
        map.put(arr[j], map.getOrDefault(arr[j], 0) + 1);
        if (map.size() == k) {
            int dups = j;//at this point we already have K distinct
            while ((dups + 1) < n && map.containsKey(arr[dups + 1])) dups++;//extend our windows as much as we can
   

Merge Intervals Optimized

<img src="https://gdurl.com/tLmy"></img>
class Solution {
    public int[][] merge(int[][] intervals) {
        if(intervals.length == 0 || intervals.length == 1) return intervals;
        for(int i = 0; i < intervals.length; i++){
            System.out.println(intervals[i][0]+" "+intervals[i][1]);
        }
        //sort intervals in ascending order by inital times
        orderByStart(intervals);
        for(int[] k : intervals) System.out.println(Arrays.toString(k));
        
        ArrayList<int[]> merged = new ArrayList<int[]>(

Sort Array of Arrays by one of the values

java.util.Arrays.sort(intervals, new java.util.Comparator<int[]>() {
    public int compare(int[] a, int[] b) {
        return Integer.compare(a[0], b[0]);
    }
});

Heap with custom ordering

### Very useful stufffff!!!! Sometimes it will be usefull to order the elements inside a heap not by its values but **either by some associated values**.
//this is ordering a heap not by the values added to it but by its frecuency in an array(which was stored using a hashmap named count)
PriorityQueue<Integer> heap = new PriorityQueue<Integer>((n1, n2) -> count.get(n1) - count.get(n2));

Lowest Common Ancestor

class Solution {
  TreeNode answer;
  public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
      this.answer = new TreeNode(-1);
      LCA(root, p, q);
      return this.answer;
  }
  
  public boolean LCA(TreeNode root, TreeNode p, TreeNode q){
      if(root.right == null && root.left == null){//leaf
          if(root.val == p.val || root.val == q.val) return true;
          return false;
      }
      boolean ansL = false;
      boolean ansR = false;
      if(root.left

Insert into BST

public TreeNode insertIntoBST(TreeNode root, int val) {
    TreeNode tNode = new TreeNode(val);
    TreeNode current = root;
    while(true){
        if(val > current.val){
            //BIGGER
            if(current.right == null){//insert
                current.right = tNode;
                break;
            }
            current = current.right;
        }else{
            //SMALLER
            if(current.left == null){//insert
                current.left = tNode;
                break;
  

Subarray with K different integers

public int subarraysWithKDistinct(int[] A, int K) {
    HashSet<Integer> hs = new HashSet<>();
    int L = 0;
    int R = 0;
    int count = 0;
    while(L <= R && L < A.length){
        if(R > A.length - 1){//R EXCEEDED BUT INSIDE L STILL INSIDE BOUNDS
            hs.clear();
            L++;
            R = L;
            continue;
        }
        if(hs.contains(A[R])){
            if(hs.size() == K) count++;
            R++;
        }else{
            if(hs.size() + 1 <= K){
               

Letter Digit Logs

public String[] reorderLogFiles(String[] logs) {
    if (logs == null || logs.length == 0) return logs;
    int len = logs.length;
    List<String> letterList = new ArrayList<>();
    List<String> digitList = new ArrayList<>();
    for (String log : logs) {
        if (log.split(" ")[1].charAt(0) < 'a') {
            digitList.add(log);
        } else {
            letterList.add(log);
        }
    }
    Collections.sort(letterList, (o1, o2) -> {
        String[] s1 = o1.split(" ");
        Str

findPeak

public int findPeakElement(int[] nums) {
    return search(nums, 0, nums.length - 1);
}
public int search(int[] nums, int l, int r) {
    if (l == r)
        return l;
    int mid = (l + r) / 2;
    if (nums[mid] > nums[mid + 1])
        return search(nums, l, mid);
    return search(nums, mid + 1, r);
}