Skip to content
Related Articles

Related Articles

Improve Article

Construct an Array of Strings having Longest Common Prefix specified by the given Array

  • Difficulty Level : Easy
  • Last Updated : 08 Jun, 2021

Given an integer array arr[] of size N, the task is to construct an array consisting of N+1 strings of length N such that arr[i] is equal to the Longest Common Prefix of ith String and (i+1)th String.

Examples:

Input: arr[] = {1, 2, 3} 
Output: {“abb”, “aab”, “aaa”, “aaa”} 
Explanation: 
Strings “abb” and “aab” have a single character “a” as Longest Common Prefix. 
Strings “aab” and “aaa” have “aa” as Longest Common Prefix. 
Strings “aaa” and “aaa” have “aa” as Longest Common Prefix.
 

Input : arr[]={2, 0, 3} 
Output: {“bab”, “baa”, “aaa”, “aaa”} 
Explanation: 
Strings “bab” and “baa” have “ba” as Longest Common Prefix. 
Strings “baa” and “aaa” have no common prefix. 
Strings “aaa” and “aaa” have “aaa” as Longest Common Prefix. 
 

Approach:



Follow the steps below to solve the problem:  

  • The idea is to observe that if ith string is known then (i-1)th string can be formed from ith string by changing N – arr[i-1] characters from ith string.
  • Start constructing strings from right to left and generate the N + 1 strings.

Illustration: 
N = 3, arr[] = {2, 0, 3} 
Let the (N + 1)th string is “aaa” 
Therefore, the remaining strings from right to left are {“aaa”, “baa”, “bab”} 

Below is the implementation of the above approach: 
 

C++




// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the array of strings
vector<string> solve(int n, int arr[])
{
    // Marks the (N+1)th string
    string s = string(n, 'a');
 
    vector<string> ans;
    ans.push_back(s);
 
    // To generate remaining N strings
    for (int i = n - 1; i >= 0; i--) {
 
        // Find i-th string using
        // (i+1)-th string
        char ch = s[arr[i]];
 
        // Check if current character
        // is b
        if (ch == 'b')
            ch = 'a';
 
        // Otherwise
        else
            ch = 'b';
        s[arr[i]] = ch;
 
        // Insert the string
        ans.push_back(s);
    }
 
    // Return the answer
    return ans;
}
 
// Driver Code
int main()
{
 
    int arr[] = { 2, 0, 3 };
    int n = sizeof arr / sizeof arr[0];
    vector<string> ans = solve(n, arr);
 
    // Print the strings
    for (int i = ans.size() - 1; i >= 0; i--) {
        cout << ans[i] << endl;
    }
 
    return 0;
}

Java




// Java Program to implement
// the above approach
import java.util.*;
class GFG
{
 
  // Function to find the array of strings
  static Vector<String> solve(int n, int arr[])
  {
     
    // Marks the (N+1)th string
    String s = "aaa";
    Vector<String> ans = new Vector<String>();
    ans.add(s);
 
    // To generate remaining N strings
    for (int i = n-1 ; i >= 0; i--)
    {
 
      // Check if current character
      // is b
      if(s.length() - 1 >= arr[i])
      {
 
        // Find i-th string using
        // (i+1)-th string
        char ch = s.charAt(arr[i]);
        if (ch == 'b')
          ch = 'a';
 
        // Otherwise
        else
          ch = 'b';
        char[] myNameChars =s.toCharArray();
        myNameChars[arr[i]] = ch;
        s = String.valueOf(myNameChars);
      }
 
      // Insert the string
      ans.add(s);
    }
 
    // Return the answer
    return ans;
  }
 
  // Driver Code
  public static void main(String []args)
  {
 
    int []arr = { 2, 0, 3};
    int n = arr.length;
    Vector<String> ans = solve(n, arr);
 
    // Print the strings
    for (int i = ans.size()-1; i >= 0; i--)
    {
      System.out.println(ans.get(i));
    }
  }
}
 
// This code is contributed by bgangwar59.

Python3




# Python3 Program to implement
# the above approach
 
# Function to find the array
# of strings
def solve(n, arr):
 
    # Marks the (N+1)th
    # string
    s = 'a' * (n)
    ans = []
    ans.append(s)
 
    # To generate remaining
    # N strings
    for i in range(n - 1,
                   -1, -1):
 
        # Find i-th string using
        # (i+1)-th string   
        if len(s) - 1 >= arr[i]:
           ch = s[arr[i]]
 
           # Check if current
           # character
           # is b
           if (ch == 'b'):
               ch = 'a'
 
           # Otherwise
           else:
               ch = 'b'
            
           p = list(s)
           p[arr[i]] = ch
           s = ''.join(p)
 
        # Insert the string
        ans.append(s)
 
    # Return the answer
    return ans
 
# Driver Code
if __name__ == "__main__":
 
    arr = [2, 0, 3]
    n = len(arr)
    ans = solve(n, arr)
 
    # Print the strings
    for i in range(len(ans) - 1,
                   -1, -1):
        print(ans[i])
 
# This code is contributed by Chitranayal

C#




// C# Program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to find the array of strings
  static List<string> solve(int n, int []arr)
  {
 
    // Marks the (N+1)th string
    string s = "aaa";
 
    List<string> ans = new List<string>();
    ans.Add(s);
 
    // To generate remaining N strings
    for (int i = n - 1; i >= 0; i--) {
 
      // Find i-th string using
      // (i+1)-th string
      if(s.Length-1>=arr[i]){
        char ch = s[arr[i]];
 
        // Check if current character
        // is b
        if (ch == 'b')
          ch = 'a';
 
        // Otherwise
        else
          ch = 'b';
        char[] chr = s.ToCharArray();
        chr[arr[i]] = ch;
        s =  new string(chr);
      }
 
      // Insert the string
      ans.Add(s);
    }
 
    // Return the answer
    return ans;
  }
 
  // Driver Code
  public static void Main()
  {
 
    int []arr = { 2, 0, 3 };
    int n = arr.Length;
    List<string> ans = solve(n, arr);
 
    // Print the strings
    for (int i = ans.Count - 1; i >= 0; i--) {
      Console.WriteLine(ans[i]);
    }
  }
}        
 
// This code is contributed by SURENDRA_GANGWAR.

Javascript




<script>
 
// Javascript Program to implement
// the above approach
 
// Function to find the array of strings
function solve(n, arr)
{
    // Marks the (N+1)th string
    var s = ['a','a','a']
 
    var ans = [];
    ans.push(s.join(""));
 
    // To generate remaining N strings
    for (var i = n - 1; i >= 0; i--) {
 
        if(s.length-1>=arr[i])
        {
        // Find i-th string using
        // (i+1)-th string
        var ch = s[arr[i]];
 
        // Check if current character
        // is b
        if (ch == 'b')
            ch = 'a';
 
        // Otherwise
        else
            ch = 'b';
        s[arr[i]] = ch;
        }
        // Insert the string
        ans.push(s.join(""));
    }
 
    // Return the answer
    return ans;
}
 
// Driver Code
var arr = [ 2, 0, 3 ];
var n = arr.length;
var ans = solve(n, arr);
 
// Print the strings
for (var i = ans.length - 1; i >= 0; i--) {
    document.write( ans[i] + "<br>");
}  
 
// This code iscontributed by rutvik_56.
</script>
Output: 
bab
baa
aaa
aaa

 

Time Complexity: O(N) 
Auxiliary Space: O(N)




My Personal Notes arrow_drop_up
Recommended Articles
Page :