Archive for the ‘Interview Questions’ Category

Return positions of matching closing parenthesis

Wednesday, November 25th, 2015
def get_closing_paren(sentence, opening_paren_index):
    open_nested_parens = 0
    position = opening_paren_index + 1

    for char in sentence[position:]:
        if char == '(':
            open_nested_parens += 1
        elseif char == ')':
            if open_nested_parens == 0:
                return position
            else:
                open_nested_parens -= 1
        position += 1

    raise Exception("No closing parenthesis :(")

source: https://www.interviewcake.com/question/matching-parens

OOP vs Functional Programming

Wednesday, August 12th, 2015

Short story, add reviewing this to my before interviews list:
https://en.wikipedia.org/wiki/Comparison_of_programming_paradigms

Reverse Linked List JavaScript

Monday, August 3rd, 2015

Reverse a Linked List in Javascript.
Requires Underscore.js
also here:
http://jsfiddle.net/afrascona/fuhmhqf3/

Array.prototype.getLinkedList = function () {
    var i,
        head;    
    for (i = this.length - 1; i >= 0; i -= 1) {
        head = {
            value: this[i],
            next: head
        };
    }
    return head;
};

function reverseList (head) {
    var current = head,
        tempHead,
        previous;
    while ('object' === typeof current) {
        tempHead = current.next;
        current.next = previous;
        previous = _.clone(current);
        current = _.clone(tempHead);
    }
    return previous;
}

var list = [0,1,2,3,4,5,6,7,8,9].getLinkedList();

console.dir(list);
console.dir(reverseList(list));

MxN Matrix 0 element makes row & column 0s

Monday, August 3rd, 2015
var matrix = [
	[ 2, 3, 1, 4, 5 ],
	[ 4, 6, 0, 9, 8 ],
	[ 3, 2, 1, 8, 2 ],
	[ 6, 3, 4, 7, 6 ],
	[ 8, 5, 7, 2, 1 ]
	],
	saveRows = [],
	saveColumns = [],
	i,
	j;

var onceRowLength = matrix.length;
var onceColumnLength = matrix[0].length;

function displayMatrix(matrix) {
	for ( i = 0; i < onceRowLength; i++ ) {
		for ( j = 0; j < onceColumnLength; j++ ) {
			document.writeln(matrix[i][j]);
		}
		document.writeln('<br />');
	}
}

function saveRowsAndColumns(matrix) {
	for ( i = 0; i < onceRowLength; i++ ) {
		for ( j = 0; j < onceColumnLength; j++ ) {
			if ( matrix[i][j] == 0) {
				saveRows[i] = true;
				saveColumns[j] = true;
			}
		}
	}
}

function zeroTheMatrix(matrix) {
	for ( i = 0; i < onceRowLength; i++) {
		for ( j = 0; j < onceColumnLength; j++ ) {
			if ( saveRows[i] || saveColumns[j] ) {
				matrix[i][j] = 0;
			}
		}
	}
}

displayMatrix(matrix);
saveRowsAndColumns(matrix);
zeroTheMatrix(matrix);
document.writeln('<br />');
displayMatrix(matrix);

String of all unique characters?

Sunday, August 2nd, 2015
function isUnique(str){

	//more than 256 chars means at least one is not unique assuming ASCII
	if( str.length>256 ) { return false; } 

	    //array for which chars have been used
	    var char_set = [];
	    var i;

	    //iterate over the string
	    for( i = 0; i < str.length; i++ ) {

	        val = str[i];

	        //if this has been set to true this char is not unique
	        if( char_set[val] ) {
	            return false;
	        }

	        //record this char
	        char_set[val] = true;
	    } 

	//string is unique
	return true;
}
document.writeln(isUnique('abcd'));
document.writeln(isUnique('abcdd'));

Interview Fisher-Yates Shuffle in-place algorithm JavaScript

Wednesday, July 29th, 2015
function shuffle(arrayToShuffle) {
  var arrayLengthCountdown = 	arrayToShuffle.length,
  								lastElementVal,
  								randomIndex;

  while (arrayLengthCountdown) {

    // Pick a random element from the shortening 'length' of the array, the 'front'
    randomIndex = Math.floor(Math.random() * arrayLengthCountdown--);

    console.log('randomIndex: ' + randomIndex + ' arrayLengthCountdown: ' + arrayLengthCountdown + '; swapping ' + arrayToShuffle[randomIndex] + ' with ' + arrayToShuffle[arrayLengthCountdown]);

    // And swap it with the last element of the shortening 'length', taken from the 'back' of the array, which gets injected into the 'front' to await getting shuffled
    lastElementVal = arrayToShuffle[arrayLengthCountdown];
    arrayToShuffle[arrayLengthCountdown] = arrayToShuffle[randomIndex];
    arrayToShuffle[randomIndex] = lastElementVal;

    console.log( arrayToShuffle );
  }

  return arrayToShuffle;
};
shuffle([0,1,2,3,4,5,6,7,8,9]);

Interview JavaScript Module Pattern Singleton

Monday, July 7th, 2014
var accountObj = (function() {
     var balance = 0;
     var type = 'savings';
     return {
          get_balance: function(){
               return balance;
          },
          deposit: function(a){
               balance += a;
          },
     };
}());

var myAccount = accountObj;
document.writeln('Balance: ' + myAccount.get_balance()); // 0
document.writeln('Add 5: ' + myAccount.deposit(5)); // undefined
document.writeln('Balance: ' + myAccount.get_balance()); // 5

Interview JavaScript private methods with closures for multiple objects exercise (not Module Singleton pattern!)

Monday, July 7th, 2014

JavaScript private methods with closures

var accountObj = function() {
     var privateBalance = 0;
     function privateDeposit(val) { privateBalance += val; }
     return {
          deposit: function(n) { privateDeposit(n); },
          balance: function() { return privateBalance; }
     }
};

var myAccount = accountObj();
var yourAccount = accountObj();

myAccount.deposit(10);
console.log('My account balance: ' + myAccount.balance()); //10

yourAccount.deposit(200);
console.log('Your account balance: ' + yourAccount.balance()); //200

myAccount.deposit(5);
console.log('Added 5, balance updated: ' + myAccount.balance()); //15

console.log(myAccount.privateBalance); // undefined

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

Another example:


var animal = function (spec) {
     var privateName = spec.name;
     var privateSaying = spec.saying;
     var privateReturnName = function(){
          return privateName;
     };
     var privateReturnSaying = function(){
          return privateSaying;
     }
     return {
          get_name: function(){
               return privateReturnName();
          },
          get_saying: function(){
               return privateReturnSaying();
          }
     }
};
var myHorse = animal({name: 'Wilbur', saying: 'Neeeeeeh'});
var myPig = animal({name: 'Charlotte', saying: 'Oink!'});
document.writeln(myHorse.get_name() + ' says ' + myHorse.get_saying()); <span style="color: #ff0000;">// Wilbur says Neeeeeeeh
document.writeln(myPig.get_name() + ' says ' + myPig.get_saying());

document.writeln(myPig.privateSaying); // undefined

JavaScript Factorial with Memoization

Sunday, July 6th, 2014
var memoizer = function (memo, formula) {
     var recur = function(n) {
          var result = memo[n];
          if(typeof result !== 'number') {
               result = formula(recur, n);
               memo[n] = result;
          }
          return result;
     };
     return recur;
};
 
var factorial = memoizer([1,1], function (recur, n) {
     return n * recur(n - 1);
});
 
document.writeln(factorial(10)); // 3628800

credit: Crockford, Douglas. JavaScript: The Good Parts, p.45. O’Reilly 2008

JavaScript Fibonacci with & without Memoization

Sunday, July 6th, 2014

// simple Fibonacci w/o Memoization

var fibonacci = function(n){
     return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
};
var showF = function(n){
     for(var i = 0; i <= n; i += 1) {
          document.writeln('//' + i + ': ' + fibonacci(i));
     }
};

showF(10); //55

 

//Fibonacci with Memoization

var fibonacci = (function() {
     var memo = {};

     function f(n) {
          var value;
          if (n in memo) {
               value = memo[n];
          } else {
               if (n === 0 || n === 1)
               value = n;
          } else {
               value = f(n - 1) + f(n - 2);
               memo[n] = value;
          }
          return value;
     }
     return f;
})();

document.writeln(fibonacci(50));

 

// Fibonacci with Memoizer abstracted function

var memoizer = function (memo, formula) {
     var recur = function(n) {
          var result = memo[n];
          if(typeof result !== 'number') {
               result = formula(recur, n);
               memo[n] = result;
          }
     return result;
     };
     return recur;
};

var fibonacci2 = memoizer([0,1], function (recur, n) {
     return recur(n - 1) + recur(n - 2);
});

document.writeln(fibonacci2(50)); <span style="color: #ff0000;">//12586269025</span>

 

credit: Crockford, Douglas. JavaScript: The Good Parts, p.45. O’Reilly 2008

credit: http://www.sitepoint.com/implementing-memoization-in-javascript/

JavaScript Curry

Sunday, July 6th, 2014

// Curry

“Currying allows us to produce a new function by combining a function and an argument”

Function.prototype.method = function (name, func) { // makes Augmenting Types beautifully easy when needed
if (!this.prototype[name]) {
this.prototype[name] = func;
return this;
}
};

var add = function (a, b) {
return a + b;
};

Function.method(‘curry’, function () { // leveraging our Augmentation shortcut…
var slice = Array.prototype.slice,
args = slice.apply(arguments),
that = this;

return function () {
return that.apply(null, args.concat(slice.apply(arguments)));
};
});

var add1 = add.curry(1);
document.writeln(add1(6)); //7

 

credit:

Crockford, Douglas. JavaScript: The Good Parts, p.43. O’Reilly 2008

JAVA count Fibonacci

Wednesday, August 7th, 2013
class Fib {
	public static void main( String[] args ) {
		int f = 0;
		int g = 1;

		for( int i = 1; i <= 10; i++) {
			System.out.print(f + " ");
			f = f + g;
			g = f - g;
		}

		System.out.println();
	}
}

reverse a String

Wednesday, August 7th, 2013

JAVA

class Reverso{
	public static void main(String[] args) {
		for (String toReverse: args) {
			int countOf = toReverse.length();
			for(int $i = toReverse.length() - 1; $i >= 0; $i--){
				System.out.print(toReverse.charAt($i));
			}
		}
	}
}

JavaScript

var reverse = function(str) {
    var arr = [];

    for (var i = 0, len = str.length; i <= len; i++) {
        arr.push(str.charAt(len - i))
    }

    return arr.join('');
}

document.writeln(reverse('lorem ipsum dolor'));

PHP DoublyLinkedList example

Monday, August 5th, 2013

/*

* Examples of DoublyLinkedList
*/

$obj = new SplDoublyLinkedList();

// Check wither linked list is empty
if ($obj->isEmpty())
{
echo “Adding nodes to Linked List<br>”;
$obj->push(2);
$obj->push(3);

echo “Adding the node at beginning of doubly linked list <br>”;
$obj->unshift(10);
}

echo “<br>Our Linked List:”;
print_r($obj);

echo “<br>Pick the node from beginning of doubly linked list”;
echo $obj->bottom();

/**
Our Linked List:SplDoublyLinkedList Object ( [flags:SplDoublyLinkedList:private] => 0 [dllist:SplDoublyLinkedList:private] => Array ( [0] => 10 [1] => 2 [2] => 3 ) )
Pick the node from beginning of doubly linked list10
*/

Factorial of n recursive and iterative

Monday, August 5th, 2013

Recursive solution:

public int Factorial ( int n ) {
	if ( n == 0 ) {
		return 1;
	} else {
		return n * Factorial(n-1);
	}
}

Iterative Solution:

public int factorial ( int input ) {
	int x, fact = 1;
	for ( x = input; x > 1; x--) {
		fact *= x;
	}
	return fact;
}

Detect a Palindrome

Monday, August 5th, 2013
function isPalindrome(input)
{
	var len = input.length;

	var isPalindrome = true;

	// iterate through half the length of the string
	for(j = 0; j<len/2; j++)
	{
		if(input[j] != input[len - 1 -j])
		{
			isPalindrome = false;	
			break;
		}
	}

	return isPalindrome;
}
document.writeln(isPalindrome("hello"));
document.writeln(isPalindrome("Anna"));
document.writeln(isPalindrome("deified"));

Simple Linked List example JavaSript

Wednesday, July 31st, 2013
// items of the list
var bird = {name:'Mockingbird'};
var cat = {name:'Keyboard'};
var dog = {name:'Fort'};
var duck = {name:'Scrooge'};

// the linked-list itself
var animals = {
    head : bird
};

// each item of the list stores a reference to the next one
bird.next = cat;
cat.next = dog;
dog.next = duck;

// output
var animal = animals.head;
while (animal) {
    console.log(animal.name);
    animal = animal.next;
}

source: http://blog.millermedeiros.com/linked-lists/