Categories
Uncategorized

Mutation Observer

If you want to listen to DOM Mutations then you can use the Mutation Observer.

const observer = new MutationObserver((mutations) => {
  mutations.forEach(function(mutation) {
    for (let i = 0; i < mutation.addedNodes.length; i++) { // i.e., nodeList
      console.log(mutation.addedNodes[i]);
      // You can perform your actions here.
    }
  });
});
observer.observe(document.body, {
  childList: true,
  subtree: true,
  attributes: false,
  characterData: false,
});
Categories
Uncategorized

Shortest Distance to a Character

class Solution {
    public int[] shortestToChar(String S, char C) {
        int n = S.length();
        int prev = Integer.MIN_VALUE/2;
        int[] store = new int[n];
        for(int i = 0; i < n; i++) {
            if(S.charAt(i) == C) {
                store[i] = 0;
                prev = i;
            }
            else 
                store[i] = i - prev; 
        }
        prev = Integer.MAX_VALUE/2;
        for(int i = n-1; i >= 0; i--) {
             if(S.charAt(i) == C)
                prev = i;
            else 
                store[i] = Math.min(store[i], prev - i); 
        }
        return store;
    }
}
Categories
Uncategorized

Largest 1-Bordered Square

class Solution {
    public int largest1BorderedSquare(int[][] grid) {
        int[][] h = new int[grid.length][grid[0].length];
        int[][] v = new int[grid.length][grid[0].length];
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 0) {
                    h[i][j] = 0;
                    v[i][j] = 0;
                } else {
                    h[i][j] = j > 0 ? h[i][j - 1] + 1 : 1;
                    v[i][j] = i > 0 ? v[i - 1][j] + 1 : 1;
                }
            }
        }
        int max = 0;
        for (int i = grid.length - 1; i >= 0; i--) {
            for (int j = grid[0].length - 1; j >= 0; j--) {
                int small = Math.min(v[i][j], h[i][j]);
                while (small > max) {
                    if (v[i][j + 1 - small] >= small && h[i + 1 - small][j] >= small) {
                        max = Math.max(max, small);
                    }
                    small--;
                }
            }
        }
        return max * max;
    }
}
Categories
Uncategorized

Longest Common Prefix using Binary Search (ES6)

const arr = ["hello", "helloworld", "helloworld1"];

const allContains = (inp, start, end) => {
for(let i=0; i<inp.length; i++) {
	for(let j=start; j<=end; j++) {
		if(inp[0].charAt(j)!==inp[i].charAt(j)) {
			return false;
    	}
	}
}
return true;
};

const findSubstring = (inp) => {
let min = Number.MAX_VALUE;
  for(let i=0; i<inp.length; i++) {
  	 min = Math.min(inp[i].length, min);
  }
let low = 0, high = min-1;
let prefix = '';
 while(low<=high) {
 	let mid = low + Math.round((high-low)/2);
  	if(allContains(inp, low, mid)) {
   		prefix += inp[0].substring(low, mid+1);
  		low = mid+1;
  	} else
  	high = mid-1;
		}
return prefix;
};

console.log(findSubstring(arr));

// Output: hello
// Runtime complexity: O(m*log(n)) 
// m- length of input array or list and n is length of 
// smallest string.

Demo

Categories
Uncategorized

Flatten an Array (ES6)

To flatten an array with depth of level 1:

const inputArray = [1, 2, 3, [4, 5]];
console.log([].concat(...inputArray));
// Output: [1, 2, 3, 4, 5]

Demo

To flatten an array of a specified depth:

const input = [1, 2, 3, [4, 5, 6, [8, 9, 10]], 11, [12, 13, 14]];

const flatten = (arr, depth) =>
  depth === 0 || !Array.isArray(arr) ? arr :
  arr.reduce((acc, curr) =>
    Array.isArray(curr) ? acc.concat(flatten(curr, depth - 1)) :
    acc.concat(curr), [])

console.log(flatten(input, 3));
// Ouput: [1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14]

Demo

To flatten an array infinitely:

const input = [1, 2, 3, [4, 5, 6, [8, 9, 10]], 11, [12, 13, 14]];

const flatten = (arr) =>
   !Array.isArray(arr) ? arr : arr.reduce((acc, curr) =>
    Array.isArray(curr) ? acc.concat(flatten(curr)) :
    acc.concat(curr), []);

console.log(flatten(input));
// Ouput: [1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14]

Demo

Categories
Uncategorized

Priority Queue Comparator using a HashMap

This is similar to a MinHeap.

import java.util.*; 
import java.lang.*;
 
public class GFG { 

    public static void main(String[] args) 
    { 
        HashMap<Integer, Integer> map 
            = new HashMap<>(); 
            map.put(10, 3);
            map.put(20, 2);
            map.put(30, 1);
      PriorityQueue<Integer> pq = new PriorityQueue<Integer>((a,b) -> map.get(a) - map.get(b));
      pq.add(10);
      pq.add(30);
      pq.add(20);
      System.out.println(pq.poll());
      System.out.println(pq.poll());
      System.out.println(pq.poll());
    }   
}

Output

30
20
10
Categories
Uncategorized

CSS animation – Card Slide-In

Using CSS @keyframes you can animate cards from left to right in the following way. This works on almost all major modern browsers.

Demo

Card 1

Card 2

<style>
.card {
  height: 100px;
  width: 250px;
  background: white;
  border-radius: 8px;
  border: 1px solid #999;
  box-shadow: 5px 5px 5px #999;
  animation: slidein 5s;
  animation-fill-mode: forwards;
  margin-right: 16px;
  transition-timing-function: cubic-bezier(0.1, 0.7, 1, 0.1);
}

@keyframes slidein {
  from {
    transform: translateX(-100%);
  }

  to {
    transform: translateX(100%);
  }
}
</style>
<div style="display:flex;">
  <div class="card">
  </div>
  <div class="card">
  </div>
  <div class="card">
  </div>
</div>
Categories
Uncategorized

Currying

Breaking down a function into a series of function calls with an argument. The following is an Javascript ES6 example of a sum function that returns the sum of the calls until no argument is passed.

Code

const add = (num) => {
  if (!num)
    return 0;
  let sum = 0 + num;
  const ret = (x) => {
    if (!x) {
      return sum;
    } else {
      sum += x;
      return ret;
    }
  };
  return ret;
};

alert(add(5)(6)(7)());

Demo

Categories
Uncategorized

Copy to clipboard ES6 + Deselect

Code

<script>
const copy = () => {
  const elem = document.getElementById('demo');
  elem.select();
  document.execCommand('copy');
  elem.blur();
}
</script>
<input type="text" id="demo" value="Hello World!" />
<button onclick="copy()">
  Copy
</button>

Demo

Categories
Uncategorized

Throttling (ES6)

Sometimes, we need to limit the number of method calls based on time. A throttling method is the way to go.

Code

const throttle = (fn, delay) => {
  let timeout = false;
  return (...rest) => {
    if (!timeout) {
      timeout = true;
      fn.apply(this, rest);
      setTimeout(() => {
        timeout = false;
      }, delay);
    }
  }
}


const logger = (inp) => console.log(inp);

const throttledMethod = throttle(logger, 1000);

const button = document.createElement('button');
document.body.appendChild(button);
button.addEventListener('click', () => throttledMethod('Hello World!'));

Demo