Search~25 min2s · 256 MBtarget O(n + m) time, O(n + m) spaceclassic twin: lc-844read-write-pointers · two-pointers
A search engine logs the raw keystrokes of every typed query. Each letter is logged as it is typed, and each backspace is logged as #. So the log cat#r ends as the text car.
The query cache stores results by the final text of a query. To match two logged queries against the cache, the service must know whether both logs end as the same text. Most logs are short, but a long editing session can log up to 100,000 keystrokes. The service applies each log in a working buffer, editing it in place.
Write same_query(first, second).
first and second are keystroke logs, in the order the keys were pressed. Each character is a lower-case letter a to z, or # for a backspace.true if both logs end as the same text, and false otherwise. Two texts that both end empty are the same.Input: first = "map#r#ps", second = "mapz#s"
Output: trueThe table applies first. The write pointer marks the end of the text.
| read | Keystroke | Action | write after | Text so far |
|---|---|---|---|---|
| 0 | m | letter: copied to position 0 | 1 | m |
| 1 | a | letter: copied to position 1 | 2 | ma |
| 2 | p | letter: copied to position 2 | 3 | map |
| 3 | # | backspace: write steps back | 2 | ma |
| 4 | r | letter: copied to position 2 | 3 | mar |
| 5 | # | backspace: write steps back | 2 | ma |
| 6 | p | letter: copied to position 2 | 3 | map |
| 7 | s | letter: copied to position 3 | 4 | maps |
In second, the backspace removes the z, so it also ends as maps. Both texts have length 4 and match letter by letter.
Input: first = "shoe#s", second = "shoes#"
Output: falseThe first log ends as shos, because its backspace removes the e. The second ends as shoe. Both are 4 letters long, but the last letters differ.
Input: first = "##", second = "a#"
Output: trueThe backspaces in first meet empty text and do nothing. In second, the backspace removes the a. Both texts end empty.
1 ≤ first.length ≤ 10^51 ≤ second.length ≤ 10^5a to z, or #.Rebuilding the whole text on every keystroke copies the text each time. For a log of 10^5 letters that is 5,000,050,000 character copies, and there are two logs. Aim for O(n) per log.
A backspace changes only the end of the text. So one array and one index that marks its end are enough.