Ninja And Typing

Posted: 21 Apr, 2021
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

Ninja wants to print two strings in a text editor but his keyword allows typing lowercase English letters and backspace only.

Ninja type ‘N’ characters given by string ‘STR1’ to print the first string in the editor, and type ‘M’ characters given by string ‘STR2’ to print the second string. Both ‘STR1’ and ‘STR2’ have lowercase English characters and ‘#’ to denote backspace.

Your task is to return true if both strings that print on the text editor are equal otherwise return false. See the example for more clarity.

Note:
Backspace has no effect on empty text.
Example:
Consider ‘STR1’ = “ade##c#ba”, ‘STR2 = ‘a#ad#b#ba

Both ‘STR1’ and ‘STR2’ print the string “aba” on the text editor, thus we should return true.
Input Format:
The first line contains a single integer ‘T’ representing the number of test cases. 

The first line of each test case will contain two space-separated strings  ‘STR1’ and ’STR2’ respectively.
Output Format:
For each test case, print “true” if both strings that print on the text editor are equals otherwise print “false”

Output for every test case will be printed in a separate line.
Note:
You don’t need to print anything; It has already been taken care of.
Constraints:
1 <= T <= 50
2 <= N <= 10000
0 <= M <= 10000

Time limit: 1 sec
Approach 1

We use a stack to simulate typing of each character. When ninja type backspace we pop the top character from the string otherwise we push the typed character on top of the string.

 

The steps are as follows:

 

  • Create two empty stacks ‘STK1’, ‘STK2’.
  • Run a loop where ‘i’ ranges from 0 to ‘N’-1 and for each ‘i’ do the following :
    • If STR1[i] = ‘#’ and ‘STK1’ is not empty,  Pop the top element of ‘STK1’.
    • If STR1[i] != ‘#’  Push STR1[i] at top of ‘STK1’.
  • Run a loop where ‘i’ ranges from 0 to ‘M’-1 and for each ‘i’ do the following :
    • If STR2[i] = ‘#’ and ‘STK2’ is not empty,  Pop the top element of ‘STK2’.
    • If STR2[i] != ‘#’  Push STR2[i] at top of ‘STK2’.
  • Return true if both ‘STK1’ and ‘STK2’ are equal otherwise return false.
Try Problem