Google Interview Question for Software Engineer / Developers


Country: United States
Interview Type: Phone Interview




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

public class ExcelColumn {

public static String excelColumnName(int num){
        if(num==0)
        	return "";
		if (num<=26)
			return Character.toString((char) (num+64));
		else {
			int firstpart=num/26;
		    int end=num%26;
		    end=end==0?26:end;
		    if (firstpart >26)
		    	return excelColumnName((num-end)/26)+Character.toString((char) (end+64));
		    else
		    	return Character.toString((char) ((num-end)/26+64))+Character.toString((char) (end+64));
		}
		
	}
	public static void main(String[] args) {

		for (int i=24;i<30;i++){
			System.out.println(excelColumnName(i));
		}
		System.out.println(excelColumnName(746));
	}

}



X
Y
Z
AA
AB
AC
ABR

- muntean.jenea September 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

It works!
However instead 64, it should be 65, else the Z doesn't appear in the latter combinations.

- chandeepsingh85 September 25, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Thanks, fixed, 64 is because use from [1-n]

- muntean.jenea September 26, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Another possible solution(Python code)

num=int(raw_input())
result=""
while(num>=0):
    t=num%26
    result=chr(ord("A")+t)+result
    num=num/26 -1
    
print result

- dhamu.31954 September 26, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

For 52 it returns BZ where as the it should be AZ.

- Somebody September 26, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@somebody, is your comment to reffer my code..
then,if counting start from 0 then 52 is BA
or if counting start from 1 then its AZ
my code will give BA for 52(because I start counting from 0)
if u want to start counting from 1....just add num=num-1 to my code after raw_input() line
please comment if my code give wrong answer

- dhamu.31954 September 26, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

"For 52 it returns BZ where as the it should be AZ."

It's because all cells containing Z have a trick.

Here's my solution in C#:

using System;
using System.Collections.Generic;
using System.Text;

namespace _0_2_ExcelCells
{
    class Program
    {
        static void Main(string[] args)
        {
        	ExcelHelper helper = new ExcelHelper();

        	Console.WriteLine(helper.IntToCell(1));
        	Console.WriteLine(helper.IntToCell(20));
        	Console.WriteLine(helper.IntToCell(33));
        	Console.WriteLine(helper.IntToCell(47));
        	Console.WriteLine(helper.IntToCell(52));
        	Console.WriteLine(helper.IntToCell(53));
        	Console.WriteLine(helper.IntToCell(16224));
        }
    }

    class ExcelHelper
    {
    	Stack<char> _letters = new Stack<char>();

    	public string IntToCell(int i)
    	{
    		_letters.Clear();

    		GetNextLetter(i);

    	    return GetCell();
    	}

        private string GetCell()
        {
            StringBuilder sb = new StringBuilder();

            while (_letters.Count > 0)
            {
                sb.Append(_letters.Pop());
            }

            return sb.ToString();
        }

        private void GetNextLetter(int i)
    	{
    		if (i == 0)
    		{
    			//Console.WriteLine();

    			return;
    		}

    		int m = i % 26;
    		int n = (int) i / 26;

    		if (m == 0)		// There's a trick with Z cells
    		{
    			m = 26;
    			n--;
    		}

            char letter = (char)(m + 64);   // 64 is 'A' - 1
    		
            _letters.Push(letter);

            GetNextLetter(n);
    	}
    }
}

- Vic September 26, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@dhamu my comment was for muntean.jenea. Your code seems to be correct.

- Somebody September 26, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

public static String exportToExcel( int n ){

                String s = "";

                while( n > 0 ){
                        int t = ( n== 26 ? 26 :  n%26);
                        char c = (char)(t-1 + 'a');
                        s = c+s;
                        n = n/26;
                }

                return s;

        }

- Source February 07, 2015 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Java Implementation:

public class ReplaceNumberWithExcelLabel {
	public static String convertToExcelLabel (int n) {
		String result = "";
		int index = 0;
	    while (n > 0) {
	    	index = (n - 1) % 26;
	    	result = Character.toChars(index + 65)[0] + result;
	    	n = (n - 1) / 26;
	    }
	    return result;
	}
	
	public static void main(String[] args) {
		System.out.println(convertToExcelLabel(1));
		System.out.println(convertToExcelLabel(55));
	}
}

- Adnan Ahmad October 01, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Adnan Ahmad,
Could you explain what is happening here? Character.toChars(index + 65)[0] + result;

what is the deal with [0] index array?

- Anonymous October 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

@ Anonymous
Character Class
- static char[] toChars(int codePoint)
- Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array.

You can also use

result = (char)(index+65) + result;

instead of

result = Character.toChars(index + 65)[0] + result;

- Adnan Ahmad October 14, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Excel {

	public static char column(int n) {
		int d, r;

		int A = 'A';
		int Z = 'Z';
		int numLetters = Z - A + 1;
		char s = ' ';

		while (n > 0) {
			d = (n - 1) / numLetters;
			r = (n - 1) % numLetters;
			s += A + r;
			n = d;
		}
		return Character.toUpperCase(s);
	}

	public static void main(String[] args) {

		for (int i = 1; i <= 26; i++) {
			System.out.println(column(i));
		}

		for (int i = 1; i <= 26; i++) 			
			for (int j = 1; j <= 26; j++)
				System.out.println(column(i) + "" + column(j));

		for (int i = 1; i <= 26; i++)
			for (int j = 1; j <= 26; j++)
				for (int k = 1; k <= 26; k++)
					System.out.println(column(i) + "" + column(j) + ""
							+ column(k));
	}
}

- chandeepsingh85 September 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Could someone provide a better solution than this (O(n^3)) ?

- chandeepsingh85 September 25, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

You missed the point of the question. Given N you should get the corresponding column name.
N = 3 -> "C"
N = 27 -> "AA"
N = 18278 -> "ZZZ"
N = 18279 -> "AAAA"
etc

- Miguel Oliveira September 25, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

oh, any suggestions on how to solve?

- chandeepsingh85 September 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void ConvertToExcel(int number,char* formatted){
	int i = 0, num=number;
	while (num)
	{
		formatted[i++] = 'A'-1 + num % 26;
		num = num / 26;
	}
	formatted[i--] = '\0';
	for (int p = 0, q = i; p < q; p++, q--){
		char temp = formatted[p];
		formatted[p] = formatted[q];
		formatted[q] = temp;
	}

}

- Anonymous September 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String numToColumn(int number){
        
        StringBuilder sb = new StringBuilder();
        char c;
        char s=0;
        int n = number;
        while(n > 0){
            c = (char) ((n - 1) %26);
            s = (char) ((c+65));
            n = (n-c)/26;      
            sb.append(s);
        }
        return sb.toString();
    }

- Frank September 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

the output is mirrored

- muntean.jenea September 25, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

ha, totally right.
sb.reverse().toString() would do. But, I doubt the interviewer would be happy.

- Frank September 25, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

ha, totally right.
sb.reverse().toString() would do. But, I doubt the interviewer would be happy.

- Frank September 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

final static char[] alpha = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

static int LENGTH = alpha.length;

public static String generatevariable(int a) {
int t = a;
StringBuffer s = new StringBuffer("");
if (a == 0)
return "";
if (a <= LENGTH)
s.append(alpha[a - 1]);
else {
s.append(generatevariable((a - 1) / LENGTH)); // use recursion
s.append(generatevariable(a - ((a - 1) / LENGTH) * LENGTH));
}
return s.toString();
}

- genier September 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def main():
  num = int(input())
  col = ''
  
  while num > 0:
    c = chr((num-1)%26+65)
    col = c+col
    num = (num-1)//26
  
  print(col)
  

if __name__ == '__main__':
  main()

- . September 26, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static char [] chars = new char[27];
	static {
		char c = 'A';
		for(int i=0;i<26; i++)
			chars[i] = c++;
	}
	static String getExcelValue(int num) {
		return getExcel(num-1);
	}
	static String getExcel(int num) {
		
		int rem = num % 26;
		int quot = num / 26;
		
		if(quot > 0)
			return getExcel(quot-1) + chars[rem];		
		return ""+chars[rem];
	}

- ro September 26, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ExcelColumn
{
    public static void printColumnName(int n) {
	    if(n/26>0) { // recurse
			printColumnName(n/26-1);
		}
		
		//print character
		System.out.print(Character.toString((char)('A'+n%26)));
	}
	
    public static void main(String[] args) {
		printColumnName(Integer.parseInt(args[0])-1);
	}
}

- anonymous September 26, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

python code

num=int(raw_input())
result=""
while(num>=0):
    t=num%26
    result=chr(ord("A")+t)+result
    num=num/26 -1
    
print result

- dhamu.31954 September 26, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void findXLcolumnByNumber(int number){
		List<Character> lst = new ArrayList<Character>();
		while (number > 0){			
			int b = number % 26;
			number = number / 26;
			b = b == 0 ? 26 : b;
			lst.add((char) (b + 64));
		}
		
		for (int i = lst.size() - 1; i >= 0; i--)System.out.print(lst.get(i));
		System.out.println();
	}

- Amit September 26, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

Isn't this problem same as converting a number in decimal system into a number in a (26 digit) system with (A....Z) as the digits?

- Prasad September 27, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

in c++ code

void columeInExcel(int number)
{
	string dic=" ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	vector<char> result;
	while(number)
	{
		int low = number%26;
		int high = number/26;
		if(high == 1 && low == 0)
		{
			result.push_back('z');
			break;
		}
		result.push_back(dic[low]);
		number = high;
	}
	for(int i = result.size()-1; i>=0; i--)
		cout << result[i];
	cout << endl;
}

- nkpangcong October 12, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Did this or something similar some time back, check the below link if you think this help.
ms-amazon.blogspot.in/2013/03/there-is-sequence-where-alphabets-are.html

- varun October 14, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ExcelColumns {

public static String getExcelColumnName(int n){
if(n < 1) return null;
StringBuilder sb = new StringBuilder();
while(n > 0){
sb.append((char)('A'+(n-1)%26));
n= (n-1)/26;

}
return sb.reverse().toString();

}


public static void main(String[] args) {
for (int i = 1; i < 5000; i++) {
System.out.print(getExcelColumnName(i)+",");
}
}
}

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

public class ExcelColumns {

	public static String getExcelColumnName(int n){
		if(n < 1) return null;
		StringBuilder sb = new StringBuilder();
		while(n > 0){
			sb.append((char)('A'+(n-1)%26));
			n= (n-1)/26;
			
		}
		return sb.reverse().toString();
		
	}

	
	public static void main(String[] args) {
		for (int i = 1; i < 5000; i++) {
			System.out.print(getExcelColumnName(i)+",");
		}
	}
}

- konst May 09, 2014 | 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