Identifying Primitive and Reference Types in Javascript

5 Primitive Types: Number, Boolean, String, Null, Undefined

typeof “abc” => string
typeof “true” => boolean
typeof will work for mostly all of above except null.
typeof null will return “object”.
So to verify “null” just compare to null. (value == null)

6 Reference Types: Function, Object, Array, Date, Error, RegExp

typeof object will be “object”
typeof function will be “function”

for all the rest use instanceof to identity

items instanceof Array

Note that items instanceof Object will also return true since instanceof can identity inherited types.

For Array, if you are using frames and communicating values between frames then instanceof may not provide accurate results if you are checking instanceof. Its recommended to use Array.isArray(items) in that case.

Find kth largest element in an unsorted array

Method 1 (Simple Solution)
A Simple Solution is to sort the given array using a O(nlogn) sorting algorithm like Merge Sort, Heap Sort, etc and return the element at index k-1 in the sorted array. Time Complexity of this solution is O(nLogn).

Method 2 (QuickSelect)
Using technique similar to quicksort.
Complexity is O(n^2) but avg case is O(n)

Method 3 (Using Min Heap – HeapSelect)
We can find k’th smallest element in time complexity better than O(nLogn). A simple optomization is to create a Min Heap of the given n elements and call extractMin() k times.

Longest Substring between 2 Strings

Algorithm:
1) Make a matrix m x n where m = string1 length and n = string2 length
2) if str1[i] != str2[j] then put matrix element as 0
3) if str1[i] == str2[j] then put matrix element as 1 + previous diagonal element. set max
4) form the longest substring by examining max element in matrix and going back diagonally to collect previous characters

$str1 = "GeeksForGeeks";
$str2 = "AllGeeksQuiz";
$len1 = strlen($str1);
$len2 = strlen($str2);
$matrix = array();
$max = 0;
for ($i = 0; $i < $len1 ; $i++) {
    for ($j = 0; $j < $len2 ; $j++) {
        if ($str1[$i] == $str2[$j]) {
            if (($i == 0) || ($j == 0))
                $matrix[$i][$j] = 1;
            else
                $matrix[$i][$j] = $matrix[$i-1][$j-1] + 1;
            if ($matrix[$i][$j] > $max) {
                $maxI = $i;
                $maxJ = $j;
                $max = $matrix[$i][$j];
            }
        }
    }
}

if ($max > 0) {
    $substring = '';
    for ($k = 0; $k < $max ; $k++) {
        $substring = $str1[$maxI-$k] . $substring;
    }
    echo "Longest Substring: $substring\n";
} else {
    echo "No substring\n";
}

https://www.youtube.com/watch?v=BysNXJHzCEs

Generate Prime Numbers in the 1..x range

Generate Prime Numbers in the 1..x range.

http://leetcode.com/2010/04/finding-prime-numbers.html

/* Generate a prime list from 0 up to n, using The Sieve of Erantosthenes
param n The upper bound of the prime list (including n)
param prime[] An array of truth value whether a number is prime
*/

void prime_sieve(int n, bool prime[]) {
  prime[0] = false;
  prime[1] = false;
  int i;
  for (i = 2; i <= n; i++) {
    prime[i] = true;
  }
  int limit = sqrt(n);
  for (i = 2; i <= limit; i++) {
    if (prime[i]) {
      for (int j = i * i; j <= n; j += i)
        prime[j] = false;
    }
  }
}

Find all permutations of a given string

Find all permutations of a given string:

// function to generate and print all N! permutations of $str. (N = strlen($str)).
function permute($str,$i,$n) {
   if ($i == $n)
       print "$str\n";
   else {
        for ($j = $i; $j < $n; $j++) {
          swap($str,$i,$j);
          permute($str, $i+1, $n);
          swap($str,$i,$j); // backtrack.
       }
   }
}

// function to swap the char at pos $i and $j of $str.
function swap(&$str,$i,$j) {
    $temp = $str[$i];
    $str[$i] = $str[$j];
    $str[$j] = $temp;
}   

$str = "hey";
permute($str,0,strlen($str)); // call the function.

Diagram: http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/

PHP Implementation:
http://stackoverflow.com/questions/2617055/how-to-generate-all-permutations-of-a-string-in-php

json_encode vs serialize

1) json_encode will produce a smaller string and is easy to read.
2) JSON is more portable. json is easily understandable by Javascript as well
3) JSON will have no memory of what the object’s original class was (they are always restored as instances of stdClass).

Qualys Phone Interview

1) Difference between interface and abstract class
2) How would you provide security to a web application?
3) Diff between call by value and call by reference
4) Multiple inheritance in PHP

True Multiple inheritance is not possible in PHP. However it can be simulated  by a mix of extending a class + “implementing” multiple interfaces / “using” multiple traits.
5) Does PHP pass objects by reference or by value

Simple answer is by reference. If you pass object to a function and it gets modified inside the function the changed value will be visible outside the function too.  However Just remember: pointers to objects, not objects
themselves, are passed to functions. These pointers are COPIES of the
original unless you use "&" in your parameter list to actually pass
the originals. Only when you dig into the internals of an object will
the originals change. So as such it can also be said that the object pointers are passed by value.

Good explanations:
https://www.php.net/manual/en/language.oop5.references.php
https://stackoverflow.com/questions/879/are-php-variables-passed-by-value-or-by-reference

6) What is ob_start in PHP
7) Which Design Patterns have you worked with?
8) Difference between valid xml and well formed xml

8) Given a string “This is Bob who has been working since 2002 in this industry. Wow 2002.”
write a program to determine which words in this string are palindromes.
Output should be
“Bob”
“2002”

Things to remember while writing the solution:
1) lowercase the string while checking for palindrome
2) Remove fullstops,etc. Account for multiple spaces between words.
3) The string can contain multiple Bob or 2002. So use a hash table to store the palindromes which are found. So that if that word occurs again then you don’t have to process it again.

9) Given the following schema, write a query which will produce the given output:

GRADE 
  ID   GRADE
   1    A
   2    B
   3    C

STUDENT:
  ID   NAME
   1    John 
   2    Matt
   3    Allie

STUDENT_GRADES: 
 STUDENT_ID   GRADE_ID 
  1              1
  2              2
  3              1

OUTPUT: 
  GRADE   STUDENTS
   A       John, Allie
   B       Matt
   C       NULL


SELECT G.GRADE, GROUP_CONCAT(S.NAME)
    FROM grade G 
        LEFT JOIN student_grade SG 
              ON G.ID = SG.grade_id
        LEFT JOIN student S
              ON S.ID = SG.student_id
        
    GROUP BY G.GRADE

Implement a Linked List in PHP

class Node {
  public $val;
  public $next;

  function __construct($val) {
      $this->val = $val;
      $this->next = $null;
  }
}

class LinkedList {
  public $head;

  function __construct() {
      $this->head = null;
  }

  function InsertNode($val) {
      $node = new Node($val);
      if ($this->head) {
          $current = $this->head;
          while ($current != null) {
              $prev = $current;
              $current = $current->next;
          }
          $prev->next = $node;
      } else {
          $this->head = $node;
      }
  }

  function PrintAll() {
      $current = $this->head;
      while ($current != null) {
          print $current->val . "\n";
          $current = $current->next;
      }
  }
}

$linkedList = new LinkedList();
$linkedList->InsertNode(1);
$linkedList->InsertNode(3);
$linkedList->InsertNode(2);

$linkedList->PrintAll();

Example of Associative Array in Javascript

Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence “The quick brown fox jumps over the lazy dog” repeatedly, because it is a pangram. (Pangrams are sentences constructed by using every letter of the alphabet at least once.)

After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams.

Given a sentence , tell Roy if it is a pangram or not.

E.g: We promptly judged antique ivory buckles for the next prize

function processData(input) {
    //Enter your code here
    var inpArr = input.split("");
    var uinput = input.toUpperCase();
    var freqObj = {};
    for (var a=65; a <= 90 ; a++) {
        var s = String.fromCharCode(a);
        freqObj[s] = 0;  // associative array as an object
    }
    
    for (var i = 0; i < uinput.length ; i++) {
        
        var char = uinput[i];
        //if (char in freqObj) {
        if ((char in freqObj) && (freqObj.hasOwnProperty(char)) ) {
            freqObj[char] = 1;
        } 
        
    }
    
    var okeys = Object.keys(freqObj);
    var sum = 0;
    for (var k = 0; k < okeys.length; k++) {
        if (freqObj.hasOwnProperty(okeys[k])) {
            sum += freqObj[okeys[k]];
        }
    }
    
    if (sum == 26) {
        console.log("pangram");
    } else {
        console.log("not pangram");
    }
    
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

PHP Reading from command line

$handle = fopen ("php://stdin","r");
// if single input (having no spaces)
fscanf($handle,"%d",$n);
// if trying to read 2 values separated by a space
fscanf($handle,"%d %s",$d,$s);
// if trying to read a string having spaces
$inp = trim(fgets($handle));