Faulty Keyboard - Problem

Imagine you're working on an old laptop with a quirky keyboard bug - every time you press the letter 'i', instead of just typing it, the keyboard reverses your entire string that you've written so far!

You're given a string s representing the sequence of characters you want to type. Your task is to simulate this faulty keyboard behavior and determine what the final string will look like on your screen.

The Rules:

  • When you type any character other than 'i' → it gets appended normally
  • When you type the character 'i' → the entire current string gets reversed

Goal: Return the final string that appears on your laptop screen after typing all characters in s.

Example: If you type "string", you get: sststrrts (reverse after 'i') → rtsnrtsng → final result: "rtsng"

Input & Output

example_1.py — Basic Case
$ Input: s = "string"
Output: "rtsng"
💡 Note: Step by step: '' → 's' → 'st' → 'str' → (reverse on 'i') 'rts' → 'rtsn' → 'rtsng'
example_2.py — Multiple Reversals
$ Input: s = "poiinter"
Output: "ponter"
💡 Note: '' → 'p' → 'po' → (reverse) 'op' → (reverse) 'po' → 'pon' → 'pont' → 'ponte' → 'ponter'
example_3.py — No 'i' Characters
$ Input: s = "hello"
Output: "hello"
💡 Note: Since there are no 'i' characters, the string is built normally without any reversals

Constraints

  • 1 ≤ s.length ≤ 100
  • s consists of only lowercase English letters
  • The character 'i' will trigger the reversal operation

Visualization

Tap to expand
Faulty Keyboard Problem INPUT Input String: s = "string" s t r i n g 0 1 2 3 4 5 Normal char Trigger 'i' (reverse) Faulty Keyboard i ALGORITHM STEPS 1 Type 's', 't', 'r' Append normally "str" 2 Type 'i' (REVERSE!) "str" --> "rts" "rts" 3 Type 'n' Append normally "rtsn" 4 Type 'g' Append normally "rtsng" Time: O(n) | Space: O(n) Using deque for efficiency (append at front/back = O(1)) FINAL RESULT Screen Display: r t s n g Output: "rtsng" Verification: s --> "s" t --> "st" r --> "str" i --> "rts" (reversed!) n --> "rtsn" g --> "rtsng" OK Key Insight: Use a deque (double-ended queue) and a direction flag. When 'i' is pressed, toggle the direction instead of actually reversing. Append to front or back based on direction. At the end, if direction is reversed, reverse the deque once. This avoids O(n) reversal for each 'i', making it O(n) total. TutorialsPoint - Faulty Keyboard | Optimal Solution
Asked in
Meta 15 Google 12 Amazon 8 Microsoft 6
23.4K Views
Medium Frequency
~8 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen