Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the result variable to zero.
DSA Javascript
function romanToInt(s) {
let result = [1];
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing result with 1 or null causes incorrect calculations.
Leaving result undefined leads to errors when adding values.
✗ Incorrect
The result variable should start at 0 to accumulate the integer value.
2fill in blank
mediumComplete the code to get the integer value for the Roman numeral 'I' from the map.
DSA Javascript
const romanMap = {I: 1, V: 5, X: 10};
function romanToInt(s) {
let result = 0;
for (let i = 0; i < s.length; i++) {
let value = romanMap[[1]];
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using i directly instead of s[i] causes undefined values.
Using romanMap[i] is incorrect because i is an index, not a Roman numeral.
✗ Incorrect
We use s[i] to get the current Roman numeral character from the string.
3fill in blank
hardFix the error in the if condition to check if the current Roman numeral value is less than the next one.
DSA Javascript
const romanMap = {I: 1, V: 5, X: 10};
function romanToInt(s) {
let result = 0;
for (let i = 0; i < s.length; i++) {
let current = romanMap[s[i]];
let next = romanMap[s[i + 1]];
if (current [1] next) {
result -= current;
} else {
result += current;
}
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' reverses the logic and causes wrong results.
Using '===' or '!==' does not compare sizes and breaks the logic.
✗ Incorrect
If the current value is less than the next, we subtract it according to Roman numeral rules.
4fill in blank
hardFill both blanks to correctly handle the loop and avoid accessing undefined next character.
DSA Javascript
const romanMap = {I: 1, V: 5, X: 10};
function romanToInt(s) {
let result = 0;
for (let i = 0; i [1] s.length [2] 1; i++) {
let current = romanMap[s[i]];
let next = romanMap[s[i + 1]];
if (current < next) {
result -= current;
} else {
result += current;
}
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' causes out of bounds error when accessing s[i + 1].
Using '+' instead of '-' causes incorrect loop range.
✗ Incorrect
The loop runs while i is less than s.length minus 1 to safely access s[i + 1].
5fill in blank
hardFill the blank to add the last Roman numeral value after the loop ends.
DSA Javascript
const romanMap = {I: 1, V: 5, X: 10};
function romanToInt(s) {
let result = 0;
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 += romanMap[[1]];
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using s[s.length] causes undefined access.
Using s[length - 1] is incorrect because length is not a variable.
✗ Incorrect
Add the value of the last character in the string using s[s.length - 1].
