JSFiddle - React, Tailwind, and code Playground
HTML
<div id="result"></div>
<script>
var arr = ['h','t','t','p',':','/','/','w','w','w','.','x','y','z','.','c','o','m','/','s','o','m','e',' ','u','r','l',' ','w','i','t','h',' ','s','p','a','c','e','s',null,null,null,null,null,null,null,null,null,null,null,null],
printR = function(str) {
if (Array.isArray(str)) {
str = str.join('');
}
$('#result').append('<p>' + str + '</p>');
};
</script>
JavaScript
/*
* Problem statement
* Replace spaces in the URL with %20 with following constraints
* (1) Do not define another array anywhere in your solution
* (2) Do not use methods like Array 'join' and String 'replace'
* (3) Use simple looping
*
*/
var arrLen = arr.length,
i = 0, j = 0, loop = 0;
printR('With outer loop left to right');
for (null; i < arrLen; i++, loop++) {
if (arr[i] === ' ') {
j = arrLen;
while (--j > i) {
arr[j + 2] = arr[j];
loop++;
}
arr[j + 2] = 0;
arr[j + 1] = 2;
arr[j] = '%';
}
}
printR(arr);
printR(--loop + ' iterations');
printR('-----------------------------------------------------');
/*
* Extended Problem statement
* Compare the approach with outer loop in reverse direction
*
*/
arr = ['h','t','t','p',':','/','/','w','w','w','.','x','y','z','.','c','o','m','/','s','o','m','e',' ','u','r','l',' ','w','i','t','h',' ','s','p','a','c','e','s',null,null,null,null,null,null,null,null,null,null,null,null]; //resetting the array to original value
loop = 0;
i = arrLen;
printR('With outer loop right to left');
while (--i) {
if (arr[i] === ' ') {
j = arrLen;
while (--j > i) {
arr[j + 2] = arr[j];
loop++;
}
arr[j + 2] = 0;
arr[j + 1] = 2;
arr[j] = '%';
}
loop++;
}
printR(arr);
printR(--loop + ' iterations');