Spread Sheet Decode

excerpt: This covers the building block alphabet ascii value. tags: ascii-code reverse-modulo

Given a spreadsheet column string like AA, AZ etc, decode it into its numeric value.

Example:

AA => 27
Z => 26

Use the reverse of modulo operation to decode the string back to integer.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def spreadsheet_decoding(s)
  value = 0

  s.each_char do |c|
    value = value * 26 + c.ord - 'A'.ord + 1
  end
  
  value
end

p spreadsheet_decoding('Z')

Time complexity is O(N) and space complexity is O(1).

Building Blocks

  • Alphabet ASCII Code
  • Reverse Modulo