Javascript Algorithm Examples Flashcards

1
Q

How would you verify a prime number?

A
function isPrime(n){
  var divisor = 2;
  while (n > divisor){
    if(n % divisor == 0){
     return false; 
    }
    else
      divisor++;
  }
  return true;
}

> isPrime(137);
= true
isPrime(237);
= false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How could you find all prime factors of a number?

A
function primeFactors(n){
  var factors = [], 
      divisor = 2;
  while(n>2){
    if(n % divisor == 0){
       factors.push(divisor); 
       n= n/ divisor;
    }
    else{
      divisor++;
    }     
  }
  return factors;
}

> primeFactors(69);
= [3, 23]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do get nth Fibonacci number? - try 1

A
function fibonacci(n){
  var fibo = [0, 1];

if (n <= 2) return 1;

  for (var i = 2; i <=n; i++ ){
   fibo[i] = fibo[i-1]+fibo[i-2];
  }

return fibo[n];
}

> fibonacci(12);
= 144

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do get nth Fibonacci number? - try 2

A
function fibonacci(n){
  if(n<=1)
    return n;
  else
    return fibonacci(n-1) + fibonacci (n-2);  
}

> fibonacci(12);
= 144

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How would you find the greatest common divisor of two numbers?

A
function greatestCommonDivisor(a, b){
  var divisor = 2, 
      greatestDivisor = 1;
  //if u pass a -ve number this will not work. fix it dude!!
  if (a < 2 || b < 2)
     return 1;
  while(a >= divisor && b >= divisor){
   if(a %divisor == 0 && b% divisor ==0){
      greatestDivisor = divisor;      
    }
   divisor++;
  }
  return greatestDivisor;
}

> greatestCommonDivisor(14, 21);
=7
greatestCommonDivisor(69, 169);
= 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How would you merge two sorted array?

A
function mergeSortedArray(a, b){
  var merged = [], 
      aElm = a[0],
      bElm = b[0],
      i = 1,
      j = 1;
  if(a.length ==0)
    return b;
  if(b.length ==0)
    return a;
  /* 
  if aElm or bElm exists we will insert to merged array
  (will go inside while loop)
   to insert: aElm exists and bElm doesn't exists
             or both exists and aElm < bElm
    this is the critical part of the example            
  */
  while(aElm || bElm){
   if((aElm && !bElm) || aElm < bElm){
     merged.push(aElm);
     aElm = a[i++];
   }   
   else {
     merged.push(bElm);
     bElm = b[j++];
   }
  }
  return merged;
}

> mergeSortedArray([2,5,6,9], [1,2,3,29]);
= [1, 2, 2, 3, 5, 6, 9, 29]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How would you swap two numbers without using a temporary variable?

A

function swapNumb(a, b){
console.log(‘before swap: ‘,’a: ‘, a, ‘b: ‘, b);
b = b -a;
a = a+ b;
b = a-b;
console.log(‘after swap: ‘,’a: ‘, a, ‘b: ‘, b);
}

> swapNumb(2, 3);
= before swap: a: 2 b: 3
= after swap: a: 3 b: 2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How would you reverse a string in JavaScript? - try 1

A
function reverse(str){
  var rtnStr = '';
  for(var i = str.length-1; i>=0;i--){
    rtnStr +=str[i];
  }
  return rtnStr;
}

> reverse(‘you are a nice dude’);
= “edud ecin a era uoy”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How would you reverse a string in JavaScript? - try 2

A
function reverse(str){
  var rtnStr = [];
  if(!str || typeof str != 'string' || str.length < 2 ) return str;
  for(var i = str.length-1; i>=0;i--){
    rtnStr.push(str[i]);
  }
  return rtnStr.join('');
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How would you reverse a string in JavaScript? - try 3

A
function reverse(str) {
  str = str.split('');
  var len = str.length,
      halfIndex = Math.floor(len / 2) - 1,
      revStr;
  for (var i = 0; i <= halfIndex; i++) {
    revStr = str[len - i - 1];
    str[len - i - 1] = str[i];
    str[i] = revStr;
  }
  return str.join('');
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How would you reverse words in a sentence?

A
//have a tailing white space
//fix this later
//now i m sleepy
function reverseWords(str){
 var rev = [], 
     wordLen = 0;
 for(var i = str.length-1; i>=0; i--){
   if(str[i]==' ' || i==0){
     rev.push(str.substr(i,wordLen+1));
     wordLen = 0;
   }
   else
     wordLen++;
 }
 return rev.join(' ');
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

If you have a string like “I am the good boy”. How can you generate “I ma eht doog yob”? Please note that the words are in place but reverse.

A
function reverseInPlace(str){
  return str.split(' ').reverse().join(' ').split('').reverse().join('');
}

> reverseInPlace(‘I am the good boy’);
= “I ma eht doog yob”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How will you verify a word as palindrome?

A
function isPalindrome(str){
  var i, len = str.length;
  for(i =0; i isPalindrome('madam')
  = true
> isPalindrome('toyota')
  = false
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

If you have a function that generate random number between 1 to 5 how could u generate random number 1 to 7 by using that function?

A
function rand5(){
   return 1 + Math.random() * 4;
}
function rand7(){
  return 5 + rand5() / 5 * 2;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

from a unsorted array of numbers 1 to 100 excluding one number, how will you find that number

A
function missingNumber(arr){
  var n = arr.length+1, 
  sum = 0,
  expectedSum = n* (n+1)/2;
  for(var i = 0, len = arr.length; i < len; i++){
    sum += arr[i];
  }

return expectedSum - sum;
}

> missingNumber([5, 2, 6, 1, 3]);
= 4

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

From a unsorted array, check whether there are any two numbers that will sum up to a given number?

A
function sumFinder(arr, sum){
  var len = arr.length;
  for(var i =0; i sumFinder([6,4,3,2,1,7], 9);
  = true
> sumFinder([6,4,3,2,1,7], 2);
  = false
17
Q

From a unsorted array, check whether there are any two numbers that will sum up to a given number? - try 2

A
function sumFinder(arr, sum){
  var differ = {}, 
      len = arr.length,
      substract;
  for(var i =0; i sumFinder([6,4,3,2,1,7], 9);
  = true
> sumFinder([6,4,3,2,1,7], 2);
  = false
18
Q

How would you find the largest sum of any two elements?

A

function topSum(arr){

  var biggest = arr[0], 
      second = arr[1], 
      len = arr.length, 
      i = 2;

if (len<2) return null;

  if (biggest biggest){
      second = biggest;
      biggest = arr[i];
    }
   else if (arr[i]>second){
      second = arr[i];
   }

}
return biggest + second;
}

19
Q

Count Total number of zeros from 1 up to n?

A
function countZero(n){
  var count = 0;
  while(n>0){
   count += Math.floor(n/10);
   n = n/10;
  }
  return count;
}

> countZero(2014);
= 223

20
Q

How can you match substring of a sting?

A
function subStringFinder(str, subStr){
  var idx = 0,
      i = 0,
      j = 0,
      len = str.length,
      subLen = subStr.length;

for(; i subStringFinder(‘abbcdabbbbbck’, ‘ab’)
= 0
> subStringFinder(‘abbcdabbbbbck’, ‘bck’)
= 9

//doesn’t work for this one.
> subStringFinder(‘abbcdabbbbbck’, ‘bbbck’)
= -1

21
Q

How would you create all permutation of a string?

A
function permutations(str){
var arr = str.split(''),
    len = arr.length, 
    perms = [],
    rest,
    picked,
    restPerms,
    next;
if (len == 0)
    return [str];

for (var i=0; i
22
Q

Create a function having no parameters declared and print all the arguments passed to it (key ‘in’ methods)

A
function func(){
    for(let key in arguments){
        console.log(arguments[key]);
    }
}
// driver code
func(1, "Hello", true);
23
Q

Create a function having no parameters declared and print all the arguments passed to it (only value method)

A
function func(){
    for(let value of arguments){
        console.log(value);
    }
}
// driver code
func(1, "Hello", true);
24
Q

Design a function which can recieve variable number of arguments in parameters and print them

A
function varArgsFunc(...params){
    params.forEach(function(value, index){
        console.log(index, ": ", value);
    })
}
// driver code
varArgsFunc("Hello", ",", "World", "!!!");
25
Write a function which can return multiple values from a function (array method)
``` function multipleValueReturnFunc(){ const a = 5, b = 10; return [a, b]; } ``` ``` // driver code const [x, y] = multipleValueReturnFunc(); ```
26
Write a function which can return multiple values from a function (obj method)
``` function multipleValueReturnFunc(){ const a = 'Java', b = 'Script'; return { a, b }; } ``` ``` // driver code const {x, y} = multipleValueReturnFunc(); ```
27
Remove Duplicates
function removeDuplicate(arr){ var exists ={}, outArr = [], elm; ``` for(var i =0; i removeDuplicate([1,3,3,3,1,5,6,7,8,1]); = [1, 3, 5, 6, 7, 8] ```
28
String Reverse - whole string - string ++ Method
``` function reverse(str){ var rtnStr = ''; for(var i = str.length-1; i>=0;i--){ rtnStr +=str[i]; } return rtnStr; } ``` > reverse('you are a nice dude'); = "edud ecin a era uoy"
29
String Reverse - whole string - push Method
``` function reverse(str){ var rtnStr = []; if(!str || typeof str != 'string' || str.length < 2 ) return str; ``` ``` for(var i = str.length-1; i>=0;i--){ rtnStr.push(str[i]); } return rtnStr.join(''); } ```
30
Check - am I a Palindrome
``` function isPalindrome(str){ var i, len = str.length; for(i =0; i isPalindrome('madam') = true > isPalindrome('toyota') = false ```
31
Random - between VAR1 and VAR2
``` function rand5(){ return 1 + Math.random() * 4; } ``` ``` function rand7(){ return 5 + rand5() / 5 * 2; } ```
32
Find the Missing Number in Array of Nums
``` function missingNumber(arr){ var n = arr.length+1, sum = 0, expectedSum = n* (n+1)/2; ``` ``` for(var i = 0, len = arr.length; i < len; i++){ sum += arr[i]; } ``` return expectedSum - sum; } > missingNumber([5, 2, 6, 1, 3]); = 4
33
Is the Sum of the Array and the 2nd Parameter - equal?
``` function sumFinder(arr, sum){ var len = arr.length; ``` ``` for(var i =0; i sumFinder([6,4,3,2,1,7], 9); = true > sumFinder([6,4,3,2,1,7], 2); = false ```
34
Find the largest sum
function topSum(arr){ ``` var biggest = arr[0], second = arr[1], len = arr.length, i = 2; ``` if (len<2) return null; ``` if (biggest biggest){ second = biggest; biggest = arr[i]; } else if (arr[i]>second){ second = arr[i]; } ``` } return biggest + second; }
35
Count all Zeros in the numbers leading up to the given Paramater
``` function countZero(n){ var count = 0; while(n>0){ count += Math.floor(n/10); n = n/10; } return count; } ``` > countZero(2014); = 223