Google Interview Question for Front-end Software Engineers


Country: United States
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
3
of 3 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# soulution, Improvement suggestions are appretiated!

static void TestPrintColors()
        {
            string[] colors = new string[4] {"red", "blue", "green", "yellow"};
            string str = "Lorem ipsum dolor sit amet";
            PrintColors(colors, str);
        }

        static void PrintColors(string[] colors, string str)
        {
            char log;
            ConsoleColor originalColor = Console.ForegroundColor;
            int colorIndex = 0;
            ConsoleColor currentColor = originalColor;
            for (int i = 0; i < str.Length; i++)
            {
                log = str[i];

                if (log == ' ')
                {
                    Console.Write(log);
                    continue;
                }
                
                switch(colors[colorIndex])
                {
                    case "red":
                    currentColor = ConsoleColor.Red;
                    break;

                    case "blue":
                    currentColor = ConsoleColor.Blue;
                    break;

                    case "green":
                    currentColor = ConsoleColor.Green;
                    break;

                    case "yellow":
                    currentColor = ConsoleColor.Yellow;
                    break;

                    default:
                    currentColor = originalColor;
                    break;
                }

                colorIndex++;

                if (colorIndex >= colors.Length)
                {
                    colorIndex = 0;
                }

                Console.ForegroundColor = currentColor;

                Console.Write(log);
            }

            // Clean up
            Console.WriteLine("");
            Console.ForegroundColor = originalColor;
        }

- 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


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