Faulty Keyboard

You have a faulty keyboard that reverses the text whenever you type the letter ‘i’. You are given a string, and you need to return the final string as it appears on the screen.

Approach:

  1. Initialize an empty string result that represents the current text on the screen.
  2. Iterate through the given string s, character by character.
  3. If the current character is ‘i’, reverse the result string.
  4. Otherwise, append the current character to the result.
  5. Continue until you’ve processed all characters in the input string s.
  6. Return the result as the final answer.
1
2
3
4
5
6
7
8
9
class Solution:
    def finalString(self, s: str) -> str:
        result = ""
        for char in s:
            if char == 'i':
                result = result[::-1] # Reverse the string if 'i' is encountered
            else:
                result += char # Append the character to the result if it's not 'i'
        return result

Insights:

  • The problem provides an interesting twist with the faulty ‘i’ key, leading to an intermediate reversal in the string.
  • The solution leverages simple string manipulation, reversing and appending operations.
  • The time complexity of the solution is O(n^2), where n is the length of the input string. The reversal takes O(n) time, and since we reverse n times in the worst case, the overall complexity is O(n^2).
  • We can optimize the solution by using a stack or deque to achieve O(n) time complexity. But for a beginner’s level understanding, the given approach suffices.