Imagine you are working with Excel and want to convert a column label like 'AB' into its corresponding column number to automate spreadsheet processing.
Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.
Input: A string columnTitle consisting of uppercase English letters only.
Output: An integer representing the column number.
1 ≤ length of columnTitle ≤ 7columnTitle consists only of uppercase English letters (A-Z)
Edge cases: Single letter 'Z' → 26Longest input 'ZZZZZZZ' → large number within integer rangeInput with all 'A's → minimum values for length
def titleToNumber(columnTitle: str) -> int:
# Write your solution here
pass
class Solution {
public int titleToNumber(String columnTitle) {
// Write your solution here
return 0;
}
}
#include <string>
using namespace std;
int titleToNumber(string columnTitle) {
// Write your solution here
return 0;
}
function titleToNumber(columnTitle) {
// Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: 0Using zero-based indexing for letters (e.g., 'A' -> 0) without adding 1.✅ Change letter value calculation to 'ord(ch) - ord('A') + 1'.
Wrong: 27Summing letter values instead of positional base-26 accumulation.✅ Accumulate result as 'result = result * 26 + letter_value' for each character.
Wrong: 52Off-by-one error in letter value for 'B' (mapping 'B' to 1 instead of 2).✅ Use 'ord(ch) - ord('A') + 1' to get correct letter values.
Wrong: 3Summing letter values without positional weighting for multi-letter inputs.✅ Multiply accumulated result by 26 before adding current letter value.
Wrong: TLEUsing recursive or exponential time approach instead of iterative O(n).✅ Implement iterative solution with O(n) time complexity.
✓
Test Cases
Focus on boundary inputs like single letters and maximum length strings.
Test your code against tricky positional calculations and off-by-one errors.
Ensure your solution is efficient and runs in linear time.
t1_01basic
Input"A"
Expected1
⏱ Performance - must finish in 2000ms
A corresponds to 1 in base-26 encoding.
💡 Think of the column title as a base-26 number where A=1, B=2, ..., Z=26.
💡 Use the formula: result = result * 26 + (value of current letter).
💡 For 'A', result = 0 * 26 + 1 = 1.
Why it failed: Incorrect output means you likely did not convert letters to 1-based values correctly. Fix by using 'ord(ch) - ord('A') + 1' for each character.
✓ Correctly converts single-letter column titles.
t1_02basic
Input"AB"
Expected28
⏱ Performance - must finish in 2000ms
AB corresponds to 1*26 + 2 = 28 in base-26 encoding.
💡 Process letters from left to right, multiplying accumulated result by 26 before adding current letter value.
💡 Check that 'A' maps to 1 and 'B' maps to 2, then combine as 26*1 + 2.
💡 Result for 'AB' is 26 + 2 = 28.
Why it failed: If output is wrong, you likely treated letters as zero-based or reversed order. Fix by using 1-based letter values and left-to-right accumulation.
✓ Correctly handles multi-letter column titles.
t2_01edge
Input"Z"
Expected26
⏱ Performance - must finish in 2000ms
Single letter 'Z' corresponds to 26.
💡 Verify that 'Z' maps to 26, not 25 or 0.
💡 Check your letter-to-number conversion formula carefully.
💡 Use 'ord(ch) - ord('A') + 1' to get 26 for 'Z'.
Why it failed: Output less than 26 means zero-based indexing bug. Fix by adding +1 to letter value calculation.
✓ Correctly converts 'Z' to 26.
t2_02edge
Input"AAAAAAA"
Expected1
⏱ Performance - must finish in 2000ms
All 'A's corresponds to minimum value 1 regardless of length.
💡 Check that repeated 'A's do not multiply the result incorrectly.
💡 Remember each 'A' adds 1 after multiplying by 26.
💡 Calculate as ((((((1)*26 + 1)*26 + 1)*26 + 1)*26 + 1)*26 + 1)*26 + 1 = 1 for all 'A's.
Why it failed: If output is greater than 1, you likely summed letter values instead of positional base-26 calculation. Fix by accumulating result as result*26 + letter_value.
✓ Correctly handles repeated 'A's as minimum value.
💡 Check that the first letter contributes 26 times its value.
💡 Verify that the second letter adds its value without multiplication.
💡 Use formula: result = result * 26 + letter_value for each letter.
Why it failed: If output is 27, you likely summed letter values instead of positional base-26. Fix by accumulating with multiplication by 26 before adding letter value.
✓ Correctly handles mixed letters with positional weights.
t3_02corner
Input"BA"
Expected53
⏱ Performance - must finish in 2000ms
'BA' = 2*26 + 1 = 53, tests off-by-one errors in letter values.
💡 Ensure 'B' maps to 2, not 1 or 3.
💡 Check that accumulation order is left to right.
💡 Use 'ord(ch) - ord('A') + 1' for letter values.
Why it failed: Output 52 means off-by-one error in letter value for 'B'. Fix by adding +1 after subtracting 'A' ASCII.
✓ Correctly converts letters with proper 1-based indexing.
💡 Calculate powers of 26 for each position correctly.
💡 Accumulate result as result*26 + letter_value for each letter.
💡 Avoid summing letter values without positional weighting.
Why it failed: Output 3 means summing letter values only. Fix by multiplying accumulated result by 26 before adding letter value.
✓ Correctly computes multi-letter titles with positional weights.
t4_01performance
Input"ZZZZZZZ"
Expectednull
⏱ Performance - must finish in 2000ms
Input length n=7, O(n) time complexity must complete within 2 seconds.
💡 The algorithm should run in linear time relative to input length.
💡 Avoid recursive or exponential approaches that cause TLE.
💡 Use iterative accumulation with constant space.
Why it failed: TLE indicates use of inefficient exponential or recursive approach. Fix by implementing iterative O(n) solution.
✓ Algorithm runs in O(n) time and passes performance test.
Practice
(1/5)
1. You need to convert a string representing a numeral system where symbols can either add or subtract values based on their order (e.g., a smaller value before a larger one means subtraction). Which approach best guarantees an optimal and efficient solution for this problem?
easy
A. Single pass iteration comparing current and next symbol values to decide addition or subtraction
B. Greedy approach that always adds the largest symbol value first
C. Dynamic Programming with memoization to handle all possible substrings
D. Backtracking all possible symbol combinations to find the maximum integer value
Solution
Step 1: Understand the problem pattern of subtractive notation
The problem requires interpreting symbols where a smaller value before a larger one means subtraction, which can be handled by comparing adjacent symbols.
Step 2: Identify the optimal approach using single pass iteration
A single pass comparing current and next symbol values allows deciding whether to add or subtract efficiently without extra space or complex recursion.
Final Answer:
Option A -> Option A
Quick Check:
Single pass with value comparison is optimal and commonly used [OK]
Hint: Compare adjacent symbols to decide add or subtract [OK]
Common Mistakes:
Thinking DP is needed
Using greedy largest-first incorrectly
Trying backtracking unnecessarily
2. What is the time complexity of answering a single query using the precomputed lookup table approach for the angle between clock hands, assuming the table is already built?
medium
A. O(1) because the angle is retrieved directly from a precomputed 12x60 table.
B. O(12*60) because you must compute all angles each query.
C. O(60) because you must scan all minutes to find the angle.
D. O(log(720)) because binary search is used on the precomputed angles.
Solution
Step 1: Understand precomputation
The table stores angles for all 12 hours and 60 minutes, total 720 entries, computed once.
Step 2: Query time complexity
Each query accesses the table by hour and minute indices directly, which is constant time O(1).
Final Answer:
Option A -> Option A
Quick Check:
Lookup table access is direct indexing -> O(1) [OK]
Hint: Precomputation shifts cost to setup, queries are O(1) [OK]
Common Mistakes:
Confusing precomputation cost with query cost
Assuming linear scan or binary search needed per query
3. Examine the following buggy Python code intended to compute the LCM safely without overflow:
def gcd_iterative(a, b):
while b != 0:
a, b = b, a % b
return a
def lcm_safe(a, b):
gcd = gcd_iterative(a, b)
return a * b // gcd
if __name__ == '__main__':
a, b = 1000000, 1000000
print("LCM =", lcm_safe(a, b))
What is the subtle bug in this code?
medium
A. Line 7: Multiplying a and b before dividing by gcd can cause integer overflow.
B. Line 3: The Euclidean algorithm lacks a base case for recursion.
C. Line 9: The input values are not validated for being positive integers.
D. Line 2: The while loop condition should be 'while a != 0' instead of 'while b != 0'.
Solution
Step 1: Analyze lcm_safe function
The function computes LCM as a * b // gcd. Multiplying a and b first can overflow for large inputs before division.
Step 2: Identify the bug
To avoid overflow, division by gcd should happen before multiplication: (a // gcd) * b.
Final Answer:
Option A -> Option A
Quick Check:
Multiplying large numbers before division risks overflow [OK]
Hint: Divide before multiply to avoid overflow in LCM calculation [OK]
Common Mistakes:
Ignoring overflow risk in LCM calculation
Misunderstanding Euclidean algorithm base case
4. Consider the following buggy code for Roman to Integer conversion. Which line contains the subtle bug that causes incorrect results for inputs like "IV" or "IX"?
medium
A. Line with 'result += curr'
B. Line with 'next_val = value(s[i + 1]) if i + 1 < len(s) else 0'
C. Line with 'curr = value(s[i])'
D. Line with 'if curr <= next_val:'
Solution
Step 1: Identify the condition for subtraction
The correct condition is to subtract only when current value is strictly less than next value, not when equal.
Step 2: Analyze the buggy condition
The code uses 'if curr <= next_val:', which incorrectly subtracts when values are equal, causing wrong results for cases like 'IV' or 'IX'.
Final Answer:
Option D -> Option D
Quick Check:
Changing '<=' to '<' fixes the bug [OK]
Hint: Subtraction only if current < next, not <= [OK]
Common Mistakes:
Using <= instead of <
Forgetting boundary checks
Wrong value mappings
5. Suppose the Roman numeral system is extended to allow repeated symbols beyond the usual limits (e.g., "IIII" for 4 instead of "IV"). Which modification to the optimal single-pass algorithm is necessary to correctly convert such inputs?
hard
A. No modification needed; the existing algorithm handles repeated symbols correctly
B. Use a stack to track symbol sequences and apply custom rules for repeats
C. Add a preprocessing step to convert repeated symbols into subtractive pairs
D. Remove the subtraction logic and always add symbol values
Solution
Step 1: Understand the new input format with extended repeats
Allowing repeated symbols beyond standard subtractive notation breaks assumptions of the original algorithm.
Step 2: Identify necessary algorithm change using a stack
A stack-based approach can track sequences and apply custom rules for repeats and subtractive pairs, handling extended notation correctly.
Step 3: Why other options fail
Always adding values ignores subtraction; preprocessing is complex and inefficient; no modification ignores new rules.
Final Answer:
Option B -> Option B
Quick Check:
Stack enables flexible parsing of non-standard repeats [OK]
Hint: Extended repeats require tracking sequences, not just pairwise comparison [OK]
Common Mistakes:
Assuming old logic suffices
Removing subtraction entirely
Trying inefficient preprocessing
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.