Prepin
Log in

R

Retrieve all distinct substrings from a specified string.

Approach / Explanation

The task requires you to create a function that generates a list of all unique substrings from a given input string. A substring refers to a contiguous sequence of characters within the string. For example, if your input string is "hello," some of the substrings would include "h," "he," "hel," "hell," "hello," "e," "el," and so forth. Your objective is to return a list of all possible substrings without any duplicates. It's important to note that while the lengths of these substrings can vary from 1 to the length of the input string, the order in which they appear does not matter. Therefore, substrings that contain the same characters but in different arrangements will be treated as unique substrings. To achieve this, you could: Create an empty set or list to keep track of the unique substrings. Iterate through the input string, and for each character, perform another loop with a different end index to capture all potential substrings that begin with that character. Insert each of these substrings into your set or list, ensuring to check that it isn't already included.

Suggested Answer

Here is a precise Python solution that follows the aforementioned method: def unique_substrings ( s ) : substrings = set ( ) for i in range ( len ( s ) ) : for j in range ( i + 1 , len ( s ) + 1 ) : substrings . add ( s [ i : j ] ) return list ( substrings ) When calling unique_substrings("aba") , the function will return ['a', 'b', 'ab', 'aba', 'ba'] .

Alternative Answer

Below is an analogous implementation in JavaScript: function uniqueSubstrings ( s ) { let substrings = new Set ( ) ; for ( let i = 0 ; i < s . length ; i ++ ) { for ( let j = i + 1 ; j <= s . length ; j ++ ) { substrings . add ( s . slice ( i , j ) ) ; } } return Array . from ( substrings ) ; } When the input uniqueSubstrings("abc") is provided, the function will return ["a", "ab", "abc", "b", "bc", "c"] . It’s important to note that the Set object utilized in both Python and JavaScript examples only permits unique values, which makes it easier for us, as we don't need to verify duplicates before inserting a new substring into our collection.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Google
Robinhood

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.