Bird
Raised Fist0
DSA Typescriptprogramming

Roman to Integer Conversion in DSA Typescript

Choose your learning style10 modes available
Mental Model
Roman numerals are letters that represent numbers. We add values normally, but if a smaller value comes before a bigger one, we subtract it instead.
Analogy: Imagine reading a price tag where sometimes a smaller coin before a bigger coin means you owe less, like a discount, so you subtract that smaller coin's value.
R O M A N  N U M E R A L S
I=1, V=5, X=10, L=50, C=100, D=500, M=1000
Example: M -> C -> M -> X -> I -> V
Values: 1000 -> 100 -> 1000 -> 10 -> 1 -> 5
Dry Run Walkthrough
Input: Roman numeral: MCMXCIV
Goal: Convert the Roman numeral MCMXCIV to its integer value
Step 1: Read 'M' (1000), add 1000 to total
Total = 1000
Why: Start with first symbol value
Step 2: Read 'C' (100), next is 'M' (1000), since 100 < 1000, subtract 100
Total = 1000 - 100 = 900
Why: Smaller before bigger means subtract
Step 3: Read 'M' (1000), next is 'X' (10), since 1000 > 10, add 1000
Total = 900 + 1000 = 1900
Why: Bigger or equal after smaller means add
Step 4: Read 'X' (10), next is 'C' (100), since 10 < 100, subtract 10
Total = 1900 - 10 = 1890
Why: Smaller before bigger means subtract
Step 5: Read 'C' (100), next is 'I' (1), since 100 > 1, add 100
Total = 1890 + 100 = 1990
Why: Bigger or equal after smaller means add
Step 6: Read 'I' (1), next is 'V' (5), since 1 < 5, subtract 1
Total = 1990 - 1 = 1989
Why: Smaller before bigger means subtract
Step 7: Read 'V' (5), no next symbol, add 5
Total = 1989 + 5 = 1994
Why: Last symbol always adds
Result:
Total = 1994
Annotated Code
DSA Typescript
class RomanToInteger {
  private romanMap: Record<string, number> = {
    I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000
  };

  convert(roman: string): number {
    let total = 0;
    for (let i = 0; i < roman.length; i++) {
      const currentVal = this.romanMap[roman[i]];
      const nextVal = i + 1 < roman.length ? this.romanMap[roman[i + 1]] : 0;

      if (currentVal < nextVal) {
        total -= currentVal; // subtract when smaller before bigger
      } else {
        total += currentVal; // add otherwise
      }
    }
    return total;
  }
}

const converter = new RomanToInteger();
const input = "MCMXCIV";
const result = converter.convert(input);
console.log(result);
const currentVal = this.romanMap[roman[i]];
Get value of current Roman symbol
const nextVal = i + 1 < roman.length ? this.romanMap[roman[i + 1]] : 0;
Get value of next Roman symbol or 0 if none
if (currentVal < nextVal) { total -= currentVal; } else { total += currentVal; }
Subtract if smaller before bigger, else add
OutputSuccess
1994
Complexity Analysis
Time: O(n) because we scan the Roman numeral string once
Space: O(1) because the map size is fixed and no extra space grows with input
vs Alternative: Compared to parsing each symbol multiple times or using recursion, this linear scan is simpler and faster
Edge Cases
Empty string
Returns 0 because no symbols to convert
DSA Typescript
for (let i = 0; i < roman.length; i++) {
Single symbol like 'V'
Returns the value of that symbol (5)
DSA Typescript
const nextVal = i + 1 < roman.length ? this.romanMap[roman[i + 1]] : 0;
Symbols in descending order like 'VIII'
Adds all values normally (5 + 1 + 1 + 1 = 8)
DSA Typescript
if (currentVal < nextVal) { total -= currentVal; } else { total += currentVal; }
When to Use This Pattern
When you see a problem asking to convert Roman numerals to numbers, use the subtract-if-smaller-before-bigger pattern to handle special cases efficiently.
Common Mistakes
Mistake: Always adding values without checking the next symbol leads to wrong totals for cases like 'IV' or 'IX'.
Fix: Check if current symbol is smaller than next and subtract in that case.
Summary
Converts Roman numeral strings to their integer values by adding or subtracting symbol values.
Use when you need to interpret Roman numerals as numbers in code.
Remember to subtract when a smaller value comes before a bigger one, otherwise add.

Practice

(1/5)
1. What is the main rule to convert Roman numerals to integers?
easy
A. Add values of symbols, subtract if a smaller symbol is before a larger one
B. Multiply all symbol values together
C. Add values only if symbols are the same
D. Subtract all symbol values from 1000

Solution

  1. Step 1: Understand Roman numeral rules

    Roman numerals are converted by adding values of symbols, but if a smaller value comes before a larger one, it is subtracted.
  2. Step 2: Apply the rule to conversion

    For example, IV is 5 - 1 = 4, not 1 + 5 = 6.
  3. Final Answer:

    Add values of symbols, subtract if a smaller symbol is before a larger one -> Option A
  4. Quick Check:

    Roman to integer = add/subtract values [OK]
Hint: Subtract when smaller symbol precedes larger one [OK]
Common Mistakes:
  • Always adding values without subtraction
  • Multiplying symbol values
  • Ignoring order of symbols
2. Which TypeScript syntax correctly defines a function to convert Roman numerals to integers?
easy
A. def romanToInt(s): return 0
B. function romanToInt(s: string): number { return 0; }
C. func romanToInt(s string) int { return 0 }
D. romanToInt = (s) => { return '0'; }

Solution

  1. Step 1: Identify TypeScript function syntax

    TypeScript functions use the syntax: function name(params): returnType { body }
  2. Step 2: Match correct syntax

    function romanToInt(s: string): number { return 0; } matches TypeScript syntax with parameter type and return type specified.
  3. Final Answer:

    function romanToInt(s: string): number { return 0; } -> Option B
  4. Quick Check:

    TypeScript function syntax = function romanToInt(s: string): number { return 0; } [OK]
Hint: Use 'function name(params: type): returnType' in TypeScript [OK]
Common Mistakes:
  • Using Python or Go syntax in TypeScript
  • Returning string instead of number
  • Missing type annotations
3. What is the output of this TypeScript code?
function romanToInt(s: string): number {
  const map: {[key: string]: number} = {I:1, V:5, X:10, L:50, C:100, D:500, M:1000};
  let total = 0;
  for(let i = 0; i < s.length; i++) {
    const current = map[s[i]];
    const next = map[s[i+1]] || 0;
    if(current < next) total -= current;
    else total += current;
  }
  return total;
}
console.log(romanToInt('IX'));
medium
A. 11
B. 4
C. 9
D. Error

Solution

  1. Step 1: Trace the loop for 'IX'

    For 'I' (1) and next 'X' (10), since 1 < 10, subtract 1. For 'X' (10), no next, add 10.
  2. Step 2: Calculate total

    Total = -1 + 10 = 9.
  3. Final Answer:

    9 -> Option C
  4. Quick Check:

    'IX' = 9 [OK]
Hint: Subtract if current < next, else add [OK]
Common Mistakes:
  • Adding all values without subtraction
  • Off-by-one error in loop
  • Not handling last character correctly
4. Find the bug in this TypeScript code for Roman to Integer conversion:
function romanToInt(s: string): number {
  const map = {I:1, V:5, X:10, L:50, C:100, D:500, M:1000};
  let total = 0;
  for(let i = 0; i <= s.length; i++) {
    const current = map[s[i]];
    const next = map[s[i+1]] || 0;
    if(current < next) total -= current;
    else total += current;
  }
  return total;
}
medium
A. Return type should be string, not number
B. map object keys should be lowercase
C. Use 'var' instead of 'let' for i
D. Loop condition should be i < s.length, not i <= s.length

Solution

  1. Step 1: Check loop boundary

    The loop runs from i = 0 to i <= s.length, which causes s[i] to be undefined at last iteration.
  2. Step 2: Correct loop condition

    Change to i < s.length to avoid accessing undefined index.
  3. Final Answer:

    Loop condition should be i < s.length, not i <= s.length -> Option D
  4. Quick Check:

    Loop boundary off-by-one error fixed [OK]
Hint: Use i < length to avoid out-of-bounds access [OK]
Common Mistakes:
  • Using <= instead of < in loops
  • Wrong case for map keys
  • Incorrect return type
5. Given the Roman numeral string 'MCMXCIV', what integer does the following TypeScript function return?
function romanToInt(s: string): number {
  const map: {[key: string]: number} = {I:1, V:5, X:10, L:50, C:100, D:500, M:1000};
  let total = 0;
  for(let i = 0; i < s.length; i++) {
    const current = map[s[i]];
    const next = map[s[i+1]] || 0;
    if(current < next) total -= current;
    else total += current;
  }
  return total;
}
console.log(romanToInt('MCMXCIV'));
hard
A. 1994
B. 1904
C. 2004
D. 1494

Solution

  1. Step 1: Break down 'MCMXCIV'

    M=1000, C=100, M=1000, X=10, C=100, I=1, V=5. Apply subtraction where smaller precedes larger.
  2. Step 2: Calculate total step-by-step

    1000 (M) + (100 < 1000, subtract 100) + 1000 + (10 < 100, subtract 10) + 100 + (1 < 5, subtract 1) + 5 = 1000 - 100 + 1000 - 10 + 100 - 1 + 5 = 1994.
  3. Final Answer:

    1994 -> Option A
  4. Quick Check:

    'MCMXCIV' = 1994 [OK]
Hint: Subtract smaller before larger, else add [OK]
Common Mistakes:
  • Adding all values without subtraction
  • Misreading symbol order
  • Skipping last character
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard