Problem Statement
In Santa's workshop, a naughty elf has been playing around in the gift manufacturing chain, adding or removing an unplanned step.
You have the original sequence of steps in the manufacturing process original and the modified sequence modified that may include an extra step or miss a step.
Your task is to write a function that identifies and returns the first extra step that has been added or removed in the manufacturing chain. If there is no difference between the sequences, return an empty string.
const original = 'abcd'
const modified = 'abcde'
findNaughtyStep(original, modified) // 'e'
const original = 'stepfor'
const modified = 'stepor'
findNaughtyStep(original, modified) // 'f'
const original = 'abcde'
const modified = 'abcde'
findNaughtyStep(original, modified) // ''
Considerations:
- There will always be one step of difference or none.
- The modification can occur anywhere in the chain.
- The original sequence can be empty.
My Solution
function findNaughtyStep(original, modified) {
if(original === modified){
return ''
}
let differentElementIndex = 0;
for(let i = 0; original[i] === modified[i]; i++){
differentElementIndex = i + 1;
}
return original.length > modified.length ? original[differentElementIndex] : modified[differentElementIndex];
}
- Declare a conditional statement that returns an empty string if the original string is equal to the modified string.
- Initialize a variable
differentElementIndex
to 0, which will store the index where the elements at the same position in both strings are different. - Create a for loop that increments a variable
i
whileoriginal[i] === modified[i]
are equal. When they are not equal, assign the value of the current index + 1 todifferentElementIndex
. - Finally, check if the string named
original
is longer than themodified
string. If true, extract the element at thedifferentElementIndex
obtained previously. Otherwise, ifmodified
is longer, extract the element from themodified
string.
Code Challenge 3
Top comments (0)