Faulty Keyboard — LeetCode 2810 Python Solution

EasyStringSimulation
Problem
#2810
Pattern
Hash Map
Reading time
2 min

The 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.

Example

Input
s = "string"
Output
"rtsng"
Explanation
After typing first character, the text on the screen is "s".

Python solution

Python
class Solution:
    def finalString(self, s: str) -> str:
        t = []
        for c in s:
            if c == "i":
                t = t[::-1]
            else:
                t.append(c)
        return "".join(t)

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n), where n is the length of string s auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2810. Faulty Keyboard is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2810. Faulty Keyboard?
LeetCode 2810. Faulty Keyboard is rated Easy on LeetCode.
What is the time complexity of LeetCode 2810. Faulty Keyboard?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 2810. Faulty Keyboard?
The Python solution on this page uses O(n), where n is the length of string s auxiliary space.
What topics does LeetCode 2810. Faulty Keyboard cover?
LeetCode 2810. Faulty Keyboard is tagged String and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview