Categories
interview

Throttling function calls with a Queue in Javascript (ES6)

The following ES6 Javascript code, helps to throttle function calls without discarding them. It uses a queue to keep track of all the function calls. We can use the reset method to reset the queue and the setTimeout() method.

Demo

Categories
interview

Longest Palindromic Substring

/**
 * @param {string} s
 * @return {string}
 */
var longestPalindrome = function(s) {
  if (!s || s.length === 0)
    return '';
  let start = 0,
    end = 0;
  for (let i = 0; i < s.length; i++) {
    // There can be 2n - 1 centers for the palindromes. We can 
    // include each character and the space in between the       
    // characters.
    let l1 = expandAroundCenters(s, i, i);
    let l2 = expandAroundCenters(s, i, i + 1);
    let l = Math.max(l1, l2);
    if (l > end - start) {
      start = i - Math.floor((l - 1) / 2);
      end = i + Math.floor(l / 2);
    }
  }
  return s.substring(start, end + 1);
};

var expandAroundCenters = function(s, left, right) {
  while (left >= 0 &&
    right < s.length &&
    s.charAt(left) === s.charAt(right)) {
    left--;
    right++;
  }
  return right - left - 1;
}

// Time Complexity O(n ^ 2)
// Space Complexity O(1)
Categories
interview

Smooth Animation

The following is a method to perform smooth animation of an element from left to right given the duration and distance. 60 frames per second (fps) is the minimum required frame rate for smooth animation. In this example, the element is being animated from left to right at 60 fps for a duration of 2 seconds (2000 ms) and a distance of 100px.

Javascript (ES6)

HTML

CSS

DEMO

Categories
interview

Random Pick Index

Given an input array that consists of numbers that may consist of duplicates, return the position of the number that is picked. This position has to be a “Random Pick Index” if the picked number has duplicates.

Example: Input: [1, 2, 4, 4, 4], Pick -> 4 then you can return 2, 3, or 4 randomly with equal probability. If 1 is the pick then 0 needs to be returned as there is only one occurrence at 0.

Categories
interview

DFS DOM (ES6)

<div id="root">
  <div>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
  </div>
  <div>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
  </div>
</div>
const root = document.getElementById("root");

const walk = function (root) {
  let obj = root.children;
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (obj[key].textContent === "1") 
        console.log(obj[key]);
      else 
        walk(obj[key]);
    }
  }
};

walk(root);