Juneiker

Posted on

Challenge 3 adventjs midudev - The Naughty Elf

Juneiker Castillo

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];

}
``````
1. Declare a conditional statement that returns an empty string if the original string is equal to the modified string.
2. Initialize a variable `differentElementIndex` to 0, which will store the index where the elements at the same position in both strings are different.
3. Create a for loop that increments a variable `i` while `original[i] === modified[i]` are equal. When they are not equal, assign the value of the current index + 1 to `differentElementIndex`.
4. Finally, check if the string named `original` is longer than the `modified` string. If true, extract the element at the `differentElementIndex` obtained previously. Otherwise, if `modified` is longer, extract the element from the `modified` string.

Code Challenge 3