-1

This appears to be simple but I've been researching technical interview questions and there is one in particular on Glassdoor that I've yet to find a solution for. It's a loop that increments a character by one, but after Z, it converts to AA so it essentially becomes a string or concatenated characters. Similar to how scrolling right in Excel causes the alphabetical column names to contain more characters.

Essentially, it asks to build a string incrementer so that A + 1 = B... Z + 1 = AA, AA + 1 = AB... ZZ + 1 = AAA... and so forth.

While I understand that the characters increment by 1 because of the unicode behind the character, how can one make a loop that implicitly creates another character to add another letter AND increase it by one without making the original letter increase until the final character in the string reaches Z? An example being AZ going back to BA or BBZ going to BCA.

I feel like this could get limited because one would have to create a for loop and add a new array item for each new character they want to add after the loop reaches the condition (char < 'Z' again?)

Pseudocode would be appreciated but it can be explained in a particular language if preferred.

2 Answers2

0

One solution is to consider the final string as a number to base x, where x is the number of available characters. In the German alphabet, e.g. x = 26, since the alphabet is
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
(without special characters).

Then, the problem reduces to incrementing a number i, and then converting i to a base x representation.
Normally, x = 10, and the base 10 representation of i = 123 is „123“, because 123/10^2 = 1, (123-1*10^2)/10^1 = 2, and (123-1*10^2-2*10^1)/10^0 = 3.
But in base 26 i it is „4T“, because 123/26^1 = 4 (represented by „4“), and (123-4*26)/26^0 = 19 (represented by „T“).

Dharman
  • 30,962
  • 25
  • 85
  • 135
Reinhard Männer
  • 14,022
  • 5
  • 54
  • 116
0

Duplicate of this post.

It's a tricky question and I was slightly stumped on it too. Here's the solution in Ruby:

def num_to_excel_col(n)
  raise 'Number must be positive' if n < 1
  result = ''
  while true
    if n > 26
      n, r = (n - 1).divmod(26)
      result = (r + 'A'.ord).chr + result
    else
      return (n + 'A'.ord - 1).chr + result
    end
  end
end

# You can substitute 1024 by any positive integer and
# you'll keep getting more results.
(1..1024).each do |i|
  puts num_to_excel_col(i)
end
DaniG2k
  • 4,772
  • 36
  • 77