Given the sequence S1 = {a,b,c,d,…,x,y,z,aa,ab,ac…. } and given that this sequence corresponds (term for term) to the sequence S2 = {0,1,2,3,….}. Write code to convert an element of S2 to the corresponding element of S1.
Your challenge, should you accept it, is to code this problem correctly on your first try. Without any help from the computer of course 🙂 You might think you have the idea to solve it but it is tricky to code it correctly.
Hint:
I’ve created the following table for your convenience.
a - 0 aa - 26 ..... za - 676 aaa - 702 b - 1 ab - 27 ..... zb - 677 aab - 703 c - 2 . . . . . . . . . . . . . . . z - 25 az - 51 ..... zz - 701 aaz - 727
From a-z, how many of them are there? How about aa-zz? And aaa-zzz?
Solution:
You should be able to observe that from a-z (a total of 26), from aa-zz (a total of 262), from aaa-zzz (a total of 263), and so on… I will explain why this is important later.
Assume s1 = abc and we need to find its corresponding number, s2. Now imagine that aaa can be magically transformed to 000, aab –> 001, …, and abc to some number xyz. The question is, what should xyz be?
Now this is a trivial question. Why? Remember that our numeral system has 10 as its base. Here, we are merely converting the system from base 26 to base 10. Therefore, xyz = 2*260 + 1*261 + 0*262 = 28.
But wait, we are not finished yet. To find the real value of s2, we need to find how many of them appeared before aaa and add to xyz. Using the important observation earlier, we can easily determine that that there are a total of 26 + 262 = 702 that appeared before aaa. Therefore, s1 corresponds to the number s2 = 28 + 702 = 730.
Assume that we are converting from s2 = n to s1 = “abcde…”.
We can generalize to the following equation (Equation (1)):
Equation (1) n = 26 + 262 + ... + 26k-1 + a0 + a1*26 + a2*262 + ... + ak-1*26k-1 = a0 + (a1 + 1) 26 + (a2 + 1) 262 + ... + (ak-1 + 1) 26k-1 where ai ranges from 0-25 (each representing a letter in s1), k is the number of letters in s1.
To solve the above equation, we have to find the values of a0, a1, …, ak-1. Once we solve this equation, we are able to determine the string of letters of s1 directly.
a0 can be solved by taking n % 26. Why? Because a0 ranges from 0-25, which is not divisible by 26, while the rest are factor of 26. After we obtained the value of a0, we divide n by 26. This will yield the number
n' = (a1 + 1) + (a2 + 1) 26 + ... + (ak-1 + 1) 26k-2
You might think that a1 + 1 = n’ % 26. This is wrong. What happens when a1 = 25? For sure, a1 +1 is divisible by 26, and thus the mentioned equation is invalid. We can easily resolve this by doing a1 = (n’ – 1) % 26.
The rest is easy, we continue further with n” = (n’ – 1) / 26 and a2 = (n” – 1) % 26, up until ak-1.
Clearly, we need to do both modulo 26 and divide by 26 operations a total of k-1 times. But do we really need to know the value of k (or the number of letters in s1)?
The beauty of this method is, since we start from the least significant digit and work our way up, we don’t need to evaluate k. We just need to divide n by 26 repeatedly until it becomes 0.
1 2 3 4 5 6 7 8 9 |
string numToStr(int n) { string str(1, 'a' + n%26); n = n/26; while (n != 0) { str = (char)('a' + (n-1)%26) + str; n = (n-1)/26; } return str; } |
Alternative Solution:
The above solution can be converted to a recursive solution too. The advantage is the recursive solution can print the solution directly without storing the characters into a variable. Check my post: Recursion to the Rescue! where recursion is used to reverse a string.
1 2 3 4 5 6 7 8 9 10 |
void numToStrHelper(int n) { if (n == 0) return; numToStrHelper((n-1)/26); cout << (char)('a'+(n-1)%26); } void numTostr(int n) { numToStrHelper(n/26); cout << (char)('a'+n%26); } |
Further Thoughts:
This question is actually much easier to solve if S2 is changed to:
S2 = {1,2,3,4,….} ie, a->1, b->2, c->3, …, aa->27.
Then transforming from n to a string in S1 is just the same as converting the number from base 10 to base 26. Using this idea as a starting point, you can derive the same Equation (1) above.
Excel Sheet Row Numbers,
Bar raiser? Like you said, convert from base 10 to base 26. Something pretty darn obvious once you get the answer.
I would've expected a bar raiser to be a question more complex that even the answer would require lots of explanation.
a->0
aa->26 Now the first a has weight 1 instead of 0
z->25
as follow the decimal rule, the next should be ba, but we have aa, where if a is zero we get 00
In other words, 10 based numbers 01 is 1, while here aa is not a
Now if we follow the rule: right most letters weight 0-25, while others weight 1-26
so 676 = 26 * 26 should be za = 26*26 + 0;
27*26 corresponding to aaa = 1*26*26 + 1*26 + 0;
Reverse the logic is the answer
No, it's not that straight forward. As mentioned in "Further Thoughts", this question cannot be solved by converting from base 10 to base 26 directly, but it is a good starting point.
I believe my approach is more complicated than necessary though. (ie, tedious math required to outline the idea)
Omg took me 1:30 hour to figure out my first solution. So dead if I’m in an interview!
Can also solve this problem through recursion.
public static void printNum2Chr(int num) {
LinkedList list = convertNum2Chr(num);
while (list.size() > 0) {
System.out.print(list.removeLast());
}
System.out.println();
}
private static LinkedList convertNum2Chr(int num) {
LinkedList retList = new LinkedList();
if (num < 26) {
retList.add(new Character((char)('a' + num)));
return retList;
}
LinkedList tmpList = convertNum2Chr(num – 1);
int n = 1;
while (tmpList.size() > 0) {
char c = tmpList.removeFirst().charValue();
c = (char)(c + n);
if (c < 'z') {
retList.add(c);
n = 0;
} else {
retList.add('a');
n = 1;
}
if (n == 1 && tmpList.size() == 0) {
retList.add('a');
}
}
return retList
}
I believe your solution is not quite right.
For input value 676, the correct answer is to print out the string aza, but your code prints out the string za. The leading "a", which is kind of zero, is omitted.
Dealing with leading "zeros" is an essential part of the problem, and is glossed over by just thinking in terms of base conversions.
Also, fwiw, I find your explanation needlessly tedious and turgid. Why attribute false reasoning to the user, just to shoot it down?
Actually you are wrong, 676 should get YZ if A = 1, in this question A = 0, so 676 = YY. I actually checked this on Google Spreadsheet…
sorry, 676 = ZA it is correct.
this is simple conversion from base 10 to base 26
void convert(unsigned int N)
{
unsigned char a = 'a';
unsigned int Base = 26;
if(N < Base)
{
printf("%c",a+N);
}
else
{
convert(N/Base-1);
printf("%c",a + (N%Base));
}
}
int main()
{
unsigned int x;
for(x= 0; x<= 727; x++)
{
printf("%i ", x);
convert(x);
printf("\n");
}
return 0;
}
No it's not just base 26. I was asked this exact same question at a Google interview recently, and failed to get hired. (BTW, that sequence is _exactly_ the column names of a spreadsheet.) I guess they feel they are hiring too many people these days, and are trying to pick the few that come by that can solve problems current employees cannot even solve themselves. Good luck with that Google
hi,
could u plz explain the solution a bit more clearly? I agree for 676 ur solution is not right.
I m sry. the solution for 676 is za which is correct.
Pingback: Amazon “Bar Raiser” Interview Question | 口├人人│의 Blog
excellent….
Great article. I think I cannot solve it.
It seems that the original problem can be convert to the further-thought problem by plussing 1 to the set S2, and
get solved quickly.
This also looks simple and straight. I just tested it against your code.
http://apps.topcoder.com/forums/;jsessionid=ADD56E9A68661BCD10E86E77A5769569?module=Thread&threadID=758832&start=0&mc=3#1590404
I intended to write:
cout << (char) (n%26 + 'a');
public static String replace(int n){
StringBuffer s= new StringBuffer();
while(n>=0){
s.append((char)(‘a’+n%26));
n=n/26-1;
}
return s.toString();
}
java solution
JAVA Solution to convert number to string in excel sheet
Hi, can anybody please help me understand this. when we consider a=1,b=2…. we can covert the given string directly to an integer. Here we are converting the base to 26. I am clear with that. but what i am confused about is we are not considering cases when the number can contain digit ‘0’. And that leads me to the confusion that why do we need to add 26^1+26^2…+26^k when we consider a=0,b=1,c=2….I will really appreciate your help
сожно ли вылечиться от последней стадии алкоголизма http://globalempirerealestategroup.xyz/index.php?viewurl=2159 как бросить пить в минске
g6687hjhk7
gilgamesh immortality essay one page business plan pdf download free research papers alternative medicine
gate gourmet essay in russia
free resume tools
free resume builder pcman
four basic guidelines to follow in writing a resume
example of thesis about racism
example of culture shock essay
freres scott resume saison 2
free cloning outline for research paper
free essay on children and poverty
good books for english extended essay
gcse english coursework film review sample j2ee resume extraversion personality essay
free essay writer online how to write queries in arcgis free homework passess
free business plan for recruitment agency grounds keeper resume exercise for taking an essay exam
forensic biology dissertation ideas how to write product proposal example of introduction in a book report
essay topics for canterbury tales 24 ready to go genre book reports good attention grabbers compare contrast essay
example of business plan for bookstore legal intern cover letter examples essay writing my future plans
global warming natural or man made coursework pirenne thesis analysis essay writing brainstorming techniques
frederick jackson turner frontier thesis criticism how to write a survey for market research free essay on animal rights
examples of reflective essay catering manager job description resume expressing opinions essay
forest fires persuasive essay modern curriculum vitae and resume for teachers of secondary schools free forms to write a well
free essay on ukraine grade 2 students write a play free resume templates students no experience
essay two and a half men essay format 5 paragraph outline free research papers on foreign nurses
good night and good luck thesis communication computer data homework problem stalling examples stem cell research papers
free personal banker resume templates law school business plan competition free sample medical resume
freud research paper topics sample resume of personal secretary free essay on anorexia nervosa
free business plan softawre introducing a topic in an essay example of methodology chapter of research proposal
free download of resume formats for freshers resume ctc firefox how to resume download with part
free essay aspirin science coursework gcse acid rain free assistance in writing a resume
example cover letter for academic advisor lyrical essay example speech pathology cfy cover letter
fresher latest resume collection sample structure of research paper example resume for young people
formal argumentative essay format cellular respiration vs photosynthesis essay essay topics on world religion
fund74 ruanketa i resume resume design format free university essay
experienced government administrative assistant resume top business plan software free essay spinner
every step essay petra jurt 120 b 448 filmbay mnbt172 e books 2edu html expected salary on resume evolution research paper
free resume template training specialist sample skills in resume for hrm gender differences in the classroom essay
front desk manager resume objective do i need an objective statement in my resume free music downloads essay
example qualitative research proposal research paper tutorials george washington obituary essay
format for writing a critical lens essay how to write amounts on checks example procedure section research paper
essay titles in quotes or italics free sample hvac cover letter free printable bordered paper writing
free printable homework for 1st graders cultural analysis essay exemplary essay examples
free sample of an expository essay best book on business plan free business plan for event management company
free elementary education resume examples voorbeeld business plan word frozen food manager resume
free business plan theme park college essay conclusions examples free argumentative research paper
essay william blake poison tree how to write 400 in roman numerals example of research proposal apa
fundamentals of corporate finance homework answers resume drop off followup evolution of the automobile essay
good animal farm thesis when to write a thank you note after interview free download dissertation reports
freiherr von stackelberg dissertation tinkering toward utopia book report file transfer resume protocol
full life cycle development resume resume layout for microsoft word 2010 free online research essay homework help
examples of core qualifications on resume communication skill on resume essay tests advantages
flight attendant resume sample free free online discursive essay find resume resume html server3 jobthai com
free business plan for small business design phd thesis funny quotes phd thesis
et dukkehus resume sample cover letter for survey interviewer fracture thesis
from current employer confidential resume resume ubu roi alfred jarry gallery experience resume
expository essay ppt objective in resume for internship in engineering eulogies how to write one
free dissertation topics banking finance emergency management specialist resume essay writing the game i like most
essay writing format for high school students singers resume samples free template for compare and contrast essay
freight forwarder sales resume literature review on interest rates free sample of medical assistant cover letter
fiction cover letter short story good resume objective for students in college federalist papers essay 1
free resume development for freshers creativewriting free medical receptionist resume template
golf teaching professional cover letter customer service banking resume sample fantastic cover letter
find job seekers resume proposal writing jobs essay topics for ap us history
examples comparison contrasting essay awareness campaigns of radio thesis free administrative resume
george weymann thesis where to put a thesis statement in an essay form for resume free
example resume stewardess mills thesis on sociological imagination global warming essay full auth3 filmbay yo12i aj html
formatting essay mla why should students do there homework good college essay
golding essay prize how to write specifications for string operations free research paper publications
essay usage mobile block quote in essay example ged essay examples
examples of foreign literature in thesis startup business plan template fsot sample essay questions
general service technician resume http://fiveshots.us/index.php?view-id=4528 example resume public service
example cover letter scientific paper submission http://divazzy.us/index.php?topic=3460 example of cover letter for executive position
expository essay projects http://tagcast.us/index.php?topic=11056 general statement in an essay
essay writing competitions in india http://solucionesdidacticas.xyz/index.php?viewpage=5156 free research papers about buckminster fuller
free acid rain essay http://wikinu.us/index.php?page=8319 events manager cover letter
fortune 500 business plan http://shufflebox.us/index.php?topic=11819 free research papers corporate social responsibility
field test engineer resume http://centicero.us/index.php?link=11715 free resume template for management
final year project dissertation http://teksphere.us/index.php?topic=5723 exemplification essay samples
essay topics for small children http://jumptube.us/index.php?page-id=12808 gcse biology coursework mark scheme
free sample of job application cover letter http://kazushiro.us/index.php?page-id=2934 essay water pollution cause effect
expository research paper definition lesson plans http://skalia.us/index.php?topic=662 glaceau business plan
for and against essay mobile phones http://chatterclub.us/index.php?link=7838 gonzaga application essay prompt
essay writing outline graphic organizer http://dvacher2.us/index.php?topic=14413 freidrich nietzche on morality essay
example of a simple research paper http://twinyx.us/index.php?page=692 example cover letter engineering
extent do children learn language through imitation essay http://taista.xyz/index.php?topic=2451 free resumix resume sample
essaywriting service http://riffbug.us/index.php?viewpage=4962 family of origin term papers
example thesis in computer engineering http://snyderconsult.xyz/index.php?viewpage=2743 financial planning resume objective
free sample handyman resume http://sakumacondom.us/index.php?topic=11582 free resume real estate agent
free essay hospitality industry http://kovrick.us/index.php?page-id=5206 geophysicist resume
essay writing simple guide http://tagsphere.us/index.php?topic=13995 free cover letter information
fashion pr cover letter http://jaxnation.us/index.php?view-id=1873 gcse statistics coursework sample