Here is the interview question prompt, presented for reference.
You're given an array of strings containing alphabetical characters and certain $
characters. A $
represents a DELETE action whereby the character before it is deleted.
Each of these strings will be run through a method to operate on the $
DELETE action. We want to find out if the final string is the same for all of them. Let's take an example:
String[] input = {"f$st", "st"};
isDollarDeleteEqual(input);
// true
// true because both become "st"
let input = ["f$st", "st"];
isDollarDeleteEqual(input);
// true
// true because both become "st"
input = ["f$st", "st"]
is_dollar_delete_equal(input)
# True
# True because both become 'st'
std::vector<std::string> input = {"f$st", "st"};
isDollarDeleteEqual(input);
// true
// true because both become "st"
string[] input = {"f$st", "st"};
IsDollarDeleteEqual(input);
// true
// true because both become "st"
input := []string{"f$st", "st"}
isDollarDeleteEqual(input)
// true
// true because both become "st"
Can you find a solution in O(n)
time and constant
space?
O(n)
O(n)
for good solution, O(1)
for asymptotically optimal solutionYou can see the full challenge with visuals at this link.
Challenges • Asked about 5 years ago by Hardik
This is the main discussion thread generated for Dollar Sign Deletion.
Test case 1 and 2 are both same yet it is shown that their results are different.
['f$ec', 'ec'] should return true
['f$ec', 'ec'] should return false
These 2 test cases are contradictory.
Yes, we have now fixed this problem.
I can't figure out why my code doesn't work. It works when I try it in repl.it, is it because it doesn't make the time constraint?? Thanks!
function isDollarDeleteEqual(arr) {
let mapped = arr.map(item => getFinalStr(item));
return mapped.every(item => item === mapped[0]);
}
function getFinalStr(str) {
let arr = str.split('');
for(i =0; i < arr.length; i++) {
if(arr[i] === '$') {
arr.splice(i-1, 2);
}
}
return arr.join('');
}
Just to make sure this thread is finished with an answer and not a question.
This code fails tests 3 and 4 because getFinalStr()
modifies the array arr
inside the for
cycle. After splice
finishes its job, i
references the position where "$"
was before the deletion of 2 characters. Therefore, continuing iteration effectively skips the next two characters. To make this code work you could add i -= 2
after calling the splice
method. Alternatively, you should consider using other ways like while
loop granting you more control over the iteration variable.