Google Interview Question for Software Engineers


Country: United States




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

thanks for posting question. But as posted its not clear what is required in question. Why can't second row be "run do do" (7 letters and 2 spaces fit in second row)

- Anonymous July 15, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

The answer is 5 for the above example

- rucknrull July 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//Time Complexity: Worst case: O(NM) where N is the number of words in input and M is the number of rows.
public class Solution

{
	
	
	public String[] arrange(String[] words,int rows, int cols)
	{
		if(words==null||words.length==0||rows<=0||cols<=0)
		{
			return null;
		}
	
		String[] arr=new String[rows];
		int i=0;
		for(int j=0;j<arr.length;j++)
		{
			
			int c=0;
			int wordCount=0;
			int spaceCount=0;
			while(c+arr[i].length()<=cols)
			{
				wordCount++;
				if(c+arr[i].length()<cols)
				{
					spaceCount++;
					c++;
				}
				c+=arr[i++].length();
				if(i==arr.length)
				{
					i=0;
				}
			}
			StringBuilder sb=new StringBuilder();
			spaceCount=spaceCount+((c!=0)?cols-c:0);
			sb.append(wordCount + " words " + spaceCount+ " spaces" );
			arr[j]=sb.toString();
		}
		return arr;
	}
	
}

- divm01986 July 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Time complexity: O (row * col)

// Example program
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int findNumberOfWords(vector<string> stringList, int row, int col){
    int r = 0, c = 0, i = 0;
    int res = 0;
    while (r < row){
        cout << r << " " << c << " " << stringList[i] << " " << res << endl;
        if (stringList[i].length() > col) return res;
        if (stringList[i].length()+ (c==0?0:1) + c <= col) {
            if (c + stringList[i].length()+ (c==0?0:1) == col) r++;
            c = (c + stringList[i].length()+ (c==0?0:1)) % col;
            i = (i + 1) % stringList.size();
            res++;
        } else {
            r++; c = 0;
        }
        
    }
    return res;
}

int main()
{
    //Input
    vector<string> stringList = {"aa", "aaa"};
    int row = 2;
    int col = 9;
    cout << findNumberOfWords(stringList, row, col) << endl;
    return 0;
}

- vucuong020195 July 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

TimeComplexity O(mn)

public class WordsCounting {

	public static void main(String[] args) {
		String words[] = new String[] { "Do" , "run"};
		int row = 2 , col = 9;
		System.out.println(countWords( words , row , col));
		
	}

	private static int countWords(String[] words, int row, int col) {
		// TODO Auto-generated method stub
		int wordCount = 0;
		int rowIterator = 0;
		int wordIterator = 0;
		int remainingCol;
		while ( rowIterator < row )	{
			remainingCol = col;
			while ( remainingCol > 0 && words[wordIterator].length() <= remainingCol)	{
				wordCount++;
				// update remainingCol , takes wordspacing into account
				remainingCol = remainingCol - words[wordIterator].length() - 1;
				wordIterator++;
				if (wordIterator == words.length)
					wordIterator = 0;
			}
			// IF the word length in any case doesn't fit in the column , increment the wordIterator
			if ( words[wordIterator].length() > col)	{
				wordIterator++;
				if (wordIterator == words.length)
					wordIterator = 0;
			}
			//else do a row increment
			else	{
				rowIterator++;
			}
		}
		
		return wordCount;
	}

}

- Sibendu Dey July 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;

public class stringifyMe {

	public static void main(String[] args) {
		System.out.println(Arrays.toString(countWord( new String [] {"Do", "Run"}, 9,2)));
	}
	public static int [] countWord (String [] wordList, int cols, int rows) {
		int [] charCount = new int [rows]; //number of chars used
		int [] wordCount = new int [rows]; //number of words used
		int N = wordList.length;           //number of available words in the list
		int wordLoc = 0; 				   //location of the current word (start from the first word)
		for (int i = 0; i < rows; i++) {   //Loops over the rows
			while(true) {
				int temp = wordList[wordLoc].length(); 
				if (temp > cols-charCount[i]) break; //Quit a row once there are no more spaces available
				else {								 //If there are still space increment
					charCount[i] += temp+1;
					wordCount[i] += 1;
					wordLoc = (wordLoc + 1) % N;     //Index of the word should stay between 0 -> N-1
				}
			}
		}
		return wordCount;
	}
}

- AbdallahCh89 July 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

You can do this in O(mLog(n)) where m = number of rows and n = number of words using binary search after summing the length of all the original words.

- Chris July 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void ConvertWordsinRowCol(const vector<string>& vWords, int numRows, int numCols, vector<string>& LineofWords)
{
	int cols = 0, rows = 0;
	int sizes = vWords.size();
	int last = 0;
	bool first = true;
	string rowStr;

	while (rows < numRows)
	{
		while (cols < numCols)
		{
			for (int i = last; i < sizes; i++)
			{
				if (first)
					cols += vWords[i].length();
				else
					cols += vWords[i].length() + 1;

				if (cols > numCols)
				{
					last = i; break;
				}

				if (first)
					first = false;
				else
					rowStr += ' ';

				rowStr += vWords[i];
			}
			if (cols <= numCols) last = 0;
		}
		LineofWords.push_back(rowStr);
		rows++; cols = 0; 
		first = true; rowStr = "";
	}
}

- LANorth July 17, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void WordFitRow(const std::vector<std::string>& str, int row, int col){
    int count  =0;
    int strLength  = str.size();
    while(row--){
        int length  =0;
        while(length+str[count%strLength].size() <=col){
            std::cout << str[count%strLength];
            length = length + str[count%strLength].size()+1;
            count++;
            if(length+str[count%strLength].size() <=col) std::cout << " ";

        }
        if(length!=0)std::cout << std::endl;
    }
}

- babalonso July 17, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Main {

    public static void main(String[] args) {
        List<String> words = new ArrayList<>();
        words.add("Do");
        words.add("Run");
        System.out.println(CountWordsInMatrix.countWordsInMatrix(words, 2, 9));
    }
}

public class CountWordsInMatrix {

    public static int countWordsInMatrix(List<String> words, int rows, int columns) {
        if (words == null || words.size() == 0 || rows <= 0 || columns <= 0) {
            return 0;
        }
        int countWords = 0;
        int numberOfWord = 0;
        for (int i = 0; i < rows; i++) {
            int freeColumns = columns;
            while (freeColumns > 0) {
                for (int j = numberOfWord; j < words.size(); j++) {
                    freeColumns = numberOfFreeColumns(freeColumns, words.get(j).length(), freeColumns == columns);
                    if (freeColumns >= 0) {
                        countWords++;
                    } else {
                        numberOfWord = j;
                        break;
                    }
                }
            }
        }
        return countWords;
    }


    public static int numberOfFreeColumns(int freeColumn, int wordLength, boolean isBeginning) {
        if (freeColumn < wordLength) {
            return -1;
        }
        if (isBeginning) {
            return freeColumn - wordLength;
        }
        return freeColumn - wordLength - 1;
    }
}

- Egoralve July 19, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
		String list[]={"Do","Run","Jump","Hide"};
		int c =20;
		int r=4;
		int count =findwc(list,c,r);

	}

	private static int  findwc(String[] list, int c, int r) {
		String result="";
		int count =0;
		int currentrow=0;
		int i=0;
		while(currentrow<r){ //through rows
				while(true){
					if(result.length()>=c){ //checking number of columns used
						break;
					}
					if(result.length()>0){ // checking when to add space
						result=result+" ";
					}
					if(i==list.length){ // resetting list iterator 
						i=0;
					}
					result=result+list[i]; 
					count++;
					i++; //1 //2 //1
				}
				System.out.println(result);
				currentrow++;
				result="";
			}
		System.out.println(count);
		return count;
		}
}

- Neethi Elizabeth Joseph July 20, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

n

- Anonymous July 21, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/*
   Given a list of words, and the number of rows and columns, return the number of words that can be fit into the rows and columns by stringing together each consecutive word. If the next word doesn't fit in the same line, it should move to the next line. Find an efficient solution for this. For eg.

   List of words: { "Do", "Run" }
   Number of columns: 9
   Number of rows: 2

   First row: "Do Run Do" (7 letters + 2 spaces fit into 9 columns)
   Second row: "Run Do" (Only 2 words fit into 9 columns)
 */

#include <vector>
#include <string>
#include <iostream>
void WordFitRow(const std::vector<std::string>& str, int row, int col){
        int count  =0;
        int strLength  = str.size();
        while(row--) {
                int length  =0;
                while(length+str[count%strLength].size() <=col) {
                        std::cout << str[count%strLength];
                        length = length + str[count%strLength].size()+1;
                        count++;
                        if(length+str[count%strLength].size() <=col) std::cout << " ";

                }
                if(length!=0) std::cout << std::endl;
        }
}


int main(){
        std::vector<std::string> v  = { "Do", "Run" };
        WordFitRow(v, 2, 9);
        return 0;
}

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

public class Solution {
    
    public static void main(String [] args) {
        
        String [] array = {"DO", "RUN"};
        
        print(array, 2, 9);
        
    }
    
    public static void print(String [] words, int row, int column) {
        
        int word = 0;
        int i = 0;
        int j = 0;
        
        while (i < row) {
            
            if (words[word].length() <= column-j) {
                System.out.print(words[word] + " ");
                j = j + 1 + words[word].length();
                word++;
                word %= words.length;
            } else {
                System.out.println();
                j = 0;
                i++;
            }
            
        }
        
    }
    
}

- ugurdonmez87 July 24, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def build_text_grid(w_list, row, col):
    i = 0
    j = 0
    w = 0
    words_num = 0
    
    while i < row:
        word = w_list[w]
        added = False
        if j == 0 and len(word) <= col:
            j = len(word)
            added = True
        elif len(word) + 1 <= col - j:
            j += len(word) + 1
            added = True
        else:
            i += 1
            j = 0
        
        if added:
            words_num += 1
            w += 1
            if w == len(w_list):
                w = 0

    return words_num
                
print build_text_grid(["do", "more"], 2, 20)

- Nitish Garg January 13, 2017 | 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