Category: 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,
    });
    
  • 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;
        }
    }
  • 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;
        }
    }
  • 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

  • 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

  • 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
  • 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>
    
  • 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

  • Shifting Letters – Java O(n)

    class Solution {
        public String shiftingLetters(String S, int[] shifts) {
            int n = shifts.length;
            int prev = 0;
            char[] arr = S.toCharArray();
            for (int i = n - 1; i >= 0; i--) {
                prev += shifts[i] % 26;
                arr[i] = getNextChar(arr[i], prev);
            }
            return new String(arr);
        }
    
        public char getNextChar(char a, int diff) {
            return (char)((((a - 'a') + diff) % 26) + 'a');
        }
    }
  • Drag Drop ES6

    The following code demonstrates drag drop functionality in ES6.

    <script>
      const onDrop = (e) => {
        e.preventDefault();
     e.target.appendChild(document.getElementById(e.dataTransfer.getData('target')));
      };
      const onDragOver = (e) => e.preventDefault();
      const onDragStart = (e) => e.dataTransfer.setData('target', e.target.id);
      
    </script>
    <div id="dest" ondrop="onDrop(event)" ondragover="onDragOver(event)" style="height: 200px; width: 200px; border: 1px solid #000; padding: 10px; box-sizing: border-box;"></div>
    <img id="source" draggable="true" ondragstart="onDragStart(event)" src="http://via.placeholder.com/180x180" />
    

    Demo