Google Interview Question for Front-end Software Engineers


Country: United States
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
4
of 4 vote

private void printLettersInColors(String sentence, String[] colors) {
	if(sentence == null || sentence.length() == 0 || colors == null || colors.length == 0) // validation
		return;
	int no = colors.length; // length can't be more than Integer.MAX_VALUE
	int index = 0;
	for(char c : sentence.toCharArray()) {
		if(c != ' ') {
			System.out.println(c+ " - " + colors[index++%no]);
		} else {
			System.out.println(" ");
		}
	}
}

- Popeye May 08, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

may be I didn't understand the question correctly. Please let anyone explain.

- Popeye May 08, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

No. Perhaps only you understood how to do it anyways.

- NoOne May 08, 2019 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

void printcolorString(std::string str1, std::string colors[])
{
	HANDLE hAndle =  GetStdHandle(STD_OUTPUT_HANDLE);

	int iNdex = 0;
	int nlength = str1.length();
	int colorIndex = 0;
	while (iNdex <= nlength)
	{
		if(str1[iNdex] == ' ')
			SetConsoleTextAttribute(hAndle, 255);
		else
			SetConsoleTextAttribute(hAndle , colorIndex++);

		printf("%c", str1[iNdex]);
		iNdex++;
	}
}

- sullad May 10, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

import Data.Char

type Color = [String] 

zipColorWord :: String -> Color -> [(Char, String)]
zipColorWord [] _ = []
zipColorWord (c : cs) (w : ws) 
  | isSpace c = zipColorWord cs (w : ws)
  | otherwise = (c, w) : zipColorWord cs ws


repeatList :: [String] -> [String] 
repeatList xs = ret where 
  ret = xs ++ repeatList xs 

ans :: [(Char, String)]
ans = zipColorWord "Lorem ipsum dolor sit amet" (repeatList ["red", "blue", "green", "yellow"])

- Keep_learning May 11, 2019 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

void printcolorString(std::string str1, std::string colors[])
{
	HANDLE hAndle =  GetStdHandle(STD_OUTPUT_HANDLE);

	int iNdex = 0;
	int nlength = str1.length();
	int colorIndex = 0;
	while (iNdex <= nlength)
	{
		if(str1[iNdex] == ' ')
			SetConsoleTextAttribute(hAndle, 255);
		else
			SetConsoleTextAttribute(hAndle , colorIndex++);

		printf("%c", str1[iNdex]);
		iNdex++;
	}
}

- sullad May 10, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class bcolors:
    BLUE = '\033[94m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    RED = '\033[91m'
    ENDC = '\033[0m'


class ColourString(bcolors):

    def __init__(self, string):
        self.dictionary = {"l": bcolors.RED,
                           "o": bcolors.BLUE,
                           "r": bcolors.GREEN,
                           "e": bcolors.YELLOW,
                           "m": bcolors.RED,
                           "END_COLOUR": bcolors.ENDC}

        self.string = string
        self.coloured_string = ""
        self._colour()

    def _colour(self):
        previous_char = ""
        for char in self.string:
            if char.isspace():
                self.coloured_string += " "
            elif previous_char.isspace():
                self.coloured_string += (bcolors.BLUE+char+self.dictionary["END_COLOUR"])
            elif char.lower() in self.dictionary.keys():
                self.coloured_string += (self.dictionary[char.lower()]+char+self.dictionary["END_COLOUR"])
            else:
                self.coloured_string += char
            previous_char = char

string = "Lorem ipsum dolor sit amet"
first = ColourString(string)
print(first.coloured_string)

- Piotr May 08, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class bcolors:
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'


class ColourString(bcolors):

def __init__(self, string):
self.dictionary = {"l": bcolors.RED,
"o": bcolors.BLUE,
"r": bcolors.GREEN,
"e": bcolors.YELLOW,
"m": bcolors.RED,
"END_COLOUR": bcolors.ENDC}

self.string = string
self.coloured_string = ""
self._colour()

def _colour(self):
previous_char = ""
for char in self.string:
if char.isspace():
self.coloured_string += " "
elif previous_char.isspace():
self.coloured_string += (bcolors.BLUE+char+self.dictionary["END_COLOUR"])
elif char.lower() in self.dictionary.keys():
self.coloured_string += (self.dictionary[char.lower()]+char+self.dictionary["END_COLOUR"])
else:
self.coloured_string += char
previous_char = char

string = "Lorem ipsum dolor sit amet"
first = ColourString(string)
print(first.coloured_string)

- Piotr May 08, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class bcolors:
    BLUE = '\033[94m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    RED = '\033[91m'
    ENDC = '\033[0m'


class ColourString(bcolors):

    def __init__(self, string):
        self.dictionary = {"l": bcolors.RED,
                           "o": bcolors.BLUE,
                           "r": bcolors.GREEN,
                           "e": bcolors.YELLOW,
                           "m": bcolors.RED,
                           "END_COLOUR": bcolors.ENDC}

        self.string = string
        self.coloured_string = ""
        self._colour()

    def _colour(self):
        previous_char = ""
        for char in self.string:
            if char.isspace():
                self.coloured_string += " "
            elif previous_char.isspace():
                self.coloured_string += (bcolors.BLUE+char+self.dictionary["END_COLOUR"])
            elif char.lower() in self.dictionary.keys():
                self.coloured_string += (self.dictionary[char.lower()]+char+self.dictionary["END_COLOUR"])
            else:
                self.coloured_string += char
            previous_char = char

string = "Lorem ipsum dolor sit amet"
first = ColourString(string)
print(first.coloured_string)

- Piotr May 08, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include <stdlib.h>

// #define IMRed ......, where ..... you can repace ASCII of your choice of compiler or header file string which give perticular color

#define IMRED   .....
#define IMBlue   ....
#Define IMGreen  ....
#define IMYellow  ...
#deinfe IMRESETCOLOR_SPACE    ...


void Red(char *ch)
{
 printf("\n IMRed (%C)",*ch);
}
void Blue(char *ch)
{   
printf("\n IMBlue (%C)",*ch);
}
void Green(char *ch)
{   
printf("\n IMGreen (%C)",*ch);
}
void Yellow(char *ch)
{ 
  printf("\n IMYellow (%C)",*ch);
}

void (*func[4])(char *ch);// pointer to function of Red, blue, green ,yellow

int main()
{
    char colors[][20]={"red", "blue", "green", "yellow"};
    char str[]="Lorem ipsum dolor sit amet";
func[0]=Red;
func[1]=Blue;
func[2]=Green;
func[3]=Yellow;

int color_choice=sizeof(colors)/sizeof(colors[0]); //here 4

char *ch=str;
int color_num=0;

while(*ch!='\0'){
if(*ch==' ')
{
    printf("\n IMRESETCOLOR_SPACE ( )");ch++;continue;
}
else
{func[color_num%color_choice](ch);
color_num++;
ch++;
}
}
return 0;
}

- Anonymous May 09, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private void printLettersInColors(String sentence, String[] colors) {
if(sentence == null || sentence.length() == 0 || colors == null || colors.length == 0) // validation
return;
int no = colors.length; // length can't be more than Integer.MAX_VALUE
int index = 0;
for(char c : sentence.toCharArray()) {
if(c != ' ') {
System.out.println(c+ " - " + colors[index++%no]);
} else {
System.out.println(" ");
}
}
}

- Anonymous May 09, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Using zip function and infinite repeat of list, it's just couple of lines in Haskell.

import Data.Char

type Color = [String] 

zipColorWord :: String -> Color -> [(Char, String)]
zipColorWord [] _ = []
zipColorWord (c : cs) (w : ws) 
  | isSpace c = zipColorWord cs (w : ws)
  | otherwise = (c, w) : zipColorWord cs ws


repeatList :: [String] -> [String] 
repeatList xs = ret where 
  ret = xs ++ repeatList xs 

ans :: [(Char, String)]
ans = zipColorWord "Lorem ipsum dolor sit amet" (repeatList ["red", "blue", "green", "yellow"])

*Main> ans
[('L',"red"),('o',"blue"),('r',"green"),('e',"yellow"),('m',"red"),('i',"blue"),('p',"green"),('s',"yellow"),('u',"red"),('m',"blue"),('d',"green"),('o',"yellow"),('l',"red"),('o',"blue"),('r',"green"),('s',"yellow"),('i',"red"),('t',"blue"),('a',"green"),('m',"yellow"),('e',"red"),('t',"blue")]

- Keep_learning May 11, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Using zip function, and infinite repeating list, it's just couple of lines in Haskell.

import Data.Char

type Color = [String] 

zipColorWord :: String -> Color -> [(Char, String)]
zipColorWord [] _ = []
zipColorWord (c : cs) (w : ws) 
  | isSpace c = zipColorWord cs (w : ws)
  | otherwise = (c, w) : zipColorWord cs ws


repeatList :: [String] -> [String] 
repeatList xs = ret where 
  ret = xs ++ repeatList xs 

ans :: [(Char, String)]
ans = zipColorWord "Lorem ipsum dolor sit amet" (repeatList ["red", "blue", "green", "yellow"])

- Anonymous May 11, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import Data.Char

type Color = [String] 

zipColorWord :: String -> Color -> [(Char, String)]
zipColorWord [] _ = []
zipColorWord (c : cs) (w : ws) 
  | isSpace c = zipColorWord cs (w : ws)
  | otherwise = (c, w) : zipColorWord cs ws


repeatList :: [String] -> [String] 
repeatList xs = ret where 
  ret = xs ++ repeatList xs 

ans :: [(Char, String)]
ans = zipColorWord "Lorem ipsum dolor sit amet" (repeatList ["red", "blue", "green", "yellow"])

- Keep_learning May 11, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

fsdfsdf

- Anonymous May 11, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

hell

- asdf May 11, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import Data.Char

type Color = [String] 

zipColorWord :: String -> Color -> [(Char, String)]
zipColorWord [] _ = []
zipColorWord (c : cs) (w : ws) 
  | isSpace c = zipColorWord cs (w : ws)
  | otherwise = (c, w) : zipColorWord cs ws


repeatList :: [String] -> [String] 
repeatList xs = ret where 
  ret = xs ++ repeatList xs 

ans :: [(Char, String)]
ans = zipColorWord "Lorem ipsum dolor sit amet" (repeatList ["red", "blue", "green", "yellow"])

- Keep_learning May 11, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Javascript solution

function displayColorfulText(colors, text){
const strArray = text.split(' ');

const createSpanElementWithColor = (text, color) => {
let elm = document.createElement('span');
// set the innner text and then add color to it
elm.innerText = text+ ' ';
elm.style.color = color;

console.log(elm);
return elm;
}

// get element by id and then set the inner html to it
let parent = document.createElement('result');
strArray
.map((str, i) => createSpanElementWithColor(str, colors[i]))
.forEach(el => parent.appendChild(el));
document.body.appendChild(parent);

}

displayColorfulText(["red", "blue", "green", "yellow"], "Lorem ipsum dolor sit amet");

- Anonymous May 13, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void printInColors(String colors[], String str){
        int x = 0;
        int size = colors.length;
        for(int i=0;i<str.length();i++){
            if(str.charAt(i)!=' '){
                System.out.println(str.charAt(i)+" is "+colors[x%size]);
                x++;
            }
        }
    }

- rahulroshan96 May 13, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

C# solution

const ConsoleColor defaultConsoleColor = ConsoleColor.White;

        public static void TestPrintColors()
        {
            // Question
            // https://www.careercup.com/question?id=5739126414901248
            string[] colors = new string[] {"red", "blue", "green", "yellow"};
            string str = "Lorem ipsum dolor sit amet";
            PrintColor(colors, str);
        }

        static void PrintColor(string[] colors, string str)
        {
            int colorIndex = 0;
            foreach(char log in str)
            {
                if (char.IsWhiteSpace(log))
                {
                    Console.Write(log);
                    continue;
                } 
                colorIndex = (colorIndex + 1) % colors.Length;
                Console.ForegroundColor = GetColor(colors[colorIndex]);;
                Console.Write(log);
            }
            
            CleanUpConsole();
        }

        static ConsoleColor GetColor(string colorStr)
        {
            ConsoleColor color;
            if (!Enum.TryParse(colorStr, true, out color))
            {
                return defaultConsoleColor;
            }

            return color;
        }

        static void CleanUpConsole()
        {
            Console.WriteLine("");
            Console.ForegroundColor = defaultConsoleColor;
        }

- AustinTaylorx May 16, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static Dictionary<string, ConsoleColor> ColorsMap = new Dictionary<string, ConsoleColor>()
    {
      { "red", ConsoleColor.Red },
      { "blue", ConsoleColor.Blue },
      { "green", ConsoleColor.Green },
      { "yellow", ConsoleColor.Yellow },
    };

    public static void PrintColored(string output, string[] colors)
    {
      int colorId = 0;
      foreach (char c in output)
      {
        string colorStr = colors[colorId];
        if (!ColorsMap.ContainsKey(colorStr))
        {
          throw new ArgumentException($"Unknown color {colorStr}");
        }
        PrintColored(c, ColorsMap[colorStr]);

        colorId = (colorId + 1) % colors.Length;
      }
    }

    public static void PrintColored(char output, ConsoleColor color)
    {
      var prevColor = Console.ForegroundColor;
      Console.ForegroundColor = color;
      Console.Write(output);
      Console.ForegroundColor = prevColor;
    }

- dimi May 17, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var colors = ["red","blue" , "green" , "tellow"];

var string = "Lorem ipsum dolor sit amet";
var finalStr = "";

var i = 0;
while(i < string.length) {

    var char = string[i];
    if(char !== " ") {
       var current = colors.shift();
       finalStr += `<span style="font-size:20px;color:${current}">${char} </span>`;
       colors.push(current);
    }
    i++;
}

console.log(finalStr);

- guru June 08, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var colors = ["red","blue" , "green" , "tellow"];

var string = "Lorem ipsum dolor sit amet";
var finalStr = "";

var i = 0;
while(i < string.length) {

    var char = string[i];
    if(char !== " ") {
       var current = colors.shift();
       finalStr += `<span style="font-size:20px;color:${current}">${char} </span>`;
       colors.push(current);
    }
    i++;
}

console.log(finalStr);

- guru June 08, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

JavaScript Solution

const colorPrinter = (str, colorsArray) => {
	let i = 0;
	str.split('').forEach((ch, ind) => {
  	if(ch !== ' '){
    		i = (i === colorsArray.length) ? 0 : i;
      	console.log(`Character ${ch} : ${colorsArray[i]}`);
        i++;
    }
  });
}

colorPrinter('Lorem ipsum in the world', ['red', 'blue', 'green', 'yellow', 'white']);

- Ambica July 22, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

JavaScript Solution:

const colorPrinter = (str, colorsArray) => {
let i = 0;
str.split('').forEach((ch, ind) => {
if(ch !== ' '){
i = (i === colorsArray.length) ? 0 : i;
console.log(`Character ${ch} : ${colorsArray[i]}`);
i++;
}
});
}

colorPrinter('Lorem ipsum in the world', ['red', 'blue', 'green', 'yellow', 'white']);

- Ambica July 22, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

const colorPrinter = (str, colorsArray) => {
	let i = 0;
	str.split('').forEach((ch, ind) => {
  	if(ch !== ' '){
    		i = (i === colorsArray.length) ? 0 : i;
      	console.log(`Character ${ch} : ${colorsArray[i]}`);
        i++;
    }
  });
}

colorPrinter('Lorem ipsum in the world', ['red', 'blue', 'green', 'yellow', 'white']);

- Ambica July 22, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

colors = ["red", "blue", "green", "yellow"];
str = "Lorem ipsum dolor sit amet";


var printStingColor = function(str, colors){

str = str.split('');
colorsLen = colors.length;
j = 0;
str.forEach(function(ele){
if(ele !== ' '){
console.log(ele+' = '+ colors[j%colorsLen]);
j++;
}

});
}

- anandk.kumar506 September 18, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

document.write(colorLetters("Lorem ipsum dolor sit amet",["red", "blue", "green", "yellow"]));

function colorLetters(sentence, colors){
  let count =0;
  let result = '';
  for (let i=0;i< sentence.length; i++){
    if (sentence[i] !== '') {
      result += `<span style="color: ${colors[count]}">${sentence[i]}</span>`;
      count++;
      if (count>colors.length-1){
        count =0;
      }
    }else{
      result +=sentence[i];
    }
  }
  return result;
}

- Aiman October 09, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

const colors = ["red", "blue", "green", "yellow"];
const str= "Lorem ipsum dolor sit amet";

const printStrColors = (str="", colors=[]) => {
let colorIndex = 0;
const strArr = [...str];

const getColor = () => {
const index = colorIndex % colors.length;
colorIndex ++;
return colors[index];
}
const getStyle = letter => {
if(new RegExp(/\w/).test(letter)) {
return `style="color: ${getColor()}"`
}
return ''
}

return strArr.map(l => `<span ${getStyle(l)}>${l}</span>`).join('')
}
printStrColors(str, colors)

- Ali Latifi October 24, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

const colors = ["red", "blue", "green", "yellow"];
const str= "Lorem ipsum dolor sit amet";

const printStrColors = (str="", colors=[]) => {
  let colorIndex = 0;
  const strArr = [...str];

  const getColor = () => {
    const index = colorIndex % colors.length;
    colorIndex ++;
    return colors[index];
  }
  const getStyle = letter => {
    if(new RegExp(/\w/).test(letter)) {
      return `style="color: ${getColor()}"`
    }
    return ''
  }
  
  return strArr.map(l => `<span ${getStyle(l)}>${l}</span>`).join('')
}
printStrColors(str, colors)

- Ali Latifi October 24, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

const colorize = (str, colors) => {
  let colorIndex = 0;
  return str.split(" ").map(word => {
    return word.split("").map((letter, index) => {
      if (colorIndex === colors.length) colorIndex = 0;
      return `<span style="color: ${colors[colorIndex++]}">${letter}</span>`;
    }).join('');
  }).join('&nbsp;');
};

- ccsCoder December 01, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function cp(colors, str){
var strn = '';
var colnth= colors.length;
var a=[], clsx=[];
str.split(' ').forEach((word, index)=>{
a.push(word.replace(/./g, x=>'%c'+x));
clsx = clsx.concat(word.split('').map((char, idx)=>`color:${colors[(idx+index)%colnth]}`))
})
console.log.apply(this, [a.join(' '), ...clsx])
}

- kanine February 08, 2020 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

str.split(' ').map((word, wi) => word.split('').map((ch, chi) => `<span style='color:${ colors[(wi + chi) % 4] }'>${ ch }</span>`).join('')).join(' ')

- yairniz February 21, 2020 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

const colors = ['red','blue','green','yellow'];
const str = 'Lorem ipsum dolor sit amet';

const wrappper = document.getElementById('wrappper')

let emptyItemCount = 0;

const splitedStr = str.split('')
for(let i = 0, len = splitedStr.length; i < len; i++) {
  const letter = splitedStr[i]
   if (letter === ' ') {
    const text = document.createElement('span')
    text.innerHTML = '  '
    wrappper.appendChild(text)
    emptyItemCount++;
    continue;
  }
  
  const strong = document.createElement('strong')
 
  strong.innerHTML = letter
  const colorIndex = (i - emptyItemCount) % 4
  strong.style.color = colors[colorIndex]
  wrappper.appendChild(strong)
}

- Kenan February 26, 2022 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

const colors = ['red','blue','green','yellow'];
const str = 'Lorem ipsum dolor sit amet';

const wrappper = document.getElementById('wrappper')

let emptyItemCount = 0;

const splitedStr = str.split('')
for(let i = 0, len = splitedStr.length; i < len; i++) {
  const letter = splitedStr[i]
   if (letter === ' ') {
    const text = document.createElement('span')
    text.innerHTML = '  '
    wrappper.appendChild(text)
    emptyItemCount++;
    continue;
  }
  
  const strong = document.createElement('strong')
 
  strong.innerHTML = letter
  const colorIndex = (i - emptyItemCount) % 4
  strong.style.color = colors[colorIndex]
  wrappper.appendChild(strong)
}

- Kenan * February 26, 2022 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More