Author: Shiva Charan Devabhaktuni

  • Debounce (ES6)

    Sometimes, we would like to wait a certain minimum time period before successive method calls. For example in events like onscroll(), onresize(), this can go a long way in terms of optimizing the page performance as a whole.

    The wrapping of the methods using a Debounce method is a simple way to achieve the desired result.

    const debounce = (fn, interval) => {
      let timeout;
      return (...rest) => {
        if (timeout)
          clearTimeout(timeout);
          timeout = setTimeout(() => {
            fn.apply(this, rest);
          }, interval);
      };
    }
    
    const test = (inp) => {
      console.log(inp);
    };
    
    const db = debounce(test, 1000);
    const cb = () => {
      db('test');
    };
    const button = document.createElement('button');
    button.innerHTML = 'fire';
    document.body.appendChild(button);
    button.addEventListener('click', cb);
    

    Demo

  • Minimum Window Substring – Java

    The brute force method would be calculate all the substrings, which would be inefficient.

    Runtime Complexity O(m + n)

    Space Complexity O(m+n)

    class Solution {
        public String minWindow(String s, String t) {
            int tLen = t.length();
            int sLen = s.length();
            if (tLen > sLen)
                return "";
            int[] pattern = new int[256];
            int[] given = new int[256];
            for (int i = 0; i < tLen; i++)
                pattern[t.charAt(i)]++;
            int mstart = 0, size = 0, start = 0, min = sLen + 1;
            for (int j = 0; j < s.length(); j++) {
                char curr = s.charAt(j);
                if (given[curr] < pattern[curr])
                    size++;
                given[curr]++;
                if (size == tLen) {
                    while (given[s.charAt(start)] > pattern[s.charAt(start)]) {
                        given[s.charAt(start)]--;
                        start++;
                    }
                    int len = j - start + 1;
                    if (len < min) {
                        min = len;
                        mstart = start;
                    }
                }
            }
            if (size < tLen)
                return "";
            return s.substring(mstart, mstart + min);
        }
    }
  • UTF-8 Validation – Java

    Hint UTF-8 ranges between 1 to 4 bytes (8-bits).

    Runtime: O(n)

    class Solution {
        public boolean validUtf8(int[] data) {
            int n = data.length;
            int skip = 0b10000000;
            int check = 0;
            for (int currByte: data) {
                if (check > 0) {
                    if ((currByte & skip) == skip)
                        check--;
                    else
                        return false;
                } else {
                    check = getHeadType(currByte);
                    if (check < 0) return false;
                }
            }
            return check == 0;
        }
    
        public int getHeadType(int num) {
            if ((num & 0b11110000) == 0b11110000 && (num & 0b00001000) != 0b00001000) return 3;
            if ((num & 0b11100000) == 0b11100000 && (num & 0b00010000) != 0b00010000) return 2;
            if ((num & 0b11000000) == 0b11000000 && (num & 0b00100000) != 0b00100000) return 1;
            if ((num & 0b10000000) == 0b10000000) return -1; //error
            return 0;
        }
    }

     

     

  • K Empty Slots – Java

    Time O(nlogn)
    Space O(n)

    class Solution {
        public int kEmptySlots(int[] flowers, int k) {
            if (flowers.length == 1 && k == 0) return 1;
            TreeSet < Integer > set = new TreeSet < Integer > ();
            for (int i = 0; i < flowers.length; i++) {
                int curr = flowers[i];
                Integer higher = set.higher(curr);
                if (higher != null && higher - curr == k + 1) {
                    return i + 1;
                }
                Integer lower = set.lower(curr);
                if (lower != null && curr - lower == k + 1) {
                    return i + 1;
                }
                set.add(curr);
            }
            return -1;
        }
    }
  • Top K Frequent Elements – Java

    Runtime O(nlogn)

    class Solution {
        public List<Integer> topKFrequent(int[] nums, int k) {
            HashMap<Integer, Integer> times = new HashMap<Integer, Integer>();
            for(int i=0; i<nums.length; i++) {
                if(times.get(nums[i])!=null) {
                    times.put(nums[i], times.get(nums[i])+1);
                } else {
                     times.put(nums[i], 1);
                }
            }
            List<Integer> list = new ArrayList<Integer>(times.keySet());
            list.sort((a,b)->times.get(b)-times.get(a));
            return list.subList(0,k);
        }
    }

    (more…)

  • Reverse Words in a String – Java

    Using a Stack
    Uses O(n) memory and time.

    public class Solution {
        public String reverseWords(String s) {
            s = s.trim();
            Stack<String> track = new Stack<String>();
            String word = "";
            int i=0;
            while (i < s.length()) {
                if (s.charAt(i) == ' ') {
                    track.push(word);
                    word = "";
                    while(i<s.length() && s.charAt(i) == ' ')
                        i++;
                    continue;
                }
                word +=s.charAt(i++);
            }
            if (word != "") {
                track.push(word);
            }
            s = "";
            while(!track.isEmpty()) {
                s+= track.pop()+" ";
            }
            
            return s.trim();
        }
    }

    (more…)

  • Generate Parenthesis

    JavaScript

    /**
     * @param {number} n
     * @return {string[]}
     */
    const generateParenthesis = (n) => {
      const ret = [];
      computeParenthesis(n, n, '', ret);
      return ret;
    };
    
    const computeParenthesis = (open, close, str, ret) => {
      if (close === 0) {
        return ret.push(str);
      }
      if (open > 0) {
        computeParenthesis(open - 1, close, str + '(', ret);
      }
      if (close > open) {
        computeParenthesis(open, close - 1, str + ')', ret);
      }
    };

    Java

    class Solution {
        List<String> list;
        public List<String> generateParenthesis(int n) {
            list = new ArrayList<String>();
            genP("", n, n);
            return list;
        }
        
        public void genP(String str, int open, int close) {
            if (close == 0) {
              list.add(str);
              return;
            } 
            if (open > 0) {
              genP(str + '(', open - 1, close);
            }
            if (close > open) {
              genP(str + ')', open, close - 1);      
            }
        }
    }

  • Sort Array by Parity – Java

    This solution runs in 0(n) time (linear) and uses O(1) space (constant) and is based on the Dutch National Flag Problem.

    class Solution {
        public int[] sortArrayByParity(int[] A) {
            int low = 0, mid = 0, high = A.length - 1;
            int temp;
            while (mid <= high) {
                if (A[mid] == 0) {
                    temp = A[mid];
                    A[mid] = A[low];
                    A[low] = temp;
                    low++;
                    mid++;
                } else if (A[mid] % 2 == 0) {
                    mid++;
                } else {
                    temp = A[mid];
                    A[mid] = A[high];
                    A[high] = temp;
                    high--;
                }
            }
            return A;
        }
    }

     

  • Two Sum

    Optimized for runtime.
    Time O(n)
    Memory O(n)

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            int[] ret = new int[2];
            HashMap < Integer, Integer > map = new HashMap < Integer, Integer > ();
            for (int i = 0; i < nums.length; i++) {
                if (map.get(nums[i]) != null) {
                    ret[0] = map.get(nums[i]);
                    ret[1] = i;
                    return ret;
                }
                map.put(target - nums[i], i);
            }
            return ret;
        }
    }
  • Search in Rotated Sorted Array

    Solution uses a modified version of Binary Search.
    Javascript (ES6)

    /**
     * @param {number[]} nums
     * @param {number} target
     * @return {number}
     */
    const search = (nums, target) => {
      let low = 0;
      let high = nums.length - 1;
      while (low <= high) {
        const mid = low + Math.floor((high - low) / 2);
        if (nums[mid] === target) {
          return mid;
        }
        if (nums[low] <= nums[mid]) {
          // Left half is sorted.
          if (target >= nums[low] && target < nums[mid]) {
            high = mid - 1;
          } else {
            low = mid + 1;
          }
        } else {
          // Right half is sorted.
          if (target > nums[mid] && target <= nums[high]) {
            low = mid + 1;
          } else {
            high = mid - 1;
          }
        }
      }
      return -1;
    };
    
    console.log(search([4, 5, 1, 2, 3], 2)); // 3
    

    Demo

    Java

    Time: O(nlogn)
    Space: O(1)

    class Solution {
     public int search(int[] nums, int target) {
      int low = 0, high = nums.length - 1;
      int mid;
      while (low <= high) {
       mid = low + (high - low) / 2;
       if (nums[mid] == target)
        return mid;
       else if (nums[mid] < nums[high]) {
        if (target > nums[mid] && target <= nums[high])
         low = mid + 1;
        else
         high = mid - 1;
       } else {
        if (target >= nums[low] && target < nums[mid])
         high = mid - 1;
        else
         low = mid + 1;
       }
      }
      return -1;
     }
    }