Search⌘ K

Solution to Sub-task: Blank Insertions

Explore how to implement a recursive JavaScript function that inserts spaces at various positions in a line. Understand base cases and recursive logic, including helper functions, to generate all unique combinations of added blanks for text manipulation tasks.

We'll cover the following...

Blank insertions

In this step, add a certain number of spaces in a line and produce all possible combinations of added spaces at different positions.

Node.js
// helper function to permute combinations of adding just one space
// input -> [String] eg. ['he', 'l', 'lo']
// Output -> [[String]]
// eg. [ ['he', ' ', 'l', 'lo'],
// ['he', 'l', ' ', 'lo'], ]
function singleBlankInsert(line){
// when only two words basecase
if(line.length === 2) return [[line[0],' ',line[1]]];
// when only one word basecase
if(line.length <= 1) return [line];
let [head, ...tail] = line;
let answer = singleBlankInsert(tail);
answer = answer.map(x => [head, ...x]);
answer.push([head, ' ', ...tail]);
return answer;
}
function blankInsertions(num, line){
if(num === 0) return [line];
if(line.length <= 1) return [line];
let answer = blankInsertions(num-1, line);
// insert one blank for each line using map
answer = answer.map(x => singleBlankInsert(x));
// flatten the array
answer = answer.reduce((prev, curr)=> prev.concat(curr), []);
// filter duplicates
return Array.from(new Set(answer.map(JSON.stringify)), JSON.parse)
}
enHyp = {
"creative" : ["cr","ea","ti","ve"],
"controls" : ["co","nt","ro","ls"],
"achieve" : ["ach","ie","ve"],
"future" : ["fu","tu","re"],
"present" : ["pre","se","nt"],
"motivated" : ["mot","iv","at","ed"],
"desire" : ["de","si","re"],
"others" : ["ot","he","rs"],
}
console.log(blankInsertions( 2, ["A", "creative", "man"]))

Solve this solution recursively, where our base cases are as follows.

  • Number of spaces num that we need to add is zero (line 19)
  • Length of the line is less than or equal to one, and no spaces are added (line 20
...