11,693 views
24 votes
24 votes
you are given an array of strings arr. your task is to construct a string from the words in arr, starting with the 0th character from each word (in the order they appear in arr), followed by the 1st character, then the 2nd character, etc. if one of the words doesn't have an ith character, skip that word. return the resulting string.

User Plaul
by
2.3k points

1 Answer

15 votes
15 votes

Answer:

const solution = (arr) => {

const queue = arr

let res = "";

// keep looping untill the queue is empty

while(queue.length>0){

// taking the first word to enter the queue

const cur = queue.shift()

// get and add the first letter of that word

res+= cur.substring(0, 1);

// add the word to the queue if it exists

if(cur!== "") queue.push(cur.slice(1))

}

return res ;

}

console.log(solution(["Daily", "Newsletter", "Hotdog", "Premium"]));

// DNHPaeoriwtelsdmyloiegutmter

console.log(solution(["G", "O", "O", "D", "L", "U", "C", "K"]));

// GOODLUCK

Step-by-step explanation:

Using queue data structure in Javascript

This is the very optimal solution to the question

User Rck
by
3.2k points