substrings
unique substrings
string manipulation
algorithm
programming

Generate all unique substrings for given string

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Generating all unique substrings of a given string is a fundamental problem in computer science with applications in text processing, data compression, and bioinformatics. This operation involves extracting every possible contiguous sequence of characters from a string and ensuring that each substring appears only once in the final list.

Concepts and Definitions

Before diving into algorithms, let’s define some key concepts:

  • String: A sequence of characters, e.g., `"abc"`.
  • Substring: A contiguous sequence of characters within a string. For example, `"ab"`, `"bc"`, and `"abc"` are substrings of `"abc"`.
  • Unique Substrings: Substrings that appear only once in the list of all possible substrings.

Problem Explanation

The task is to generate a list of all possible unique substrings for any given string. Consider the string `s = "abc"`. The substrings are:

  • Length 1: `a`, `b`, `c`
  • Length 2: `ab`, `bc`
  • Length 3: `abc`

Therefore, the unique substrings of `"abc"` are: `["a", "b", "c", "ab", "bc", "abc"]`.

Algorithm Overview

A straightforward approach to generate all unique substrings involves iterating over every possible starting and ending position within the string:

  1. Initialize: Create a set to hold substrings and ensure uniqueness.
  2. Nested Loop:
    • Use an outer loop to fix the starting position of the substring.
    • Use an inner loop to define the ending position of the substring and extract the substring.
    • Add each substring to the set.
  3. Convert Set to List: Convert the set to a list to obtain the result.

Example Implementation

Here is a Python example implementing the above logic:

  • Empty String: If the string is empty, the set of substrings is also empty.
  • Single Character: For a single character string, the only substring is itself.
  • Suffix Array: An array of all starting positions of suffixes of a string, sorted lexicographically.
  • Suffix Tree: A compressed trie of all the suffixes of a string, allowing for faster substring identification and manipulation.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.