Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Longest substring with k unique characters
Next article icon

Create a string with unique characters from the given N substrings

Last Updated : 24 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] containing N substrings consisting of lowercase English letters, the task is to return the minimum length string that contains all given parts as a substring. All characters in this new answer string should be distinct. If there are multiple strings with the following property present, you have to print the string with minimum length. 

Examples:

Input: N = 3, arr[] = {"bcd", "ab", "cdef"}
Output: "abcdef"
Explanation:

  • abcdef contains "bcd" from [1-3] index (0-based indexing)
  • abcdef contains "ab" from [0-2] 
  • abcdef contains "cdef" from [2-5]

It can be proven that "abcdef" is the smallest string consisting of the given 3 substring fragments from input.

Input: N = 3, arr[]= {"dfghj",  "ghjkl", "asdfg"];
Output: "asdfghjkl"
Explanation: 

  • asdfghjkl contains "dfghj" from [2-6] index (0-based indexing)
  • asdfghjkl contains "ghjkl" from [4-8] 
  • asdfghjkl contains "asdfg" from [0-4]

It can be proven that "asdfghjkl " is the smallest string consisting of the given 3 substring fragments from input.

Approach: Implement the below idea to solve the problem:

  • While traversing a string, if a character in left and right exists we will be storing this, information in the left[] and right[] array. If an element of a substring does not have a left element,  
    this means that it's the first element. We will be marking these elements as -1(indicating the start of a substring).
  • Finally, print the final answer. We will be starting with the character having a - 1 value in the left[] array because it's the start of the string and will gonna print its right element from the right[] array, now this right element is the new element and now we will be finding it's the right element from right[] array the same way until we reach -2 (as right) for an element, which indicates the end of the string. 

Follow the steps to solve the above idea:

  • Create two arrays left[] and right[] having size = 26 (a to z)
  • Initialize each value for left[] and right[] = -2 (indicating the following characters has no left and right elements yet)
  • Iterate over each substring given in the input array
    • if it's the first character mark it's left = -1 (indicating the start of a substring)
    • else if, it's left == -2 (does not exist yet) update it with the left character if it exists in the current substring
    • update the right[] value by accessing s[i+1]th character of the current substring if it exists.
  • To print the final result find out the index containing -2 in the left[] array
    • print this element and update current = right[current]
    • repeat until right != -2 

Below is the code to implement the approach:

C++
// C++ code for the above approach:  #include <bits/stdc++.h> using namespace std;  // Function to create string containing // all substrings of array arr[] void formedString(int n, vector<string>& arr) {      // Defining left and right array to     // store the left and right element     // for each character (a to z)     vector<int> left(26), right(26);      // Initializing left and right values     // for each character = -2 (indicating     // the following characters has no left     // and right elements yet)     for (int i = 0; i < 26; i++)         left[i] = right[i] = -2;      for (string s : arr) {          // Iterating over each substring s         // given in the array         for (int j = 0; j < s.size(); j++) {              // Finding the character index             // to store             int t = s[j] - 'a';              // If it's the first character             // of substring (means left             // does not exist)             if (j > 0) {                 int t1 = s[j - 1] - 'a';                 left[t] = t1;             }             else if (left[t] == -2)                 left[t] = -1;              // If right element exists for             // jth character find it and             // store in right[t]             if (j < s.size() - 1) {                 int t1 = s[j + 1] - 'a';                 right[t] = t1;             }         }     }      // Code to output the final string     int j;      // Looping over all characters from     // (a to z) to find out the first     // index (having left = -1)     for (int i = 0; i < 26; i++)          if (left[i] == -1) {              // If 1st index is found print             // it and update j = right[j]             // and repeat until -2 is             // encountered -2 indicates             // the end             int j = i;              while (j != -2) {                 // Converting the integer                 // value into character                 cout << (char)(j + 97);                 j = right[j];             }         } }  // Driver code int main() {      int n = 3;     vector<string> arr = { "dfghj", "ghjkl", "asdfg" };      // Function call     formedString(n, arr); } 
Java
// Java code for the above approach:  import java.io.*; import java.util.*;  class GFG {      // Function to create string containing     // all substrings of array arr[]     static void formedString(int n, String arr[])     {          // Defining left and right array to         // store the left and right element         // for each character (a to z)         int[] left = new int[26];         int[] right = new int[26];         // Initializing left and right values         // for each character = -2 (indicating         // the following characters has no left         // and right elements yet)         for (int i = 0; i < 26; i++)             left[i] = right[i] = -2;          for (String s : arr) {              // Iterating over each substring s             // given in the array             for (int j = 0; j < s.length(); j++) {                  // Finding the character index                 // to store                 int t = s.charAt(j) - 'a';                 // If it's the first character                 // of substring (means left                 // does not exist)                 if (j > 0) {                     int t1 = s.charAt(j - 1) - 'a';                     left[t] = t1;                 }                 else if (left[t] == -2)                     left[t] = -1;                  // If right element exists for                 // jth character find it and                 // store in right[t]                 if (j < s.length() - 1) {                     int t1 = s.charAt(j + 1) - 'a';                     right[t] = t1;                 }             }         }          // Code to output the final string         int j;         // Looping over all characters from         // (a to z) to find out the first         // index (having left = -1)         for (int i = 0; i < 26; i++)              if (left[i] == -1) {                  // If 1st index is found print                 // it and update j = right[j]                 // and repeat until -2 is                 // encountered -2 indicates                 // the end                 j = i;                  while (j != -2) {                     // Converting the integer                     // value into character                     System.out.print((char)(j + 97));                     j = right[j];                 }             }     }      // Driver code     public static void main(String[] args)     {         int n = 3;          String[] arr = { "dfghj", "ghjkl", "asdfg" };         // Function Call         formedString(n, arr);     } } 
Python3
# Python3 code for the above approach  # Function to create string containing # all substrings of array arr[] def formedstring(n, arr):      # Defining left and right array to     # store the left and right element     # for each character (a to z)     left = [-2 for i in range(26)]     right = [-2 for i in range(26)]      for s in arr:          # Iterating over each substring s         #  given in the array         for j in range(len(s)):              # Find the character index to store             t = ord(s[j]) - ord('a')              # If it is the first character             # of substring (means left does not exist)             if j > 0:                 t1 = ord(s[j - 1]) - ord('a')                 left[t] = t1                              elif left[t] == -2:                 left[t] = -1              # If right element exists for jth character              # find it and store in right[t]             if j < len(s) - 1:                 t1 = ord(s[j + 1]) - ord('a')                 right[t] = t1      # Code to output the final string     j = None      # Looping over all characters from     # (a to z) to find out the first     # index (having left = -1)     for i in range(26):          if left[i] == -1:              # If 1st index is found print             # it and update j = right[j]             # and repeat until -2 is             # encountered -2 indicates the end             j = i              while j != -2:                 # Converting the integer                 # value into character                 print(chr(j + 97), end="")                 j = right[j]  # Driver code if __name__ == "__main__":     n = 3     arr = ["dfghj", "ghjkl", "asdfg"]      # Function call     formedstring(n, arr)  #This code is contributed by nikhilsainiofficial546 
C#
// C# code for the above approach: using System;  public class GFG{      // Function to create string containing     // all substrings of array arr[]     static void formedString(int n, string[] arr)     {          // Defining left and right array to         // store the left and right element         // for each character (a to z)         int[] left = new int[26];         int[] right = new int[26];         // Initializing left and right values         // for each character = -2 (indicating         // the following characters has no left         // and right elements yet)         for (int i = 0; i < 26; i++)             left[i] = right[i] = -2;          foreach (string s in arr) {              // Iterating over each substring s             // given in the array             for (int k = 0; k < s.Length;k++) {                  // Finding the character index                 // to store                 int t = s[k] - 'a';                 // If it's the first character                 // of substring (means left                 // does not exist)                 if (k > 0) {                     int t1 = s[k - 1] - 'a';                     left[t] = t1;                 }                 else if (left[t] == -2)                     left[t] = -1;                  // If right element exists for                 // jth character find it and                 // store in right[t]                 if (k < s.Length - 1) {                     int t1 = s[k + 1] - 'a';                     right[t] = t1;                 }             }         }          // Code to output the final string         int j;         // Looping over all characters from         // (a to z) to find out the first         // index (having left = -1)         for (int i = 0; i < 26; i++)              if (left[i] == -1) {                  // If 1st index is found print                 // it and update j = right[j]                 // and repeat until -2 is                 // encountered -2 indicates                 // the end                 j = i;                  while (j != -2) {                     // Converting the integer                     // value into character                     Console.Write((char)(j + 97));                     j = right[j];                 }             }     }      // Driver code     static public void Main (){          int n = 3;          String[] arr = { "dfghj", "ghjkl", "asdfg" };         // Function Call         formedString(n, arr);     } } 
JavaScript
function formedString(n, arr) {   // Defining left and right array to   // store the left and right element   // for each character (a to z)   let left = Array(26).fill(-2);   let right = Array(26).fill(-2);    arr.forEach((s) => {     // Iterating over each substring s     // given in the array     for (let j = 0; j < s.length; j++) {       // Find the character index to store       let t = s.charCodeAt(j) - 'a'.charCodeAt(0);         // If it is the first character       // of substring (means left does not exist)       if (j > 0) {         let t1 = s.charCodeAt(j - 1) - 'a'.charCodeAt(0);         left[t] = t1;       } else if (left[t] == -2) {         left[t] = -1;       }        // If right element exists for jth character       // find it and store in right[t]       if (j < s.length - 1) {         let t1 = s.charCodeAt(j + 1) - 'a'.charCodeAt(0);         right[t] = t1;       }     }   });    // Code to output the final string   let j = null;    // Looping over all characters from   // (a to z) to find out the first   // index (having left = -1)   for (let i = 0; i < 26; i++) {     if (left[i] == -1) {     // If 1st index is found print     // it and update j = right[j]     // and repeat until -2 is     // encountered -2 indicates the end     j = i;     while (j != -2) {       // Converting the integer       // value into character       process.stdout.write(String.fromCharCode(j + 97));       j = right[j];       }     }   } }  // Driver code if (require.main === module) { let n = 3; let arr = ["dfghj", "ghjkl", "asdfg"];  // Function call formedString(n, arr); } 

Output
asdfghjkl

Time Complexity: O(N*C), Where C is equal to the maximum size of a substring.   
Auxiliary Space: O(1) (two extra arrays left[] and right[] of size 26 are used which is constant for all input sizes).

Related Articles:

  • Introduction to Arrays – Data Structure and Algorithm Tutorials

Next Article
Longest substring with k unique characters

S

sdeadityasharma
Improve
Article Tags :
  • Strings
  • Technical Scripter
  • DSA
  • Arrays
  • Technical Scripter 2022
Practice Tags :
  • Arrays
  • Strings

Similar Reads

  • Count of all unique substrings with non-repeating characters
    Given a string str consisting of lowercase characters, the task is to find the total number of unique substrings with non-repeating characters. Examples: Input: str = "abba" Output: 4 Explanation: There are 4 unique substrings. They are: "a", "ab", "b", "ba". Input: str = "acbacbacaa" Output: 10 App
    6 min read
  • Count the number of unique characters in a given String
    Given a string, str consisting of lowercase English alphabets, the task is to find the number of unique characters present in the string. Examples: Input: str = “geeksforgeeks”Output: 7Explanation: The given string “geeksforgeeks” contains 7 unique characters {‘g’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’}. Inp
    14 min read
  • Counting K-Length Strings with Fixed Character in a Unique String
    Given a string S of length n containing distinct characters and a character C , the task is to count k-length strings that can be formed using characters from the string S, ensuring each string includes the specified character C, and no characters from the given string S are used more than once. Ret
    9 min read
  • Longest substring with k unique characters
    Given a string you need to print longest possible substring that has exactly k unique characters. If there is more than one substring of longest possible length, then print any one of them. Note:- Source(Google Interview Question). Examples: Input: Str = "aabbcc", k = 1Output: 2Explanation: Max subs
    13 min read
  • Count of Substrings that can be formed without using the given list of Characters
    Given a string str and a list of characters L, the task is to count the total numbers of substrings of the string str without using characters given in the list L. Examples: Input: str = "abcd", L[] = {'a', 'b', 't', 'q'} Output: 3 Explanation: On ignoring the characters 'a' and 'b' from the given s
    7 min read
  • Count substrings with each character occurring at most k times
    Given a string S. Count number of substrings in which each character occurs at most k times. Assume that the string consists of only lowercase English alphabets. Examples: Input : S = ab k = 1 Output : 3 All the substrings a, b, ab have individual character count less than 1. Input : S = aaabb k = 2
    15+ min read
  • Smallest string containing all unique characters from given array of strings
    Given an array of strings arr[], the task is to find the smallest string which contains all the characters of the given array of strings. Examples: Input: arr[] = {"your", "you", "or", "yo"}Output: ruyoExplanation: The string "ruyo" is the smallest string which contains all the characters that are u
    9 min read
  • Count of substrings from given Ternary strings containing characters at least once
    Given string str of size N consisting of only 0, 1, and 2, the task is to find the number of substrings that consists of characters 0, 1, and 2 at least once. Examples: Input: str = "0122"Output: 2Explanation:There exists 2 substrings such that the substrings has characters 0, 1, 2 at least once is
    6 min read
  • Count of substrings formed using a given set of characters only
    Given a string str and an array arr[] of K characters, the task is to find the number of substrings of str that contain characters only from the given character array arr[]. Note: The string str and the arr[] contain only lowercase alphabets. Examples: Input: S = "abcb", K = 2, charArray[] = {'a', '
    8 min read
  • Count of substrings which contains a given character K times
    Given a string consisting of numerical alphabets, a character C and an integer K, the task is to find the number of possible substrings which contains the character C exactly K times. Examples: Input : str = "212", c = '2', k = 1 Output : 4 Possible substrings are {"2", "21", "12", "2"} that contain
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences