https://open.kattis.com/problems/lyklagangriti?editresubmit=16843522 This question is basically where you are entering a password. Every time there is an L in the input, the cursor "moves" to the left, same for the right, and when there is a B, you delete the character that you are on.
text = input()
chars = list(text)
cursor = 0
password = []
for char in chars:
if char == 'L':
cursor -= 1
elif char == 'R':
cursor += 1
elif char == 'B':
password.pop(cursor - 1)
cursor -= 1
else:
password.insert(cursor, char)
cursor += 1
print(*password, sep='')
I'm doing this problem on Kattis, and so far, I have passed a lot of test cases, but I seem to be exceeding the time limit on test groups 4 and 5. Is there anyway to speed up this code?
I'm solving this problem where I need to process a string with cursor movements:
'L'
moves the cursor left
'R'
moves it right
Other characters are inserted at the cursor position
Optimized code:
from sys import stdin
text = stdin.readline().strip()
left = []
right = []
for char in text:
if char == 'L':
if left:
right.append(left.pop())
elif char == 'R':
if right:
left.append(right.pop())
elif char == 'B':
if left:
left.pop()
else:
left.append(char)
print("".join(left + right[::-1]))
This uses two stacks to simulate the cursor efficiently