Get all substrings of a string in JavaScript recursively


In the provided problem statement, our aim is to get all substrings of a string recursively with the help of Javascript. So here we will be creating a recursive function that can generate all possible substrings of a given input string.

Understanding the problem statement

The problem statement is asking us to create a recursive function which can generate all the possible substrings of a given input string with the help of Javascript. A substring is any continuous sequence of characters within the input string. For example: input strings “xy" so the possible substrings are "x", "y", and "xy".

Algorithm

Step 1 − Start the program by defining the function and pass an argument in it a string to which we have to find the substrings.

Step 2 − Define an array to hold the result array of substrings. And initialize it with zero values.

Step 3 − Use another recursive function and pass two parameters in it as starting Index and ending Index.

Step 4 − Declare a base case and check the condition that the ending Index is equal to the string length. If it is equal then return.

Step 5 − Use a recursive case in which we will check that the starting index is greater than the ending index then call the recurse function again and increment the ending index by 1.

Step 6 − Otherwise push the result by slicing the string and pass startIndex and endIndex. And again call the recurse function.

Step 7 − Call the recurse function and return the result.

Code for the algorithm

// function to get the substrings for the given string
function getAllSubstrings(str) {
   let result = [];

   function recurse(startIndex, endIndex) {
      // Base case
      if (endIndex === str.length) {
         return;
      }

      // Recursive case
      if (startIndex > endIndex) {
         recurse(0, endIndex + 1);
      } else {
         result.push(str.slice(startIndex, endIndex + 1));
         recurse(startIndex + 1, endIndex);
      }
   }

   recurse(0, 0);
   return result;
}

const inputStr = "wxyz";
const subStr = getAllSubstrings(inputStr);
console.log(subStr);

Complexity

The above recursive function has a time complexity of O(n^2) where n is the length of the input string. Because the function produces all possible substrings from the given input string. Additionally we contain (n^2) substrings in memory so the code has an O(n^2) space complexity.

Conclusion

In the Javascript code we have utilized a recursive strategy to locate all the possible substrings of the supplied string. With the usage of nested function the code is generating all the potential strings. The recurse function executes with different parameters until no substrings are created.

Updated on: 18-May-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements