- Notifications
You must be signed in to change notification settings - Fork68
rradfar/javascript-coding-challenges
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.
Note: If the number is a multiple of both 3 and 5, only count it once. Also, if a number is negative, return 0.
constsolution=number=>{// Your solution};console.log(solution(0));// 0console.log(solution(-15));// 0console.log(solution(10));// 23console.log(solution(20));// 78console.log(solution(200));// 9168
Solution
constsolution=number=>{letsum=0;for(leti=3;i<number;i++){if(i%3===0||i%5===0){sum+=i;}}returnsum;};
Create a function that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers.
consteven_or_odd=number=>{// Your solution};console.log(even_or_odd(0));// 'Even'console.log(even_or_odd(2));// 'Even'console.log(even_or_odd(3));// 'Odd'console.log(even_or_odd(-3));// 'Odd'
Solution
consteven_or_odd=number=>{// Let's use a ternary operatorreturnnumber%2===0 ?'Even' :'Odd';};
The clock shows h hours (0 <= h <= 23), m minutes (0 <= m <= 59) and s seconds (0 <= s <= 59) after midnight. Your task is to write a function which returns the time since midnight in milliseconds. There are 1,000 milliseconds in a second.
constpast=(h,m,s)=>{// Your solution};console.log(past(0,0,0));// 0console.log(past(0,1,1));// 61000console.log(past(1,0,0));// 3600000console.log(past(1,0,1));// 3601000console.log(past(1,1,1));// 3661000
Solution
constpast=(h,m,s)=>{return(h*60*60+m*60+s)*1000;};
Write a function that given the input stringname, returns the greeting statementHello, <name> how are you doing today?
constgreet=name=>{//Your solution};console.log(greet('Ryan'));// "Hello, Ryan how are you doing today?"console.log(greet('Sara'));// "Hello, Sara how are you doing today?"
Solution
constgreet=name=>{// Let's use a template literalreturn`Hello,${name} how are you doing today?`;};
The first century spans from the year 1 up to and including the year 100, The second - from the year 101 up to and including the year 200, etc. Given a year, return the century it is in.
constcentury=year=>{// Your solution};console.log(century(1705));// 18console.log(century(1900));// 19console.log(century(1601));// 17console.log(century(2000));// 20console.log(century(89));// 1
Solution
constcentury=year=>{returnMath.ceil(year/100);};
Nathan loves cycling. Because Nathan knows it is important to stay hydrated, he drinks 0.5 litres of water per hour of cycling. Given the time in hours, you need to return the number of litres of water that Nathan will drink, rounded to the smallest value.
constlitres=time=>{// Your solution};console.log(litres(0));// 0console.log(litres(2));// 1console.log(litres(1.4));// 0console.log(litres(12.3));// 6console.log(litres(0.82));// 0console.log(litres(11.8));// 5console.log(litres(1787));// 893
Solution
constlitres=time=>{returnMath.floor(time*0.5);};
Create a function that checks if a numbern is divisible by two numbersx ANDy. All inputs are positive, non-zero digits.
constisDivisible=(n,x,y)=>{// Your solution};console.log(isDivisible(3,3,4));// falseconsole.log(isDivisible(12,3,4));// trueconsole.log(isDivisible(8,3,4));// falseconsole.log(isDivisible(48,3,4));// true
Solution
constisDivisible=(n,x,y)=>{returnn%x===0&&n%y===0;};
Return the number (count) of vowels (a, e, i, o, u) in the given string. The input string will only consist of lower case letters and/or spaces.
constgetCount=str=>{// Your solution};console.log(getCount('my pyx'));// 0console.log(getCount('pear tree'));// 4console.log(getCount('abracadabra'));// 5console.log(getCount('o a kak ushakov lil vo kashu kakao'));// 13
Solution
constgetCount=str=>{letvowelsCount=0;for(letcharofstr){if('aeiou'.includes(char))vowelsCount++;}returnvowelsCount;};// An alternative solution could be to convert the string to an array (using the spread syntax)// and filtering that array by vowelsconstgetCount=str=>{constarr=[...str];returnarr.filter(ele=>['a','e','i','o','u'].includes(ele)).length;};
Trolls are attacking your comment section! A common way to deal with this situation is to remove all of the vowels from the trolls' comments, neutralizing the threat. Your task is to write a function that takes a string and returns a new string with all vowels (a, e, i, o, u) removed.
constdisemvowel=str=>{// Your solution};console.log(disemvowel('This website is for losers LOL!'));// 'Ths wbst s fr lsrs LL!'
Solution
constdisemvowel=str=>{// Let's use regular expressions (regex)returnstr.replace(/[aeiou]/gi,'');};
Given an array of integers, find the one that appears an odd number of times. There will always be only one integer that appears an odd number of times.
constfindOdd=arr=>{// Your solution};console.log(findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]));// 5console.log(findOdd([20,1,1,2,2,3,3,5,5,4,20,4,5]));// 5console.log(findOdd([1,1,2,-2,5,2,4,4,-1,-2,5]));// -1console.log(findOdd([5,4,3,2,1,5,4,3,2,10,10]));// 1console.log(findOdd([1,1,1,1,1,1,10,1,1,1,1]));// 10console.log(findOdd([10]));// 10
Solution
constfindOdd=arr=>{returnarr.reduce((a,b)=>a^b);};
Given a word, your job is to return the middle character(s) of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.
constgetMiddle=str=>{// Your solution};console.log(getMiddle('test'));// 'es'console.log(getMiddle('testing'));// 't'console.log(getMiddle('middle'));// 'dd'console.log(getMiddle('A'));// 'A'
Solution
constgetMiddle=str=>{constlen=str.length;constmid=len/2;// For an odd length, len % 2 equals 1 which is truthyreturnlen%2 ?str[Math.floor(mid)] :str[mid-1]+str[mid];};
You probably know the "like" system from Facebook and other social media. People can "like" posts, photos or other items. We want to create the text that should be displayed next to such an item.
Implement a function that takes an input array, containing the names of people who like an item and returns an output string formatted nicely as shown below.
constlikes=names=>{// Your solution};console.log(likes([]));// 'no one likes this'console.log(likes(['Peter']));// 'Peter likes this'console.log(likes(['Jacob','Alex']));// 'Jacob and Alex like this'console.log(likes(['Max','John','Mark']));// 'Max, John and Mark like this'console.log(likes(['Alex','Jacob','Mark','Max']));// 'Alex, Jacob and 2 others like this'
Solution
constlikes=names=>{constlen=names.length;letoutput;if(len===0){output='no one likes this';}elseif(len===1){output=`${names[0]} likes this`;}elseif(len===2){output=`${names[0]} and${names[1]} like this`;}elseif(len===3){output=`${names[0]},${names[1]} and${names[2]} like this`;}else{output=`${names[0]},${names[1]} and${len-2} others like this`;}returnoutput;};
Write a function that accepts an array of 10 integers (between 0 and 9), and returns a string of those numbers in the form of a phone number.
constcreatePhoneNumber=numbers=>{// Your solution};console.log(createPhoneNumber([1,2,3,4,5,6,7,8,9,0]));// '(123) 456-7890'console.log(createPhoneNumber([1,1,1,1,1,1,1,1,1,1]));// '(111) 111-1111'console.log(createPhoneNumber([1,2,3,4,5,6,7,8,9,0]));// '(123) 456-7890'
Solution
constcreatePhoneNumber=numbers=>{// Using substringsconststr=numbers.join('');return`(${str.substring(0,3)})${str.substring(3,6)}-${str.substring(6)}`;// Alternative solution using RegEx// return numbers.join('').replace(/(\d{3})(\d{3})(\d+)/, '($1) $2-$3');// Alternative solution using reduce()// return numbers.reduce((acc, cur) => acc.replace('x', cur), '(xxx) xxx-xxxx');};
Given an integer, your task is to square every digit of it and concatenate them to produce a new integer.
constsquareDigits=num=>{// Your solution};console.log(squareDigits(2112));// 4114console.log(squareDigits(3212));// 9414console.log(squareDigits(9159));// 8112581
Solution
constsquareDigits=num=>{returnNumber(num.toString().split('').map(ele=>ele*ele).join(''));};
Write a function that given an integer, checks to see if it is a square number. A square number or perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself.
constisSquare=n=>{// Your solution};console.log(isSquare(0));// trueconsole.log(isSquare(4));// trueconsole.log(isSquare(25));// trueconsole.log(isSquare(3));// falseconsole.log(isSquare(93));// falseconsole.log(isSquare(-1));// false
Solution
constisSquare=n=>{returnMath.sqrt(n)%1===0;};
Given a string of space-separated numbers, write a function that returns the highest and lowest numbers. There will always be at least one number in the input string.
consthighAndLow=numbers=>{// Your solution};console.log(highAndLow('1 2 3 4 5'));// '5 1'console.log(highAndLow('1 2 -3 4 5'));// '5 -3'console.log(highAndLow('1 9 3 4 -5'));// '9 -5'console.log(highAndLow('0 -214 542'));// '542 -214'
Solution
consthighAndLow=numbers=>{constarr=numbers.split(' ');return`${Math.max(...arr)}${Math.min(...arr)}`;};
Write a function that takes any non-negative integer as an argument and returns it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.
constdescendingOrder=n=>{// Your solution};console.log(descendingOrder(0));// 0console.log(descendingOrder(1));// 1console.log(descendingOrder(1021));// 2110console.log(descendingOrder(42145));// 54421console.log(descendingOrder(145263));// 654321console.log(descendingOrder(123456789));// 987654321
Solution
constdescendingOrder=n=>{returnparseInt(n.toString().split('').sort((a,b)=>b-a).join(''));};
Given a string which includes only letters, write a function that produces the outputs below.
constaccum=str=>{// Your solution};console.log(accum('abcd'));// 'A-Bb-Ccc-Dddd'console.log(accum('cwAt'));// 'C-Ww-Aaa-Tttt'console.log(accum('RqaEzty'));// 'R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy'
Solution
constaccum=str=>{returnstr.split('').map((ele,index)=>ele.toUpperCase()+ele.toLowerCase().repeat(index)).join('-');};
Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed. Strings passed in will consist of only letters and spaces.
constspinWords=str=>{// Your solution};console.log(spinWords('This is a test'));// 'This is a test'console.log(spinWords('Hey fellow warriors'));// 'Hey wollef sroirraw'console.log(spinWords('This is another test'));// 'This is rehtona test'
Solution
constspinWords=str=>{returnstr.split(' ').map(word=>(word.length<5 ?word :word.split('').reverse().join(''))).join(' ');};
Given a non-empty string of words, return the length of the shortest word(s).
constfindShort=str=>{// Your solution};console.log(findShort('Test where final word shortest see'));// 3console.log(findShort('Lets all go on holiday somewhere very cold'));// 2console.log(findShort('i want to travel the world writing code one day'));// 1
Solution
constfindShort=str=>{returnMath.min(...str.split(' ').map(word=>word.length));};
Write a function that takes an integer as input, and returns the number of bits that are equal to1 in the binary representation of that number. You can guarantee that input is non-negative. For example the binary representation of1234 is10011010010, so the function should return5 in this case.
constcountBits=n=>{// Your solution};console.log(countBits(0));// 0console.log(countBits(4));// 1console.log(countBits(7));// 3console.log(countBits(9));// 2
Solution
constcountBits=n=>{returnn.toString(2).split('0').join('').length;};
Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The input string can contain any character.
constXO=str=>{// Your solution};console.log(XO('xo'));// trueconsole.log(XO('Oo'));// falseconsole.log(XO('xxOo'));// trueconsole.log(XO('xxxm'));// falseconsole.log(XO('ooom'));// falseconsole.log(XO('ty'));// true (when no 'x' and 'o' is present should return true)
Solution
constXO=str=>{constlowerStr=str.toLowerCase();letresult=0;for(constletteroflowerStr){if(letter==='x'){result++;}elseif(letter==='o'){result--;}}return!result;};
Given an array of numbers, write a function that returns the sum of all of the positives ones. If the array is empty, the sum should be0.
constpositiveSum=arr=>{// Your solution};console.log(positiveSum([1,2,3,4,5]));// 15console.log(positiveSum([1,-2,3,4,5]));// 13console.log(positiveSum([-1,2,3,4,-5]));// 9console.log(positiveSum([-1,-2,-3,-4,-5]));// 0console.log(positiveSum([]));// 0
Solution
constpositiveSum=arr=>{returnarr.reduce((acc,cur)=>(cur>0 ?acc+cur :acc),0);};
You are given an array of at least length 3 containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integerN. Write a function that takes the array as an argument and returns this "outlier"N.
constfindOutlier=arr=>{// Your solution};console.log(findOutlier([0,1,2]));// 1console.log(findOutlier([1,2,3]));// 2console.log(findOutlier([1,1,0,1,1]));// 0console.log(findOutlier([0,0,3,0,0]));// 3console.log(findOutlier([160,3,1719,19,13,-21]));// 160console.log(findOutlier([4,0,100,4,11,2602,36]));// 11
Solution
constfindOutlier=arr=>{constevenArray=arr.filter(ele=>ele%2===0);constoddArray=arr.filter(ele=>ele%2!==0);returnevenArray.length===1 ?evenArray[0] :oddArray[0];};
Write a function that subtracts one list from another and returns the result. It should remove all values from arraya, which are present in arrayb.
constarrayDiff=(a,b)=>{// Your solution};console.log(arrayDiff([1,8,2],[]));// [1, 8, 2]console.log(arrayDiff([1,2,3],[1,2]));// [3]console.log(arrayDiff([3,4],[3]));// [4]console.log(arrayDiff([],[4,5]));// []
Solution
constarrayDiff=(a,b)=>{returna.filter(ele=>!b.includes(ele));};
Write a function that capitalizes each word in a given input string.
String.prototype.capitalize=function(){// Your solution};varstr="How can mirrors be real if our eyes aren't real";console.log(str.capitalize());// 'How Can Mirrors Be Real If Our Eyes Aren't Real'
Solution
String.prototype.capitalize=function(){returnthis.split(' ').map(ele=>ele[0].toUpperCase()+ele.slice(1)).join(' ');};
DNA is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms. In DNA strings, symbols "A" and "T" are complements of each other, as are "C" and "G". Given one side of the DNA, write a function that returns the other complementary side. The DNA strand is never empty.
constDNAStrand=dna=>{// Your solution};console.log(DNAStrand('AAAA'));// 'TTTT'console.log(DNAStrand('ATTGC'));// 'TAACG'console.log(DNAStrand('GTAT'));// 'CATA'
Solution
constDNAStrand=dna=>{constdnaMap={A:'T',T:'A',G:'C',C:'G',};return[...dna].map(ele=>dnaMap[ele]).join('');};
An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.
constisIsogram=str=>{// Your solution};console.log(isIsogram('Dermatoglyphics'));// trueconsole.log(isIsogram('isIsogram'));// falseconsole.log(isIsogram('isogram'));// trueconsole.log(isIsogram('moOse'));// falseconsole.log(isIsogram('aba'));// falseconsole.log(isIsogram(''));// true
Solution
constisIsogram=str=>{constlowerStr=str.toLowerCase();// Using Setreturnstr.length===newSet(lowerStr).size;// Alternative solution using every()// return [...lowerStr].every((ele, index) => lowerStr.indexOf(ele) === index);};
Write a program that prints the numbers from 1 to 100. But for multiples of3 prints "Fizz" instead of the number and for the multiples of5 prints"Buzz". For numbers which are multiples of both3 and5 prints "FizzBuzz".
constfizzBuzz=()=>{// Your solution};fizzBuzz();// 1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, ...
Solution
constfizzBuzz=()=>{letoutput;for(letnum=1;num<=100;num++){output='';if(num%3===0)output+='Fizz';if(num%5===0)output+='Buzz';console.log(output||num);}};
Write a function that will return the count of distinct case-insensitive alphanumeric characters that occur more than once in the input string.
constduplicateCount=text=>{// Your solution};console.log(duplicateCount(''));// 0console.log(duplicateCount('abcde'));// 0console.log(duplicateCount('abA11'));// 2console.log(duplicateCount('aabbcde'));// 2console.log(duplicateCount('aabBcde'));// 2console.log(duplicateCount('Indivisibility'));// 1console.log(duplicateCount('Indivisibilities'));// 2
Solution
constduplicateCount=text=>{constlowercaseText=text.toLowerCase();letfrequency={};letcount=0;for(constletteroflowercaseText){frequency[letter]=(frequency[letter]||0)+1;if(frequency[letter]===2)count++;}returncount;};
Write a function that converts a string to a new string where each character in the new string is( if that character appears only once in the original string, or) if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.
constduplicateEncode=word=>{// Your solution};console.log(duplicateEncode('din'));// '((('console.log(duplicateEncode('(( @'));// '))(('console.log(duplicateEncode('recede'));// '()()()'console.log(duplicateEncode('Success'));// ')())())'
Solution
constduplicateEncode=word=>{constlowerWord=word.toLowerCase();letresult='';for(constcharoflowerWord){lowerWord.indexOf(char)!==lowerWord.lastIndexOf(char) ?(result+=')') :(result+='(');}returnresult;};
Write a function that reverses the string that is passed to it. For this challenge, you mayNOT use the JavaScript built-inreverse() method.
constreverseString=str=>{// Your solution};console.log(reverseString('hello'));// 'olleh'console.log(reverseString('world'));// 'dlrow'console.log(reverseString(''));// ''console.log(reverseString('h'));// 'h'
Solution
constreverseString=str=>{letresult='';for(letcharofstr){result=char+result;}returnresult;};
Write a function that takes a positive numbernum and returns its multiplicative persistence, which is the number of steps it takes to multiply all the digits ofnum by each other, and repeating with the product until a single digit is obtained.
constpersistence=num=>{// Your solution};console.log(persistence(999));// 4// because 9*9*9=729, 7*2*9=126, 1*2*6=12, and finally 1*2=2console.log(persistence(93));// 3// because 9*3=27, 2*7=14, 1*4=4 and 4 has only one digitconsole.log(persistence(5));// 0// because 5 is already a single-digit number
Solution
constpersistence=num=>{if(num<10)return0;letproduct=1;while(num>=10){product*=num%10;num=Math.floor(num/10);}// Using recursionreturn1+persistence(product*num);};
Fibonacci number (Fibonacci sequence), named after mathematician Fibonacci, is a sequence of numbers that looks like this:0, 1, 1, 2, 3, 5, 8, 13,.... You get first two starting numbers, 0 and 1, and the next number in the sequence is always the sum of the previous two numbers.
Write a functionfib() that takes one parametersteps, and returns a number from the Fibonacci sequence, based on the parameter steps, which determines the position in Fibonacci number. For examplefib(0) returns0,fib(4) returns3, andfib(15) returns610.
constfib=steps=>{// Your solution};console.log(fib(0));// 0console.log(fib(4));// 3console.log(fib(17));// 1597console.log(fib(20));// 6765
Solution
// Recursive solutionconstfib=steps=>{if(steps<2)returnsteps;returnfib(steps-2)+fib(steps-1);};
Given a string, write a function that replaces every letter with its position in the alphabet:'a' = 1, 'b' = 2, .... If anything in the input isn't a letter, ignore it and don't return it.
constalphabetPosition=text=>{// Your solution};console.log(alphabetPosition('The narwhal bacons at midnight.'));// '20 8 5 14 1 18 23 8 1 12 2 1 3 15 14 19 1 20 13 9 4 14 9 7 8 20'console.log(alphabetPosition("The sunset sets at twelve o' clock."));// '20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11'
Solution
constalphabetPosition=text=>{conststartingIndex='a'.charCodeAt()-1;returntext.toLowerCase().match(/[a-z]/g).map(letter=>letter.charCodeAt()-startingIndex).join(' ');};
Given an array of integers nums and an integer target, return indices of the two numbers in the array such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice.
consttwoSum=(nums,target)=>{// Your solution};console.log(twoSum([2,7,11,15],9));// [0, 1]console.log(twoSum([3,2,4],6));// [1, 2]
Solution
consttwoSum=(nums,target)=>{constlen=nums.length;for(leti=0;i<len;i++){constj=nums.lastIndexOf(target-nums[i]);if(j>i){return[i,j];}}// Alternative solution using Map// const map = new Map();// for (let i = 0; i < nums.length; i++) {// const otherIndex = map.get(target - nums[i]);// if (typeof otherIndex !== 'undefined') {// return [otherIndex, i];// }// map.set(nums[i], i);// }};
Implement a function that takes an iterable argument (a string or an array) as input and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.
constuniqueInOrder=iterable=>{// Your solution};console.log(uniqueInOrder([1,2,2,3,3]));// [1, 2, 3]console.log(uniqueInOrder('ABBCcAD'));// ['A', 'B', 'C', 'c', 'A', 'D']console.log(uniqueInOrder('AAAABBBCCDAABBB'));// ['A', 'B', 'C', 'D', 'A', 'B']
Solution
constuniqueInOrder=iterable=>{constarr=[...iterable];returnarr.filter((ele,index)=>ele!==arr[index-1]);};
You are given an arrayprices whereprices[i] is the price of a given stock on theith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return0.
Example 1:
Input: prices = [7,1,5,3,6,4]Output: 5Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1]Output: 0Explanation: In this case, no transactions aredone and the max profit = 0.constmaxProfit=prices=>{// Your solution};console.log(maxProfit([7,1,5,3,6,4]));// 5console.log(maxProfit([7,6,4,3,1]));// 0
Solution
constmaxProfit=prices=>{letmin=Number.MAX_SAFE_INTEGER;letprofit=0;for(leti=0;i<prices.length;i++){min=Math.min(prices[i],min);if(prices[i]-min>profit){profit=prices[i]-min;}}returnprofit;};
Mike works as a DJ in the best London nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words (that don't containWUB). To make the dubstep remix of this song, Mike inserts a certain number of wordsWUB before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighboring words), and then the boy glues together all the words, includingWUB, in one string and plays the song at the club.
For example, a song with words "I AM X" can transform into a dubstep remix asWUBWUBIWUBAMWUBWUBX and cannot transform intoWUBWUBIAMWUBX.
Recently, Johnny has heard Mike's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Mike remixed. Help Johnny restore the original song.
Input: The input consists of a single non-empty string, consisting only of uppercase English letters, the string's length doesn't exceed 200 characters
Output: Return the words of the initial song that Mike used to make a dubsteb remix. Separate the words with a space.
constsongDecoder=song=>{// Your solution};console.log(songDecoder('AWUBBWUBC'));// 'A B C' (WUB should be replaced by 1 space)console.log(songDecoder('AWUBWUBWUBBWUBWUBWUBC'));// 'A B C' (Multiples WUBs should be replaced by only 1 space)console.log(songDecoder('WUBAWUBBWUBCWUB'));// 'A B C' (Any starting or trailing WUBs should be removed)console.log(songDecoder('WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB'));// 'WE ARE THE CHAMPIONS MY FRIEND'
Solution
constsongDecoder=song=>{returnsong.replace(/(WUB)+/g,' ').trim();// Alternative solution// return song.split('WUB').filter(Boolean).join(' ');};
Given a non-empty strings containing just the characters(,),{,},[,], determine if the input string is valid. An input string is valid if open brackets are closed by the same type of brackets, and open brackets are closed in the correct order.
constisValid=s=>{// Your solution};console.log(isValid('['));//falseconsole.log(isValid('()'));//trueconsole.log(isValid('(]'));//falseconsole.log(isValid('{[]}'));//trueconsole.log(isValid('([)]'));//falseconsole.log(isValid('()[]{}'));//true
Solution
constisValid=s=>{conststack=[];constpairs={'(':')','[':']','{':'}',};for(constcharofs){if(pairs[char]){stack.push(char);}elseif(pairs[stack.pop()]!==char){returnfalse;}}return!stack.length;};
Given a signed 32-bit integerx, returnx with its digits reversed. If reversingx causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
constreverse=x=>{// Your solution};console.log(reverse(0));// 0console.log(reverse(120));// 21console.log(reverse(123));// 321console.log(reverse(-123));// -321console.log(reverse(1534236469));// 0
Solution
constreverse=x=>{constMAX=Math.pow(2,31)-1;constMIN=-1*Math.pow(2,31);constarr=Math.abs(x).toString().split('');constreversed=Math.sign(x)*Number(arr.reverse().join(''));returnreversed<MIN||reversed>MAX ?0 :reversed;};
Given a sorted arraynums, write a function that removes the duplicates in-place such that each element appears only once and returns the new length. Donot allocate extra space for another array, you must do this by modifying the input array in-place withO(1) extra memory.
constremoveDuplicates=nums=>{// Your solution};console.log(removeDuplicates([1,1,2]));// 2 (because [1, 2] has length 2)console.log(removeDuplicates([0,1,1,1,2,2,3,3,4]));// 5console.log(removeDuplicates([]));// 0
Solution
constremoveDuplicates=nums=>{if(nums.length<=1)returnnums.length;letcurrentIndex=0;for(leti=1;i<nums.length;i++){if(nums[currentIndex]!==nums[i]){currentIndex++;nums[currentIndex]=nums[i];}}nums.length=currentIndex+1;returnnums.length;};
Given an arraycandies wherecandies[i] represents the number of candies that theith kid has, and an integerextraCandies, write a function that for each kid checks if he/she would have the greatest number of candies in the group if they were givenextraCandies. Note that multiple kids can have the greatest number of candies.For example,
Input: candies = [2,3,5,1,3], extraCandies = 3Output: [true,true,true,false,true]Explanation:- Kid 1 has 2 candies andif he or she receives all extra candies (3) will have 5 candies --- the greatest number of candies among the kids.- Kid 2 has 3 candies andif he or she receives at least 2 extra candies will have the greatest number of candies among the kids.- Kid 3 has 5 candies and this is already the greatest number of candies among the kids.- Kid 4 has 1 candy and evenif he or she receives all extra candies will only have 4 candies.- Kid 5 has 3 candies andif he or she receives at least 2 extra candies will have the greatest number of candies among the kids.
constkidsWithCandies=(candies,extraCandies)=>{// Your solution};console.log(kidsWithCandies([12,1,12],10));// [true, false, true]console.log(kidsWithCandies([4,2,1,1,2],1));// [true, false, false, false, false]
Solution
constkidsWithCandies=(candies,extraCandies)=>{constMAX=Math.max(...candies);returncandies.map(candy=>candy+extraCandies>=MAX);};
ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar cipher. Create a function that takes a string and returns the string ciphered with Rot13. If there are numbers or special characters included in the string, they should be returned as they are. Only letters from the latin/english alphabet should be shifted.
constrot13=str=>{// Your solution};console.log(rot13('az AZ'));// nm NMconsole.log(rot13('10+2 is twelve.'));// 10+2 vf gjryir.console.log(rot13('abcdefghijklmnopqrstuvwxyz'));// nopqrstuvwxyzabcdefghijklm
Solution
constrot13=str=>{returnstr.replace(/[a-z]/gi,letter=>String.fromCharCode(letter.charCodeAt()+(letter.toLowerCase()<='m' ?13 :-13)));};
You are given anm x n integer gridaccounts, whereaccounts[i][j] is the amount of money theith customer has in thejth bank. Return the wealth that the richest customer has. A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth. For example:
Input: accounts = [[1,5],[7,3],[3,5]]Output: 10Explanation:1st customer has wealth = 1 + 5 = 62nd customer has wealth = 7 + 3 = 103rd customer has wealth = 3 + 5 = 8The 2nd customer is the richest with a wealth of 10.
constmaximumWealth=accounts=>{// Your solution};console.log(maximumWealth([[2,8,7],[7,1,3],[1,9,5],]));// 17console.log(maximumWealth([[1,5],[7,3],[3,5],]));// 10console.log(maximumWealth([[1,2,3],[3,2,1],]));// 6
Solution
constmaximumWealth=accounts=>{returnMath.max( ...accounts.map(customer=>customer.reduce((a,b)=>a+b)));};
The marketing team is spending way too much time typing in hashtags. Let's help them with our own Hashtag Generator! Here's the deal:
- It must start with a hashtag
#. - Ignore spaces in the input.
- All words must have their first letter capitalized.
- If the final result is longer than 140 chars it must return
false. - If the input or the result is an empty string it must return
false.
constgenerateHashtag=str=>{// Your solution};console.log(generateHashtag('JavaScript'));// #JavaScriptconsole.log(generateHashtag('Do we have a Hashtag'));// #DoWeHaveAHashtagconsole.log(generateHashtag(' Hello World '));// #HelloWorldconsole.log(generateHashtag('coding'+' '.repeat(140)+'for life'));// #CodingForLifeconsole.log(generateHashtag(''));// falseconsole.log(generateHashtag(' '));// falseconsole.log(generateHashtag('a'.repeat(140)));// falseconsole.log(generateHashtag(' '.repeat(200)));// false
Solution
constgenerateHashtag=str=>{consthashtag=str.split(' ').reduce((tag,word)=>tag+word.charAt(0).toUpperCase()+word.slice(1),'#');// Alternative solution// const hashtag =// '#' +// str// .split(' ')// .map(ele => ele.charAt(0).toUpperCase() + ele.substring(1))// .join('');returnhashtag.length===1||hashtag.length>140 ?false :hashtag;};
Pete likes to bake some cakes. He has some recipes and ingredients. Unfortunately he is not good in maths. Can you help him to find out, how many cakes he could bake considering his recipes?
Write a functioncakes(), which takes therecipe object and theavailable ingredients object and returns the maximum number of cakes Pete can bake. Ingredients that are not present in the objects, can be considered as0.
constcakes=(recipe,available)=>{// Your solution};letrecipe={flour:500,sugar:200,eggs:1};letavailable={flour:1200,sugar:1200,eggs:5,milk:200};console.log(cakes(recipe,available));// 2recipe={apples:3,flour:300,sugar:150,milk:100,oil:100};available={sugar:500,flour:2000,milk:2000};console.log(cakes(recipe,available));// 0
Solution
constcakes=(recipe,available)=>{letnum_cakes=Infinity;for(letingredientinrecipe){if(!available[ingredient]||recipe[ingredient]>available[ingredient])return0;num_cakes=Math.min(num_cakes,Math.floor(available[ingredient]/recipe[ingredient]));}returnnum_cakes;};
Write a function that counts the frequency of all the characters in a given string.
constcount=string=>{// Your solution};console.log(count(''));// {}console.log(count('aba'));// { a: 2, b: 1 }
Solution
constcount=string=>{constfrequency={};for(constcharofstring){frequency[char]=(frequency[char]||0)+1;}returnfrequency;};
Complete the solution so that the function will break up camel casing, using a space between words.
constsolution=str=>{// Your solution};console.log(solution('camelCasingHere'));// camel Casing Hereconsole.log(solution('No Camels here'));// No Camels hereconsole.log(solution('ABC'));// ABCconsole.log(solution(''));// ''
Solution
constsolution=str=>{returnstr.replace(/([a-z])([A-Z])/g,'$1 $2');};
Let's assume that the numeric value of a letter is its position in the alphabet starting from0 (i.e.a -> 0, b -> 1, c -> 2, etc.). Similarly, the numerical value of a stringstr consisting of some lowercase English letters is the concatenation (not sum!) of the numeric values of each letter instr, which is then converted into an integer. For example, ifstr = 'acb', we concatenate each letter's numeric value, resulting in021 which is then converted to integer21.
You are given three stringsfirstWord,secondWord, andtargetWord, each consisting of lowercase English lettersa throughj inclusive. Write a function that returns true if the sum of the numerical values offirstWord andsecondWord equals the numerical value oftargetWord.
constisSumEqual=(firstWord,secondWord,targetWord)=>{// Your solution};console.log(isSumEqual('acb','cba','cdb'));// true// The numerical value of firstWord 'acb' is '021' -> 21// The numerical value of secondWord 'cba' is '210' -> 210// The numerical value of targetWord 'cdb' is '231' -> 231// So we return true because 21 + 210 == 231console.log(isSumEqual('aaa','a','aab'));// false// The numerical value of firstWord 'aaa' is '000' -> 0// The numerical value of secondWord 'a' is '0' -> 0// The numerical value of targetWord 'aab' is '001' -> 1// So we return false because 0 + 0 != 1console.log(isSumEqual('aaa','a','aaaa'));// true// The numerical value of firstWord 'aaa' is '000' -> 0// The numerical value of secondWord 'a' is '0' -> 0// The numerical value of targetWord 'aaaa' is '0000' -> 0// So we return true because 0 + 0 == 0
Solution
constgetNumericValue=str=>{constoffset='a'.charCodeAt();constarr=[];for(constcharofstr){arr.push(char.charCodeAt()-offset);}returnparseInt(arr.join(''));};constisSumEqual=(firstWord,secondWord,targetWord)=>{return(getNumericValue(firstWord)+getNumericValue(secondWord)===getNumericValue(targetWord));};
Write a function that given an input URL, returns its domain name.
constdomainName=url=>{// Your solution};console.log(domainName('www.google.ca'));// googleconsole.log(domainName('http://google.com'));// googleconsole.log(domainName('https://google.com'));// googleconsole.log(domainName('http://google.co.jp'));// googleconsole.log(domainName('https://www.google.com'));// google
Solution
constdomainName=url=>{returnurl.replace(/(www\.|.*\/\/|\..+)/g,'');};// Alternative solution with no regex// const domainName = url => url.replace('http://', '').replace('https://', '').replace('www.', '').split('.')[0];
Write a function that takes an input string and returns the first character that is not repeated anywhere in the string. Upper- and lowercase letters are considered the same character, but the function should return the correct case for the initial letter.
constfirstNonRepeatingLetter=str=>{// Your solution};console.log(firstNonRepeatingLetter('a'));// 'a'console.log(firstNonRepeatingLetter('stress'));// 't'console.log(firstNonRepeatingLetter('sTreSS'));// 'T'console.log(firstNonRepeatingLetter('abba'));// ''console.log(firstNonRepeatingLetter("Go hang a salami, I'm a lasagna hog!"));// ','
Solution
constfirstNonRepeatingLetter=str=>{conststrToLower=str.toLowerCase();for(letcharofstr){if(strToLower.indexOf(char.toLowerCase())===strToLower.lastIndexOf(char.toLowerCase())){returnchar;}}return'';};
Create a function that takes a positive integer less than4,000 as its input and returns a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately starting with the leftmost digit and skipping any digit with a value of zero. There can't be more than 3 identical symbols in a row. More about Roman numerals:http://en.wikipedia.org/wiki/Roman_numerals
Table of individual decimal places for your reference:
| Thousands | Hundreds | Tens | Units | |
|---|---|---|---|---|
| 1 | M | C | X | I |
| 2 | MM | CC | XX | II |
| 3 | MMM | CCC | XXX | III |
| 4 | CD | XL | IV | |
| 5 | D | L | V | |
| 6 | DC | LX | VI | |
| 7 | DCC | LXX | VII | |
| 8 | DCCC | LXXX | VIII | |
| 9 | CM | XC | IX |
constconvertToRoman=number=>{// Your solution};console.log(convertToRoman(4));// IVconsole.log(convertToRoman(9));// IXconsole.log(convertToRoman(11));// XIconsole.log(convertToRoman(19));// XIXconsole.log(convertToRoman(22));// XXIIconsole.log(convertToRoman(15));// XVconsole.log(convertToRoman(39));// XXX + IX = XXXIXconsole.log(convertToRoman(160));// C + LX = CLXconsole.log(convertToRoman(207));// CC + VII = CCVIIconsole.log(convertToRoman(246));// CC + XL + VI = CCXLVIconsole.log(convertToRoman(789));// DCC + LXXX + IX = DCCLXXXIXconsole.log(convertToRoman(1009));// M + IX = MIXconsole.log(convertToRoman(1066));// M + LX + VI = MLXVIconsole.log(convertToRoman(1776));// M + DCC + LXX + VI = MDCCLXXVIconsole.log(convertToRoman(1918));// M + CM + X + VIII = MCMXVIIIconsole.log(convertToRoman(1954));// M + CM + L + IV = MCMLIVconsole.log(convertToRoman(2014));// MM + X + IV = MMXIVconsole.log(convertToRoman(2421));// MM + CD + XX + I = MMCDXXIconsole.log(convertToRoman(3999));// MMM + CM + XC + IX = MMMCMXCIX
Solution
constconvertToRoman=number=>{constdecimals=[1000,900,500,400,100,90,50,40,10,9,5,4,1];// prettier-ignoreconstromans=['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I'];letresult='';decimals.map((value,index)=>{while(number>=value){result+=romans[index];number-=value;}});returnresult;};
Write a function that accepts two strings and returnstrue if some or all of the characters in the first string can be rearranged to match the second string.
constscramble=(str1,str2)=>{// Your solution};console.log(scramble('scriptjava','javascript'));// trueconsole.log(scramble('scriptingjava','javascript'));// trueconsole.log(scramble('scriptsjava','javascripts'));// trueconsole.log(scramble('jscripts','javascript'));// falseconsole.log(scramble('javscripts','javascript'));// false
Solution
constscramble=(str1,str2)=>{return[...str2].every(letter=>str2.split(letter).length<=str1.split(letter).length);// Alternative solution// const freq = {};// for (const letter of str1) {// freq[letter] = (freq[letter] ?? 0) + 1;// }// for (const letter of str2) {// if (!freq[letter] || freq[letter] < 0) return false;// freq[letter]--;// }// return true;};
Write a function that turns a given string into a wave! You will be passed a string and you must return that string in an array where each letter takes turns to become uppercase. The input string will always be lowercase but may be empty. If you encounter a whitespace then pass over it.
constwave=str=>{// Your solution};console.log(wave('hello'));// ['Hello', 'hEllo', 'heLlo', 'helLo', 'hellO'];console.log(wave(' gap '));// [' Gap ', ' gAp ', ' gaP '];console.log(wave('Two words'));// ['Two words', 'tWo words', 'twO words', 'two Words', 'two wOrds', 'two woRds', 'two worDs', 'two wordS'];
Solution
constwave=str=>{constresult=[];constlen=str.length;for(leti=0;i<len;i++){if(str[i]!==' '){constword=str.substring(0,i).toLowerCase()+str[i].toUpperCase()+str.substring(i+1).toLowerCase();result.push(word);}}returnresult;};
Write a function that given an integer arraynums of lengthn, returns an array of length2n wherenums is concatenated to itself.
constgetConcatenation=nums=>{// Your solution};console.log(getConcatenation([1,2,3]));// [1, 2, 3, 1, 2, 3]console.log(getConcatenation([4,3,2,1]));// [4, 3, 2, 1, 4, 3, 2, 1]
Solution
constgetConcatenation=nums=>{return[...nums, ...nums];};
Write a function that given an array of users, returns an array of their names. Can you achieve this in one line of code?
constgetNames=users=>{// Your solution};constusers=[{id:001,name:'Alice',startDate:'2021-01-03',},{id:002,name:'Bob',startDate:'2020-02-01',},{id:003,name:'Claire',startDate:'2019-03-01',},];console.log(getNames(users));// ['Alice', 'Bob', 'Claire']
Solution
constgetNames=users=>users.map(user=>user.name);
Write a function that converts all the keys in an object from snake case to camel case.
consttoCamel=obj=>{// Your solution};console.log(toCamel({first_name:'John',last_name:'Rambo',favorite_movie:'First Blood',}));// {'firstName': 'John', 'lastName': 'Rambo', 'favoriteMovie': 'First Blood'}
Solution
consttoCamel=obj=>{constresult={};for(const[key,value]ofObject.entries(obj)){// Let's use regex capture groupsconstcamelKey=key.replace(/(_[a-z])/gi,$1=>$1.replace('_','').toUpperCase());result[camelKey]=value;}returnresult;};
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a strings, returntrue if it is a palindrome, orfalse otherwise.
constisPalindrome=s=>{// Your solution};console.log(isPalindrome('A man, a plan, a canal: Panama'));// true// Explanation: "amanaplanacanalpanama" is a palindrome.console.log(isPalindrome('race a car'));// false// Explanation: "raceacar" is not a palindrome.console.log(isPalindrome('ab_a'));// true// Explanation: "aba" is a palindrome.console.log(isPalindrome(' '));// true// Explanation: `s` is an empty string "" after removing non-alphanumeric characters.// Since an empty string reads the same forward and backward, it is a palindrome.
Solution
constisPalindrome=s=>{conststr=s.toLowerCase().replace(/[^a-z0-9]/g,'');letstart=0;letend=str.length-1;while(start<end){if(str[start]!==str[end])returnfalse;start++;end--;}returntrue;// Alternative solution using built-in reverse() method// const str = s.toLowerCase().replace(/[^a-z0-9]/g, '');// return str === [...str].reverse().join('');};
Given an integer arraynums, move all0's in the array to the end of it while maintaining the relative order of the non-zero elements. Achieve this without copying the array or creating a new array.
constmoveZeroes=nums=>{// Your solution};console.log(moveZeroes([0,1,0,3,12]));// [1, 3, 12, 0, 0]console.log(moveZeroes([0,0,1]));// [1, 0, 0]console.log(moveZeroes([0]));// [0]
Solution
constmoveZeroes=nums=>{constlength=nums.length;letindex=0;for(leti=0;i<length;i++){if(nums[i]!==0){nums[index]=nums[i];if(index!==i){nums[i]=0;}index++;}}returnnums;};
About
JavaScript Coding Challenges for Beginners
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.
