function isAnagram(str1, str2) {
return (
str1
.split("")
.sort()
.join("") ===
str2
.split("")
.sort()
.join("")
);
}
Flatten an array: Write a function that takes an array of arrays and returns a single, flattened array.
function flattenArray(arr) {
return arr.reduce((acc, val) => acc.concat(val), []);
}
Longest common prefix: Write a function that takes an array of strings and returns the longest common prefix.
function longestCommonPrefix(strs) {
if (strs.length === 0) return "";
if (strs.length === 1) return strs[0];
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) !== 0) {
prefix = prefix.substring(0, prefix.length - 1);
if (!prefix) return "";
}
}
return prefix;
}
Two Sum: Given an array of integers, find two numbers such that they add up to a specific target number.
function twoSum(nums, target) {
let map = new Map();
for (let i = 0; i < nums.length; i++) {
let complement = target - nums[i];
if (map.has(complement)) {
return [map.get(complement), i];
}
map.set(nums[i], i);
}
return [];
}
Median of two sorted arrays: Given two sorted arrays, find the median element.
const median = (a1, a2) => {
let x = a1.concat(a2);
x.sort(function (a, b) {
return a - b;
});
let len = x.length;
return len % 2 === 0 ? (x[Math.floor(len / 2) - 1] + x[Math.ceil(len / 2)]) / 2 : x[Math.floor(len / 2)];
}
let a = [0, 2, 3, 5, 9];
let b = [1, 4];
console.log(median(a, b));
Reverse Integer: Write a function that takes an integer and returns its reverse.
function reverseInteger(n) {
let r = n.toString().split('').reverse().join('');
return Math.sign(n) * parseInt(r);
}
// Call
reverseInteger(-267);
reverseInteger(31522);
const arr1 = [3, 5, 6, 10, 11, 20];
const arr2 = [1, 2, 7, 8, 15, 19];
mergeTwo(arr1, arr2); // [1, 2, 3, 5, 6, 7, 8, 10, 11, 15, 19, 20]
function mergeSortedArray(arr1,arr2){
var tempArray = [];
while(arr1.length || arr2.length) {
if(typeof arr1[0] === 'undefined') {
tempArray.push(arr2[0]);
arr2.splice(0,1);
} else if(arr1[0] > arr2[0]){
tempArray.push(arr2[0]);
arr2.splice(0,1);
} else {
tempArray.push(arr1[0]);
arr1.splice(0,1);
}
}
return tempArray;
}
FizzBuzz Tree: Write a function that takes a binary tree as input and returns an array with the values of each node, but for multiples of 3 replace the value with "Fizz", for multiples of 5 replace with "Buzz", and for multiples of both 3 and 5 replace with "FizzBuzz".
function fizzBuzz(n) {
for (let i = 1; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
}
}
function isPalindrome(str) {
return str === str.split("").reverse().join("");
}
function sumArray(arr) {
return arr.reduce((a, b) => a + b, 0);
}