Problem: Leet Code 171- Excel Sheet Column Number

QUESTION:

Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.

For example:

A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28 
...

Example 1:

Input: columnTitle = "A"
Output: 1

Example 2:

Input: columnTitle = "AB"
Output: 28

Example 3:

Input: columnTitle = "ZY"
Output: 701

💭Analyzing question:

  1. In Excel sheet, in working area, we observe the uppercase letters in Top of every column, they are alphabetical representation of the numeric value of columns.

  2. In this question, we are given that string input, we must return that numeric count of that particular column header.


💡Approach:

  • We get String as input, as input might be single character or more than one character.

  • We know that there are 26 characters in Alphabet, so after Z (26), we get AA (27).

  • So first based on the length of string, we must get each character, and subtract it with ‘A’, and add 1 to it, and store in a variable named value, as counting column starts from 1 in case of numerical counting.

  • Then we declare a variable called result in which we multiply result with 26 and then add value to it.

  • This will give us the numerical representation of entered column title in string.


  • 💻My Java Code:

    My Optimal Approach

class Solution {
    public int titleToNumber(String columnTitle) {
        int result = 0;
        for(int i=0;i<columnTitle.length();i++){
            int val = columnTitle.charAt(i)-'A'+1;
            result = result * 26 + val;
        }
        return result;
    }
}

🖥️Output:


⏱️Efficiency of my Approach:

  • Time Complexity: O(n) → n = length of the string

  • Space Complexity: O(1)


🧠My Learnings:

  1. Mathematical operations like +, -, * are used to get desired numerical notation from Alphabetic Representation

  2. Doing index-based access to get each character to perform necessary mathematical operation, as although the logic is simple, but really faced lot of understanding issues!!


Tags:

#Java #Leetcode #ProblemSolving #DSA

0
Subscribe to my newsletter

Read articles from ARCHANA GURUSAMY directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ARCHANA GURUSAMY
ARCHANA GURUSAMY

👩‍💻 I'm Archana Gurusamy, a passionate 3rd-year B.Tech IT student on a mission to grow as a developer.I'm currently deep-diving into Data Structures & Algorithms using Java, while also exploring web development and real-world projects. I love solving coding challenges, building meaningful applications, and documenting my learning journey through technical blogs. I believe in learning in public — sharing my logic, code, and even my rough ideas as I grow. I'm actively working on building a strong IT profile while preparing for real world challenges.