Tutorialspoint
Problem
Solution
Submissions

Find All Substrings of a Given String

Certification: Intermediate Level Accuracy: 66.67% Submissions: 6 Points: 5

Write a Python function to find all possible string substrings.

Example 1
  • Input: s = "abc"
  • Output: ['a', 'ab', 'abc', 'b', 'bc', 'c']
  • Explanation:
    • Step 1: Start with an empty result list.
    • Step 2: Find all substrings starting from index 0:
      • Substring of length 1: 'a'
      • Substring of length 2: 'ab'
      • Substring of length 3: 'abc'
    • Step 3: Find all substrings starting from index 1:
      • Substring of length 1: 'b'
      • Substring of length 2: 'bc'
    • Step 4: Find all substrings starting from index 2:
      • Substring of length 1: 'c'
    • Step 5: Combine all substrings to get ['a', 'ab', 'abc', 'b', 'bc', 'c'].
Example 2
  • Input: s = "xy"
  • Output: ['x', 'xy', 'y']
  • Explanation:
    • Step 1: Start with an empty result list.
    • Step 2: Find all substrings starting from index 0:
      • Substring of length 1: 'x'
      • Substring of length 2: 'xy'
    • Step 3: Find all substrings starting from index 1:
      • Substring of length 1: 'y'
    • Step 4: Combine all substrings to get ['x', 'xy', 'y'].
Constraints
  • 1 <= len(string) <= 100
  • Time Complexity: O(n²) where n is the length of the string
  • Space Complexity: O(n²)
StringsDeloitteDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use nested loops to generate all substrings: outer loop for the starting index, inner loop for the ending index.
  • Append each substring to a list and return the list.

Steps to solve by this approach:

 Step 1: Initialize an empty list to store all substrings
 
 Step 2: Use a nested loop to generate all possible substring ranges
 Step 3: Outer loop (i) iterates through each starting position
 Step 4: Inner loop (j) iterates through each possible ending position
 Step 5: For each (i,j) pair, extract substring s[i:j] and add to list
 Step 6: Continue until all possible substrings are generated
 Step 7: Return the complete list of all substrings

Submitted Code :