Skip to content

Edvins Antonovs

Backspace String Compare code challenge

My approach to solving LeetCode’s Backspace String Compare code challenge.


Problem

Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.

Note that after backspacing an empty text, the text will continue empty.


Solution

We start by creating a new function (cleanString) which accepts a string (s) as a variable. Then inside this function, we use String.split() to split a given string by letter and store the result in an array (val). We also create an array (res) to keep our final results.

Then we iterate through an array where we check whenever the current value (val[i]) is not equal to # during each loop. Here two things can happen, if the value is not identical, we add it to the results array, and if it's equal, we remove the last array value (Array.pop()).

Then all we need to do is to return a final result of the cleanString function by using Array.join() to convert it back to the string.

Finally, we run the cleanString function against the given words twice to compare their equality. Based on the comparison results, we return a boolean value.

1var backspaceCompare = function (s, t) {
2 const cleanString = (s) => {
3 let val = s.split('');
4 let res = [];
5
6 for (let i = 0; i < val.length; i++) {
7 if (val[i] !== '#') {
8 res.push(val[i]);
9 } else {
10 res.pop();
11 }
12 }
13
14 return res.join('');
15 };
16
17 return cleanString(s) === cleanString(t) ? true : false;
18};

Appendix

Subscribe to the newsletter

Get emails from me about web development, tech and entrepreneurship.

© 2022 by Edvins Antonovs. All rights reserved.