Get all substrings of a string in JavaScript recursively

In JavaScript, generating all substrings of a string can be elegantly solved using recursion. A substring is any continuous sequence of characters within a string. For example, the string "abc" has substrings: "a", "b", "c", "ab", "bc", and "abc".

Understanding the Problem

We need to create a recursive function that generates all possible substrings of a given input string. For the string "xy", the possible substrings are "x", "y", and "xy". The recursive approach systematically explores all starting and ending positions to build each substring.

Algorithm Steps

Step 1 ? Define the main function that accepts a string parameter.

Step 2 ? Initialize an empty array to store all substrings.

Step 3 ? Create a recursive helper function with starting and ending index parameters.

Step 4 ? Set base case: if ending index equals string length, return.

Step 5 ? If starting index exceeds ending index, move to next ending position.

Step 6 ? Otherwise, extract substring and continue with next starting position.

Step 7 ? Call the recursive function and return results.

Recursive Implementation

// Function to get all substrings recursively
function getAllSubstrings(str) {
   let result = [];

   function recurse(startIndex, endIndex) {
      // Base case: reached end of string
      if (endIndex === str.length) {
         return;
      }

      // If startIndex exceeds endIndex, move to next ending position
      if (startIndex > endIndex) {
         recurse(0, endIndex + 1);
      } else {
         // Add current substring to result
         result.push(str.slice(startIndex, endIndex + 1));
         // Continue with next starting position
         recurse(startIndex + 1, endIndex);
      }
   }

   recurse(0, 0);
   return result;
}

// Example usage
const inputStr = "abc";
const substrings = getAllSubstrings(inputStr);
console.log("All substrings of '" + inputStr + "':");
console.log(substrings);
All substrings of 'abc':
[ 'a', 'ab', 'abc', 'b', 'bc', 'c' ]

How the Recursion Works

The algorithm uses two indices to track substring boundaries. It starts with both indices at 0, extracts the substring, then recursively moves the start index. When the start index exceeds the end index, it resets to 0 and increments the end index, exploring longer substrings.

Recursive Substring Generation String: "abc" Step 1: start=0, end=0 ? "a" Step 2: start=1, end=0 ? move end Step 3: start=0, end=1 ? "ab" Step 4: start=1, end=1 ? "b" Step 5: start=0, end=2 ? "abc" Process continues until all positions explored

Alternative Recursive Approach

// Alternative: Generate substrings by including/excluding characters
function getSubstringsAlternative(str, index = 0, current = "", result = []) {
   // Base case: processed all characters
   if (index === str.length) {
      if (current !== "") {
         result.push(current);
      }
      return result;
   }
   
   // Include current character
   getSubstringsAlternative(str, index + 1, current + str[index], result);
   
   // Exclude current character (start new substring)
   if (current !== "") {
      result.push(current);
   }
   getSubstringsAlternative(str, index + 1, str[index], result);
   
   return [...new Set(result)]; // Remove duplicates
}

console.log("Alternative approach:");
console.log(getSubstringsAlternative("xy"));
Alternative approach:
[ 'xy', 'x', 'y' ]

Complexity Analysis

Aspect Complexity Explanation
Time O(n³) O(n²) substrings × O(n) slice operation
Space O(n²) Storage for all n² substrings
Call Stack O(n²) Maximum recursion depth

Conclusion

Recursive substring generation provides an elegant solution with clear logic flow. The algorithm systematically explores all possible start and end positions, making it easy to understand and implement for educational purposes.

Updated on: 2026-03-15T23:19:00+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements