Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the result variable to zero.
DSA Typescript
function romanToInt(s: string): number {
let result = [1];
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing result with 1 or null causes wrong calculations.
Leaving result undefined leads to errors.
✗ Incorrect
The result variable should start at 0 to accumulate the integer value.
2fill in blank
mediumComplete the code to get the integer value of a Roman numeral character from the map.
DSA Typescript
const romanMap: { [key: string]: number } = {I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000};
function romanToInt(s: string): number {
let result = 0;
for (let i = 0; i < s.length; i++) {
let current = romanMap[[1]];
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using i instead of s[i] causes wrong key lookup.
Using romanMap[i] is incorrect because i is a number index.
✗ Incorrect
We use s[i] to get the current Roman numeral character at index i.
3fill in blank
hardFix the error in the condition to check if the current Roman numeral is less than the next one.
DSA Typescript
for (let i = 0; i < s.length - 1; i++) { let current = romanMap[s[i]]; let next = romanMap[s[i + 1]]; if (current [1] next) { result -= current; } else { result += current; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' reverses the logic and causes wrong results.
Using '==' or '>=' does not handle subtraction correctly.
✗ Incorrect
If current is less than next, we subtract current from result.
4fill in blank
hardFill both blanks to add the last Roman numeral value after the loop and return the result.
DSA Typescript
for (let i = 0; i < s.length - 1; i++) { let current = romanMap[s[i]]; let next = romanMap[s[i + 1]]; if (current < next) { result -= current; } else { result += current; } } result [1] romanMap[s[s.length [2] 1]]; return result;
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-=' subtracts the last value incorrectly.
Using '+' instead of '- 1' causes index out of range.
✗ Incorrect
We add the value of the last Roman numeral to result using '+=' and access it with s.length - 1.
5fill in blank
hardFill all three blanks to complete the function that converts a Roman numeral string to an integer.
DSA Typescript
function romanToInt(s: string): number {
const romanMap: { [key: string]: number } = {I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000};
let result = [1];
for (let i = 0; i < s.length - 1; i++) {
let current = romanMap[s[i]];
let next = romanMap[s[i + 1]];
if (current [2] next) {
result -= current;
} else {
result += current;
}
}
result [3] romanMap[s[s.length - 1]];
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Starting result at 1 causes off-by-one errors.
Using '>' instead of '<' reverses subtraction logic.
Forgetting to add the last numeral causes wrong totals.
✗ Incorrect
Initialize result to 0, subtract when current < next, and add the last value with '+='.
