Data Structure and Algorithm Common Interview Questions (Part 2)

FizzBuzz, Array Chunk and Anagrams

Please check part 1 of this blog for more exercise.

fizzBuzz(5) output: 1,   2,   fizz,   4,   buzz

Solution

  1. Create a for loop that goes from 0 to the N number
  2. Use an if, else statement to check each number if they are multiple of the current number.
  3. If the number is multiple of the 3 print “fizz” if multiple of 5 “Buzz” and “FizzBuzz” if multiple of both.
if(i % 3 === 0 && i % 5===0)

Array Chunk

The problem:

chunk([1, 2, 3, 4], 2) --> [[ 1, 2], [3, 4]]chunk([1, 2, 3, 4, 5], 2) --> [[ 1, 2], [3, 4], [5]]chunk([1, 2, 3, 4, 5, 6, 7, 8], 3) --> [[ 1, 2, 3], [4, 5, 6], [7, 8]]chunk([1, 2, 3, 4, 5], 4) --> [[ 1, 2, 3, 4], [5]]chunk([1, 2, 3, 4, 5], 10) --> [[ 1, 2, 3, 4, 5]]
  1. The number given is bigger than the number of elements inside the array.

Solution

  1. Create an empty array which represents the chunked array
  2. loop inside each element of the array we are getting as an argument
  3. Grap the last element inside the chunked array and store it into a variable
  4. Create a conditional statement inside the loop
  5. The condition should check if the last element in the chunked array does not exist or the last element in the chunked array has a lent equal to the N number we are getting.
  6. If the above condition is true we need to push inside the chunked array an array with the element inside our current round of loop. In case is not we need to push the element inside the last element in the chunked array.
last.push(4) = [[1,4]]

Anagrams

Question:

anagrams('rail safety', 'fairy tales') --> Trueanagrams('RAIL! SAFETY!', 'fairy tales') --> Trueanagrams('Hi there', 'Bye there') --> False

Solution

  1. For each string clear all the spaces inside and lower any capital letter
  2. Transform the string into an array of characters.
  3. Sort the element inside the array: cba → abc
  4. Rejoin the sorted array into a new string
  5. comparing both sorted string if they are equal. If they are equal return true or false if they are not equal.

The code

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store