I have a problem which requires a string to be transformed into another one by appending copies of its' initial value to itself. The problem allows to remove single characters at some places.
Explanation
let x = "abba"; // First string
let y = "aba" // Second initial string
y("aba") => remove last "a" => y("ab") => y+initialY = "ab"+"aba" =>
y("ababa") => remove char at index 2 => y("abba") => y == x => sucess
My algorithm successfully solves the problem:
let x = "abbbbcccaaac"
let y = "abc"
let xArr = x.split('')
let yArr = y.split('')
let count = 0;
for (let i = 0; i < xArr.length; i++) {
if(yArr[i] == undefined) {
yArr = yArr.concat(y.split(''));
count++;
}
if(xArr[i] != yArr[i]) {
yArr.splice(i, 1);
i--;
}
}
console.log("Output is:", yArr.join(''))
console.log("Appends in order to transform:", count)
The algorithm works as intended, however, I am uncertain regarding its time and space complexity and most importantly - efficiency.
Is this algorithm in
O(n)
time complexity where n is the length ofx
?If this is not
O(n)
, can the problem be solved inO(n)
time?Does
.concat()
,.splice()
or.split()
somehow change the time complexity since they are nested in a for loop? What if they weren't, do they still change the time complexity of an algorithm and by how much?Given the rules of this problem, is this an efficient way to solve it?
What is the space complexity of this algorithm?