Amazon Interview Question for Software Engineer / Developers


Country: India
Interview Type: Phone Interview




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

Number of a's = (int)k/26;
Terminating Charter = k%26, where
1 = a
2 = b
.
.
.
26 = z

So, if k=28
No. of a's = (int)28/26 = 1
Terminating Character = 28%26 = 2
Hence result = ab

- ravigupta May 17, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

You are thinking the sequence goes a, b..... aa,ab......aaa,aab.... but in fact it increments like a number with base 26... so like the next letter after az is not aaa but ba...

your answer is incorrect...

think about base 26

- rdo May 18, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Can be solved use a recursive method:


import java.util.HashMap;

public class FindTheKthString {

private static HashMap<Integer, StringBuffer> letterCode = new HashMap<Integer, StringBuffer>();

static {
for (int i = 1; i < 26; i++) {
letterCode.put(i, new StringBuffer(Character.toString((char) (i + 96))));
letterCode.put(0, new StringBuffer(Character.toString((char) (26 + 96))));
}
}


private static StringBuffer getTheStringAtKthPosition(int i) {
int lastIndex = i%26;
int step = (i-1)/26;

if(step==0)
{
return new StringBuffer(letterCode.get(lastIndex));
}

else
{
return getTheStringAtKthPosition(step).append(letterCode.get(lastIndex));

}

}


public static void main(String[] args) {
for(int index=700;index<=740;index++)
{
System.out.println(index+" "+getTheStringAtKthPosition(index));
}
}
}

- qingd7 May 17, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

@gingd7 nice soln..

- bjain May 17, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Very neat solution

- Kiddo July 19, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

public class abcdQuestion {

public static void main(String[] args) {
printString(28);

}

public static void printString(int k) {
if (k <= 26) {
System.out.println(Character.toString((char) (96 + k)));

return;
}

HashMap<Integer, String> hp = new HashMap<Integer, String>();
HashMap<Integer, String> temp = new HashMap<Integer, String>();

for (int i = 1; i <= 26; i++) {

hp.put(i, Character.toString((char) (i + 96)));

}
int count = 27;
int l = 1;

while (count <= k) {

String s = hp.get(l);

Iterator<Entry<Integer, String>> it = hp.entrySet().iterator();
while (it.hasNext() && count <= k) {
String d = s + it.next().getValue();

temp.put(count, d);
count++;

}
hp.putAll(temp);

if ((count - 1) == k) {
System.out.println(hp.get(k));
return;
}

l = l + 1;
}

}
}

- bjain May 17, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

here the output will be "ab" when the function printString is called with k=28

- bjain May 17, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

int main(){

int ar[10];
int n,t,q,r,k,i;
scanf("%d",&n);

k=0;
r = n%26;
ar[k] = r;
q = n/26;
while(q != 0){
k++;
r = q%26;
ar[k] = r;
q = q/26;
}
printf("Binary:\n");
t=k;
while(t >= 0)
printf("%d | ",ar[t--]);

while(k >= 0){
i=k-1;
if(ar[i] != 0){
t = ar[k--] + 96;
printf("%c",t);
}
else{
if(ar[k] > 1){
t = ar[k] + 95;
printf("%c",t);
}
t = 26 + 96;
printf("%c",t);
k=k-2;
}
}

return;
}

- vis May 18, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Assumption user will enter +ve value starting from one.

void InterviewQuestions::findValueInSequence()
{
    std::string outputStr = "a";
    int positionRequested = 28;
    std::cout<<"\nEnter the position requested (+ve number only starting from one) : ";
    std::cin>>positionRequested;
    // Decrement as value is calculated as per the index 0;
    --positionRequested;
    int i = 0;
    int n = positionRequested/26;
    int rem = positionRequested%26;
    while ( i < n )
    {
        if (outputStr.size() == 1)
        {
            outputStr.insert(0,1,'a');
        }
        else
        {
            char ch = outputStr[0];
            if ( ch == 'z')
            {
                outputStr[0] = 'a';
                outputStr.insert(0,1,'a');
            }
            else
            {
                ch += 1;
                outputStr[0] = ch;
            }
        }
        i++;
    }
    // add the reminder to the first character of the output string.
    char ch = outputStr[outputStr.size() - 1];
    for ( i = 0; i< rem; i++)
    {
        ++ch;
    }
    outputStr[outputStr.size() - 1] = ch;
    std::cout<<"\nRequested Character is : "<<outputStr.c_str()<<"\n";
}

- Ricky May 18, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Use Trie DS , do a level order traversal till the count which you need, and then return the value for that node.

- umesh May 18, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

Trie can help here.

given value (say n).
n/26=x and n%26=y.
now what U hv to go is to the x level node and yth element. that O(1) complexity

- Prem May 18, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

No need for a trie, way too complicate... think about something close to...

vector<char> letterString;

while(num)
{
letterString.push_back(num%26 + 'a');
num /=26;
}

and then print letterString...

We are counting in base 26 and using letters to represent the values...

- Anonymous May 18, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

I believe this is the answer they were looking for:

int num = 28;
char letter;
string answer;

while(num)
{
      letter = (num-1)%26;
      answer.push_back(letter + 'a');
      num = (num-letter)/26;
}

You then must print in reverse order due to the way it is pushed onto the string...

- rdo May 18, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I made a small change in your program as it wasn't behaving well for numbers greater than 676



int num = 704;

int letter;
String answer="";



while(num != 0)
{
letter = (num)%26;
answer = answer + ((char)(letter+96));
num = (num-letter)/26;
}
StringBuffer buffer = new StringBuffer(answer);
answer = buffer.reverse().toString();
char[] array = answer.toCharArray();
for(int i =0;i<array.length;i++) {
if(i > 0 && i < answer.length()-1) {
int val =(int)array[i] +1;
array[i] = (char)val;
}
}
for(int i =0;i<array.length;i++) {
System.out.print(array[i]);
}

- Sidharth Sharma May 19, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

The "modified" version doesn't work for 675 and 676, while the original version does. And can someone explain why does the original version not work for numbers greater than 676?

- Sunny January 01, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

def getStringAtKth(k):
if k<=26:
return chr(96+k)

q,r = divmod(k,26) #q-> quotient and r-> remainder

if r == 0:
q, r = q-1, 26

retstr = getStringAtKth(q)+chr(96 + r)
return retstr

- Anonymous May 19, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Submitted by me without login......

def getStringAtKth(k):
if k<=26:
return chr(96+k)

q,r = divmod(k,26) #q-> quotient and r-> remainder

if r == 0:
q, r = q-1, 26

retstr = getStringAtKth(q)+chr(96 + r)
return retstr

- virgo676 May 19, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

You din't consider multiple character lenghth. elements can be abu, cyz etc too. So, incorrect

- Vis May 24, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

It is much like a 2D array

[   a    b   c   d    z]
[  aa ab ac ad    az]
[  ba bb bc bd    bz]
[---------------------]
[---------------------]
[  za zb zc zd    zz]

let XY is the string at kth position
X can be generate with k/26(0-null, 1-a, 2-b........26-z )
Y can be generate with k%26(0-a, 1-b, 2-c........25-z )

----Prefer algo rather then code in this forum

- PKT May 19, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

What about the series after zz ?

- Anonymous January 21, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

def find_repr(num):
    s=""
    q,r=num,0
    while True:
       r=q%26
       q=q/26
       if r==0:
          r=26
          q=q-1
       s=chr(r-1+ord('a'))+s
       if q==0: break
    return s

if __name__=='__main__':
   for i in range(703,1000):
      print find_repr(i),
   print

- light May 20, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Base26 {
public static void main(String[] a) {
String alphabet = "zabcdefghijklmnopqrstuvwxy";
String result = new String();
int num = 26*26*26*26;
if(num == 0) {
System.out.print("a");
} else {
while(num > 0) {
int digit = num%26;
result = alphabet.charAt(digit) + result;
if(digit == 0) {
num = (num-1)/26;
} else {
num = num/26;
}
}
System.out.print(result);
}
}
}

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

seems like a 26 radix problem

- NGloom May 21, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>

using namespace std;

int main()
{
	int k = 28;
	int n = 26;

	k--;

	while(k/n > 0)
	{
		k-=n;
		n*=26;
	}
	n/=26;
	while(n>0)
	{
		char c = k/n+'a';
		cout<<c;
		n/=26;
	}
	cout<<endl;
}

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

public static String findStringAt2(int position)
	{
		
		String strToReturn = "";
		int p1 = position;
		
		while( p1 > 26)
		{
			p1 = p1 - 26;
			strToReturn += "A";
		}
		
		return strToReturn + c1[p1-1];
		
	}

- Shrikant June 13, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I not sure of the solution. Do a simple conversion as we do in Decimal to binary with base as 26 instead if 2.

eg: If k is 1408, then

26| 1408
--------
26| 54 - 4
--------
26| 2 - 2
---------

So the solution is 224 and converting it into alphabets gives bbd.

For given eg, k=28 => 12 => ab

Pls correct me

- gokulkrishnasr June 18, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Base 26 seems to be the best way here. But I wanted to know how the number say k=678 would map to the string aab. 678 would be nothing but 102 base 26. So, how can this equates to aab?

- Pavan Dittakavi June 24, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

a to z - 26 and aa to zz - 26*26. So zz will be 702 and 678 is not equal to aab. aab is 704

- gokulkrishnasr June 25, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>

void print_chars(int k);

int main()
{
int k;

printf("\n enter the value of k \n");
scanf("%d",&k);



print_chars(k);


return 0;
}


void print_chars(int k)
{
if(k==0) return;

print_chars(k/26);

printf("%c",(char)('a'+(k%26-1)));
}

- kim June 25, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

convert input number to 1+ 26 + 26^2 +26^3 +.......26^n + k where k<26^n+1

Convert k to base 26.

prepend enough 0s to make sure its length n.

Convert to corresponding characters. 0-->a..... 25 -->z

- ViX July 02, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

It's a base 26 conversion Here is the Java solution:

public static void main(String args[]) {
        int position = 85;
        String result = "";
        while (position > 0) {
            int b = position % 26;
            position = position / 26;
            result = b + result;
        }
        String charResult = "";
        for (int iCount = 0; iCount < result.length(); iCount++) {
            charResult = charResult + (char) (result.charAt(iCount) - 47 + 95);
        }
        System.out.println("String is: " + charResult);
    }

- ms July 13, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Try 675-677...

- Sunny January 01, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

void func(char* res_str, k)
{
	for((k / (26*26)) times)
	{
		append (k/26) to res_str;
	}
	append (k%26) to res_str;
}

- sakshi August 16, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{
#include<stdio.h>
int main()
{
int n=703;

char arr[26]={'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'};

while(n){
printf("%c ",arr[(n)%26]);
n=(n)/26;

}
return 0;
}

}
guys is this as simple as this or am i missing something .... of course the above program prints the required atring in reverse we can avoid that by using recursion or store it in a string to reverse it ...

- sreeram September 28, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

pls give the exact code...its incomplete as it prints string in reverse order

- lol September 28, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public String encode(final int number) {
StringBuilder btr = new StringBuilder();
int quotient = number;
int remainder = 0;
while(quotient != 0) {
remainder = quotient % base;
if(remainder == 0)
remainder = base;
quotient = (quotient - remainder) / base;

char c = (char)('a' + remainder - 1);
btr.append(c);
}
return btr.reverse().toString();
}

- Sonu October 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This question can be reduced to converting a decimal number (base 10) to a base 26 number.
Below is the code for it :

#include <iostream>

using namespace std;

int getLength(int number, int base)
{
    int length = 0;
    while(number > 0 )
    {
                 number /= base;
                 length++;
    }    
    return length;
}

int* convertDecimal(int toBase, int number)
{
     int len = getLength(number,toBase);
     int *base26 = new int[len];
     int remainder;
     for(int i=0; i < len ; i++)
     {
                     base26[i] = number % toBase;
                     number /= toBase;
     }
     return base26;
}

int main()
{
    int number ;
    cout<<"Enter the number : ";
    cin>>number;
    int *base26 = convertDecimal(26,number-1);
    int length = getLength(number-1,26);
    for(int i=length-1; i>=0; i--)
    {
            cout<<"  "<<char(97+base26[i]);
    }
    cout<<"\n\n";
    system("pause");
}

- varun sharma March 27, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/**
	 * 
	 * @param num
	 * @return
	 */
	public static String getExcelHeaderForNum(int num) {
		int prevChar = (num - 1) / 26;
		int thisChar = (num - 1) % 26;

		if (prevChar == 0) {
			return "" + (char) (thisChar + 'A');
		} else {
			return getExcelHeaderForNum(prevChar) + (char) (thisChar + 'A');
		}

	}

}

- shashi January 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

int n;
	cout<<"NUMBER : ";
	cin>>n;
	int repeat=n/27;
	for(int i=0;i<repeat;i++)
		printf("%c",'a'+i);
	int rem=n%27;
	printf("%c",'a'+rem);

- varun July 17, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

What a LOL question

- Loler September 28, 2012 | 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