LeetCode Problem - Link


Problem

Your laptop keyboard is faulty, and whenever you type a character 'i' on it, it reverses the string that you have written. Typing other characters works as expected.

You are given a 0-indexed string s, and you type each character of s using your faulty keyboard.

Return the final string that will be present on your laptop screen.

 

Example 1:

Input: s = "string"
Output: "rtsng"
Explanation: 
After typing first character, the text on the screen is "s".
After the second character, the text is "st". 
After the third character, the text is "str".
Since the fourth character is an 'i', the text gets reversed and becomes "rts".
After the fifth character, the text is "rtsn". 
After the sixth character, the text is "rtsng". 
Therefore, we return "rtsng".


Sequential Approach

Somehow I had the same solution as the fastest code in LeetCode, but still, it's 50% slower than other solutions. I wonder why

/**
 * @param {string} s
 * @return {string}
 */
var finalString = function (s) {
    var accumulatedString = ""
    for (var i = 0; i < s.length; i++) {
        if (s[i] == "i") {
            accumulatedString = reverseString(accumulatedString)
        } else {
            accumulatedString += s[i]
        }
    }
    return accumulatedString
};


var reverseString = (s) => {
    return s.split("").reverse().join("")
}