I was recently asked this question in an interview:
Given two strings s and t, return if they are equal when both are typed into empty text editors. # means a backspace character.
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".
I came up with below solution but it is not space efficient:
public static boolean sol(String s, String t) {
return helper(s).equals(helper(t));
}
public static String helper(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c != '#')
stack.push(c);
else if (!stack.empty())
stack.pop();
}
return String.valueOf(stack);
}
I wanted to see if there is any better way to solve this problem which doesn't use stack. I mean can we solve it in O(1) space complexity?
Note: we could have multiple backspace characters in as well.
In order to achieve O(1)
space complexity, use Two Pointers and start from the end of the string:
public static boolean sol(String s, String t) {
int i = s.length() - 1;
int j = t.length() - 1;
while (i >= 0 || j >= 0) {
i = consume(s, i);
j = consume(t, j);
if (i >= 0 && j >= 0 && s.charAt(i) == t.charAt(j)) {
i--;
j--;
} else {
return i == -1 && j == -1;
}
}
return true;
}
The main idea is to maintain the #
counter: increment cnt
if character is #
, otherwise decrement it. And if cnt > 0
and s.charAt(pos) != '#'
- skip the character (decrement position):
private static int consume(String s, int pos) {
int cnt = 0;
while (pos >= 0 && (s.charAt(pos) == '#' || cnt > 0)) {
cnt += (s.charAt(pos) == '#') ? +1 : -1;
pos--;
}
return pos;
}
Time complexity: O(n)
.
Source 1, Source 2.
Corrected pseudocode of templatetypedef
// Index of next spot to read from each string
let sIndex = s.length() - 1
let tIndex = t.length() - 1
let sSkip = 0
let tSkip = 0
while sIndex >= 0 and tIndex >= 0:
if s[sIndex] = #:
sIndex = sIndex - 1
sSkip = sSkip + 1
continue
else if sSkip > 0
sIndex = sIndex - 1
sSkip = sSkip - 1
continue
// Do the same thing for t.
if t[tIndex] = #:
tIndex = tIndex - 1
tSkip = tSkip + 1
continue
else if tSkip > 0
tIndex = tIndex - 1
tSkip = tSkip - 1
continue
// Compare characters.
if s[sIndex] != t[tIndex], return false
// Back up to the next character
sIndex = sIndex - 1
tIndex = tIndex - 1
// The strings match if we’ve exhausted all characters.
return sIndex < 0 and tIndex < 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With