Faulty Keyboard — LeetCode 2810 Python Solution
- Problem
- #2810
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(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.