Unit 4 Session 2 (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use a helper function to navigate each string from the end to the beginning, accounting for backspaces and comparing the resulting characters from each string.
1) Define a helper function that returns the index of the next valid character in the string by accounting for backspaces.
2) Initialize pointers for both strings at the end.
3) While either pointer has not reached the beginning of the string:
a) Use the helper function to find the next valid character for both strings.
b) Compare these characters:
i) If they are different, return False.
ii) If one string has characters left and the other doesn't, return False.
c) Decrement both pointers.
4) If all comparisons are valid, return True.
⚠️ Common Mistakes
def get_next_valid_char_index(string, index):
# Count of backspaces
backspace_count = 0
while index >= 0:
if string[index] == '#':
backspace_count += 1
elif backspace_count > 0:
backspace_count -= 1
else:
break
index -= 1
return index
def backspace_compare(s, t):
i, j = len(s) - 1, len(t) - 1
while i >= 0 or j >= 0:
i = get_next_valid_char_index(s, i)
j = get_next_valid_char_index(t, j)
if i >= 0 and j >= 0 and s[i] != t[j]:
return False
if (i >= 0) != (j >= 0):
# One is at the end, the other isn't
return False
i -= 1
j -= 1
return True