Infogain Questions

1) Given some text find all valid email addresses in it.

$ret = array();

function isValidEmail($word) {
$domain_parts = array();
$domain = "";

$components = explode("@", $word);

if (count($components) != 2) {
return false;
} else {
$domain = $components[1];
$domain_parts = explode(".", $domain);
if (count($domain_parts) < 2) {
return false;
}
}
return true;
}

function findEmailAddresses($input) {
$result = array();
if ((!$input) || empty($input)) {
return $result;
}
$words = explode(" ", $input);
foreach ($words as $word) {
if (isValidEmail($word)) {
$result[] = $word;
}
}
return $result;
}

$str = "This valid@email.com is just a test abc@ when @pqr is abc@pqr.com.";
$ret = findEmailAddresses($str);

var_dump($ret);

2) Given some text and an array of keywords, find all the words in the text which are any combination of the keywords. The below is by sorting. But another way is by hashing the keyword.

<?php

$ret = array();

function mysort($str) {
$arr = str_split($str);
sort($arr, SORT_STRING);
return implode("",$arr);
}

function findCombinations($input, $keywords) {
$result = array();
if ((!$input) || empty($input)) {
return count($result);
}
foreach ($keywords as $keyword) {
$sortedKeywords[] = mysort($keyword);
}
var_dump($sortedKeywords);
$inputArr = explode(" ", $input);
foreach ($inputArr as $word) {
$sortedInput[] = mysort($word);
}
var_dump($sortedInput);
foreach ($sortedInput as $sortedWord) {
if (in_array($sortedWord, $sortedKeywords)) {
$result[] = $sortedWord;
}
}
return $result;

}

$str = "This valid@email.com the is eht just a test abc@ when @pqr is abc@pqr.com.";
$keywords = array("het", "opo");
$ret = findCombinations($str, $keywords);

var_dump($ret);
?>

Interview challenge : getMovieTitles

Myriad Systems.

To solve this challenge, write an HTTP GET method to retrieve information from a particular movie database.

https://stackoverflow.com/questions/48448432/fragment-of-missing-code-in-the-solution-movie-titles-complete-a-challenge-more

function getMovieTitlesData(title, page = 1) {
   const url = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + title + '&page=' + page;
   console.log('URL:',url);
   const titles = [];
   return new Promise((resolve, reject) => {
      fetch(url, {
        method: 'get',
      }).then((response) => {
        return response.json();
      }).then((jsondata) => {
        for (let i = 0; i < jsondata.data.length; i++) {
           titles.push(jsondata.data[i].Title);
      }
      var total_pages = Number(jsondata.total_pages); 
      var curpage = Number(jsondata.page); 
      resolve({
         titles : titles,
         page : page,
         total_pages : total_pages
      });
    }).catch((error) => {
      console.log("Failure", error);
    })
  })

}


function getMovieTitles(substr) {
   const promises = [];
   const titles = []; 
   getMovieTitlesData(substr).then(result => {
     titles.push(...result.titles);
     for (let i = result.page + 1; i <=result.total_pages; i++) {
        promises.push(getMovieTitlesData(substr, i));
     }
     Promise.all(promises).then(datas => {
       datas.forEach(data => {
          titles.push(...data.titles);
       });
       console.log(titles.sort());

     });
  })
}

getMovieTitles('spiderman');

 

 

Trulia Phone Interview

PHP

1) Difference between interface and abstract class. Write code to show example of each. Can a class derive from abstract class and implement an interface as well? (Yes)

2) Write a function to test a palindrome.

Javascript :
1) What is the difference between
x = 1;
var x = 1;
window.x = 1;

2) Write a function to add an array of numbers using the arguments variable

var data = [1,2,3,4];
console.log(sum(data));

function sum() {
   var myData = arguments[0];
   return myData.reduce(function (acc, num) { acc += num; return acc});
}

3) write a function to implement mult(4)(5)

function mult(x) {
   return function(y) {
       return x*y;
   }
}

var ans = mult(4)(5);

Still concise :

function mult(num1) {
  return num2 => num1 * num2;
}

console.log(mult(4)(5));

4) Write a function to output alert(1), alert(2) every 1 second till 5 times
Similar to question asked in Ten-X interview.

5) write a function to put spaces in a string “Hello World” ==> “H e l l o W o r l d”.

var spacify = function (str) {
    return str.split('').join(' ');
};

console.log(spacify("Hello"));

Is it possible to write a function spacify like “hello world”.spacify()

String.prototype.spacify = String.prototype.spacify || function() {
  return this.split('').join(' ');
};

console.log("Hello".spacify());

Yahoo Phone Interview

1) Write a function to accept seconds and print time in format hh:mm:ss
2) If the same function is to be used multiple times how would we optimize the code so that we don’t have to calculate it each time. (hint: use static)

 
function formatTime($seconds) {
    if !($seconds) {
        return "";
    }
    static $timeArray = array();
    if (isset($timeArray[$seconds])) {
        echo "using cache\n";
        return $timeArray[$seconds];
    }
    $origSeconds = $seconds;
    $hours = floor($seconds / 3600);
    $seconds = $seconds % 3600;
    $mins = floor($seconds / 60);
    $seconds = $seconds % 60;
    $ret = sprintf("%02d::%02d::%02d", $hours, $mins, $seconds);
    $timeArray[$origSeconds] = $ret;
    return ($ret);
}

Another example of memoizing a function:

$memoize = function($func)
{
    return function() use ($func)
    {
        static $cache = [];

        $args = func_get_args();

        $key = md5(serialize($args));

        if ( ! isset($cache[$key])) {
            $cache[$key] = call_user_func_array($func, $args);
        }

        return $cache[$key];
    };
};

$fibonacci = $memoize(function($n) use (&$fibonacci)
{
    return ($n < 2) ? $n : $fibonacci($n - 1) + $fibonacci($n - 2);
});

3) Can cookies be stolen ?
Yes cookies can be stolen. XSS is one way to do it.
https://www.go4expert.com/articles/stealing-cookie-xss-t17066/

4) Interface vs Abstract class
5) When does the page on screen get refreshed ?
Repainting and Reflowing
http://frontendbabel.info/articles/webpage-rendering-101/
http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/
http://taligarsiel.com/Projects/howbrowserswork1.htm

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

Ten-X Interview

1) Write a javascript function to print an array slowly (e.g each element in intervals of 500 ms). Example of array : 1,5,6,’cool’,8. Once done then print “all done”.

Method-1

var arr = [1,5,6,"cool",8];

function foo(i) {
   console.log("i:" + i + ":" + arr[i]);

}

function foo2() {
   console.log("all done");
}

for (i=1; i <=3 ; i++) {
    setTimeout(foo, i*500, i);
}

setTimeout(foo2, (i)*500);

Disadvantage in Method-1 is that so many setTimeout will be in memory. In Method-2 the number of setTimeout in memory will be less.

Method-2

var arr = [1,5,6,'cool', 8];

function foo(i) {
if (i < arr.length) {
console.log("i:" + i + ":" + arr[i]);
setTimeout(foo, 500, i+1);
} else {
console.log("all done");
}
}

setTimeout(foo, 500, 0);

Method-3

const arr = [10, 12, 15, 21];
for (let i = 0; i < arr.length; i++) {
  // using the ES6 let syntax, it creates a new binding
  // every single time the function is called
  // read more here: http://exploringjs.com/es6/ch_variables.html#sec_let-const-loop-heads
  setTimeout(function() {
    console.log('The index of this number is: ' + i);
  }, 3000*i);

Method-4

for (i = 0, max = 9; i < max ; i ++) {
  setTimeout(printFunc(i), 500*i);
}

function printFunc(i) {
   return function() {
       console.log(i);
   }
}

Method-5. (Using IIFE – Immediately Invoked Function Expression)

var arr = [1,5,6,"cool",8];

for (i=0; i < arr.length ; i++) {
   (function(i) {
    setTimeout(foo, i*1500, i);
   }(i))
}
function foo(i) {
   console.log("i:" + i + ":" + arr[i]);

}

function foo2() {
   console.log("all done");
}


setTimeout(foo2, (i)*1500);

 

2) Given a string “San Francisco Hotel” and a array of strings (e.g. San Jose Culture of Art, Father Francisco and San Mateo”, “Yahoo”, “I love Hotel”) etc find out the best match. For example in above “Father Francisco and San Mateo is best match since it contains San and Francisco.

You can index all given individual strings. For example “San”, “Jose”, “Culture”, “Art”, etc  mapping name to index of string where it appears.

San ==> array(0,1)

Jose ==> array (0)

Culture ==> array(0)

Art ==> array(0)

Father ==> array(1)

Francisco ==> array(1)

Mateo ==> array(1)

Hotel ==> array(3)

Then to search for an input string, You can get all the results for each word in the input string and combine the resultant set in a hash which contains which word occurs how many times.

For San Francisco Hotel you will need to show strings : 0,1,3 for sure. However to rank these strings you can use a hash which will show you which word appears more times.

result[1] ==> 2  (string at index 1 contains 2 matching words)

result[0] ==> 1 (string at index 0 contains 1 matching word)

result[3] ==> 1  (string at index 3 contains 1 matching word)

 

3) Given a sorted array return a random array.

4) Given an array of N numbers return the max product of 3 numbers. Example if the array contains [4,2,7,5,3] then the max product possible is 4 * 7 * 5 = 140.

5) In Javascript Using functional programming , given an array of numbers, return the sum of their squares.

var arr = [2,4,6,8];

var sum = arr.map(function(s) { return s*s;}).reduce(function(acc, val) {return acc + val;});

Interview questions from Pinank

here are the questions:
1. Given a library of Stack with 2 functions (push(x), pop()), implement a queue library (i.e. enqueue(x), dequeue())
Use 2 stacks:
enqueue() : keep push(x)ing in Stack1 only
dequeue() : keep pop()ing from Stack2 only. (Incase Stack2 is empty, pop() everything from Stack1 to push() into Stack2) and then pop() from Stack2

2. Explain working of HTTP protocol (some people answer in quite detail (about DNS lookup, TCP handshake, etc.)

3. How can you implement a HashTable?
Use an ‘Array’ to store values. (Each array element is actually a linked-list, so 2 values having same key can be inserted at the same-element in the Array.
Also need 2 functions:
a) to get hash-key (to decide where to store the element in the array)
b) compare() : I forgot the exact reason, but i think its used for resolving collision. (In Java they also store the ‘key’ along with the object’ instead of just storing the object and this compare() function is then used .. i’ll try to find the document that has more details on how its used..
c) Some people also ask what are good options of hash-functions ? (it will depend on type of data, but some common options are ‘mod’ function) e.g. 57 mod 8 = 1 (if array size is 8) ..

Must Know Algorithms

As per Cracking the Coding Interview:

Data Structures
Linked Lists
Binary Trees
Tries
Stacks
Queues
Vectors/ArrayLists
Hash Tables

Algorithms
Breadth First Search
Depth First Search
Binary Search
Merge Sort
Quick Sort
Tree Insert/Find/etc

Concepts
Bit Manipulation
Singleton Design Pattern
Factory Design Pattern
Memory (Stack vs Heap)
Recursion
Big-O Time

Software Architect Interview Questions

What do you understand from the word Architecture? What is meant by software Architecture?

What kind of Software Architecture have you designed till now? Can you explain with the help of commands and patterns?

Which kind of design patterns have you used while building software architecture?

Explain pattern? What is design pattern and factory pattern? Where can these be used?

What is the use of builder pattern? Why it is so important in Software Architecture?

What is shallow copy and deep copy in prototype pattern? Describe: singleton and command pattern?

Numerate the advantages and disadvantages of composition and inheritance in Software Architecture?

When do you use abstract class and what are the conditions to use interfaces?

Explain the difference between object oriented, interface oriented and aspect oriented design and programming?

In which case do you use interface oriented and aspect oriented designs?

Difference between Object Oriented Programming and Component Oriented Programming
https://www.safaribooksonline.com/library/view/programming-net-components/0596102070/ch01s02.html