Algorithm and Data Structures

With the boom in the software and seeing new languages and frameworks on recent bases companies and individuals are realizing the importance of the core basis and now everyone is racing to brush up their

With the boom in the software and seeing new languages and frameworks on recent bases companies and individuals are realizing the importance of the core basis and now everyone is racing to brush up their skills.

This is a series of articles which are my take on Algorithm.

String Reverse

let’s say we have the word “Hello” and we would want to reverse it to “olleH”. this can be done in multiple ways but I prefer the below 2 ways.

function reverse(str) {
var s ="";
for(let item of str) {
s = item + s;
}
return s;
}

console.log(reverse('Hello'));

Using inbuilt functions: first split the string into an array and then use a reverse function on it and then join it back

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

console.log(reverse('Hello'));

Reverse all the words in a sentence so if the user inputs “Hello How are you” then the output should be “olleH woH era uoy”.

function reverse(str){
let words= str.split(' ');
let reversed='';

for(let items of words)
{
	reversed += items.split('').reverse().join('') +' ';
}

return reversed;
}

console.log(reverse('Hello How are you'));

Palindrome

given a string return true if its a palindrome else return false. The word “racecar” is a palindrome while “Hello” isnt.

2 ways of performing the validation:

way 1: using inbuild functions

function palindrome(str) {
	
	return str === str.split('').reverse().join('');
}

console.log(palindrome("abba"));

way2: using for loops (inefficient way)

function palindrome(str) {
	
  var reverse ='';
  
	for(char of str)
	{
		reverse = char + reverse;
	}
  
return str === reverse;
}

console.log(palindrome("abba"));

Way 2: using for loops (efficient way)

function palindrome(str) {
	
  
	for(i=0; i<str.length/2; i++)
	{
		if(str[i] !== str[str.length -1-i])
    return false;
	}
  
		return true;
}

console.log(palindrome("abcba"));

Palindrome with case sensitivity if the user provides words like “RaceCar” this would need to be converted to lower case and then needs to be checked.

function palindrome(str) {

str = str.toLowerCase();
	
  var reverse ='';
  
	for(char of str)
	{
			reverse = char + reverse;
	}
  
  return str === reverse;

}

console.log(palindrome("Abba"));
function palindrome(str) {

	return str.toLowerCase() === str.toLowerCase().split('').reverse().join('');
}

console.log(palindrome("Abba"));

Integer reversal

Given a integer like 15 and you need to return 51 for it.

Way 1: assuming that we dont get decimals and also considering sign:

function reverseInt(n) {

var temp, sum=0;
var sign=Math.sign(n);

if(sign<0)
{
	n = n*sign;
}

while(n>0)
{
	temp = n % 10;
  sum = sum*10 + temp;
  n = n/10|0
}
return sum*sign;

}

way 2: using inbuilt functions by converting to string. this will handle the below cases.
1. negative numbers will remain negative -15 will be converted to -51.
2. the function can handle ints and floats 123.456 will be converted to 654.321
3. It will return integer if the input is an integer 123 will return 123 and not 123.00
4. It will also removing leading zeros 123.1200 will be returned as 12.321

function reverseInt(n) {

return  parseFloat(n.toString().split('').reverse().join('')) * Math.sign(n);

}
console.log(reverseInt(-123.456));

Find Max Char

given a string, return the character that is most commonly used in the string. maxChar(“abcccccccd”) === “c”

Way 1: manual design

function maxChar(str) {
let count =0;
let currentchar='';
let maxchar=0;

for (let char of str)
{
		for (let innerchar of str)
    {
    			if(char === innerchar)
          {
          	count++;
          }
    }

    if(count>maxchar)
    {
    		  currentchar = char;
    			maxchar = count;
    }
}


return currentchar;
}

console.log(maxChar("Hellow Thereaaaaaaaa"));

Way2: leveraging Javascript features objects

function maxChar(str) {
let charMap ={};
let maxchar= '';
let max = 0;

for (let char of str)
{
	if(charMap[char])
  {
  		charMap[char]++;
  }
  else
  {
  	charMap[char]=1;
  }
//charMap[char]=charMap[char]+1||1; above if can be condensed like this as well
}

for(let char in charMap)
{
		if(charMap[char] > max)
    {
    		max = charMap[char];
    		maxchar = char;
    }
}

return maxchar;
}

console.log(maxChar("Hellow There"));

way3: leveraging object methods

function maxChar(str) {
let charMap ={};
let charArray=[];
let valueArray
let max=0;

for (let char of str)
{
	charMap[char]=charMap[char]+1||1;
}

charArray = Object.keys(charMap);
valueArray = Object.values(charMap);
max = Math.max(...valueArray);
return charArray[valueArray.indexOf(max)];


}

console.log(maxChar("Hellow Thereaaa"));

FizzBuzz

write a program that console logs the number from 1 to n. but for multiples of 3 log fizz, for multiples of 5 log buzz and for multiple of 3 and 5 log fizzbuzz.

Way 1:

function fizzBuzz(n) {
	let count =0;
	let x = 0;
	let y = 0;
	while(n!==count)
	{
		count++;
		x = count%3;
		y = count%5;
		if(x === 0 && y ===0)
		{
			console.log("fizzbuzz");
		}
		else if(x === 0)
		{
			console.log("fizz");
		}
		else if(y === 0)
		{
			console.log("buzz");
		}
		else
		{
			console.log(count);
		}
	}
}

fizzBuzz(15);

way 2:

function fizzBuzz(n) {
	let x = 0;
	let y = 0;
    for (var i = 1; i <= n; i++) {
        var result = "";
		x = i%3;
		y = i%5;
        if (x === 0 && y === 0) result += "fizzbuzz";  
        else if (x === 0) result += "fizz";        
        else if (y === 0) result += "buzz";

        console.log(result || i);
    }
}

fizzBuzz(15);

Array Chunking

Given an array and chunk size, divide the array into many subarrays whre each subsrray is of length size.

Way 1: very basic solution

function chunk(array, size) {

	let rotate = (array.length%size===0)? array.length/size: (array.length+1)/size;
	
	let arr= [];
	
	for(let i =0; i<rotate; i++)
	{
		arr[i] = [];
		for(let j=0; j<size; j++)
		{
			let value = array.shift();
			if(value)
			{
				arr[i].push(value);
			}
		}
	}
	
	return arr;

}

way 2: basic reduced number of lines

function chunk(array, size) {

let arr= [];

for(let element of array)
{
		let temparray = arr[arr.length-1];
    console.log(temparray);
    
    if(!temparray || temparray.length === size)
    {
    		arr.push([element]);
    }
   	else
    {
    		temparray.push(element);
    }
}

console.log(arr);

}

console.log(chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11],2))

way 3: uisng array methods

function chunk(array, size) {

let arr= [];

let index =0;
while(index<array.length)
{
	arr.push(array.slice(index,index + size));
    index += size;
}

console.log(arr);

}

console.log(chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11],2))

way 4: using splice

function chunk(array, size) {
    let result = []
    let arrayCopy = [...array]
    while (arrayCopy.length > 0) {
        result.push(arrayCopy.splice(0, size))
    }
    return result
}


console.log(chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11],2))

Leave a Reply

Your email address will not be published. Required fields are marked *