JSFiddle - React, Tailwind, and code Playground

by asdf

JavaScript

// given 2 strings determine if they are anagrams, i.e. you can create second string from characters of first string. For example, 'lock' -> 'clok'
function isAnagram (str1, str2) {
  var strMap = {};
  
  if (str1.length !== str2.length) {
    return false;
  }
  for (var j=0; j<str2.length; j++) {
    if (!strMap[str2[i]]) {
      strMap[str2[j]] = 1;
    } else { 
      strMap[str2[j]] += 1;
    }
  }
  
  for (var i=0; i<str1.length; i++) {
    if (!strMap[str1[i]]) {
      return false;
    }
    strMap[str1[i]] -= 1;
  }
  return true;
} 

console.log(isAnagram('lock', 'clok'));
console.log(isAnagram('lock', 'clock'));
console.log(isAnagram('lock', 'blok'));

// You have two sorted arrays, for example
// var a = [1, 5, 7, 15];
// var b = [-3, 6, 7];
// Merge those two arrays into third one. As a result, merged array should be sorted as well:
// [-3, 1, 5, 6, 7, 7, 15]

function mergeAndSort (arr1, arr2) {
  function sortNumeric (a, b) {
    return a - b;
  }
  // var result = arr1.concat(arr2); 
  // return result.sort(sortNumeric);
  var idx = 0;
  for (var i=0; i<arr2.length; i++) {
  	for (var j=idx, length=arr1.length; j<length; j++) {
    	if (arr2[i] <= arr1[j]) {
      	arr1.splice(j, 0, arr2[i]);
        idx=j;
        break;
      } else if (j === length-1) {
		    arr1.push(arr2[i]); 
      }
    }
  }
  return arr1;
} 
function mergeAndSort2 (arr1, arr2) {
  var i = 0, j=0, result=[];
  while (i<arr1.length && j<arr2.length) {
		if (arr1[i] <= arr2[j]) {
			result.push(arr1[i]);
    	i++;
		} else {
    	result.push(arr2[j]);
      j++
		}
  }
  while (i<arr1.length) {
  	result.push(arr1[i])
    i++;
  }
  while (j<arr2.length) {
  	result.push(arr2[j])
    j++;
  }
  return result;
}
console.log(mergeAndSort2([1, 5, 7, 15], [-3, 6, 7, 18]));

// Is Palindrome?
function isPalindrome (word) {
	for (var i=0, j=word.length-1; i<=Math.floor(word.length/2) && j>=Math.floor(word.length/2); i++, j--) {
    	if (word[i] !== word[j]) {
	      return...