Construct an Array of Strings having Longest Common Prefix specified by the given Array
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>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Length of longest prefix anagram which are common in given two strings Given two strings str1 and str2 of the lengths of N and M respectively, the task is to find the length of the longest anagram string that is prefix substring of both strings. Examples: Input: str1 = "abaabcdezzwer", str2 = "caaabbttyh"Output: 6Explanation: Prefixes of length 1 of string str1 and str
8 min read
Length of longest common prefix possible by rearranging strings in a given array Given an array of strings arr[], the task is to find the length of the longest common prefix by rearranging the characters of each string of the given array. Examples: Input: arr[] = {âaabdcâ, âabcdâ, âaacdâ}Output: 3Explanation: Rearrange characters of each string of the given array such that the a
8 min read
Pair of strings having longest common prefix of maximum length in given array Given an array of strings arr[], the task is to find the pair of strings from the given array whose length of the longest common prefix between them is maximum. If multiple solutions exist, then print any one of them. Examples: Input: arr[] = {"geeksforgeeks", "geeks", "geeksforcse", } Output: (geek
15+ min read
Longest string in an array which matches with prefix of the given string Given an array of strings arr[] and Q queries where each query consists of a string str, the task is to find the longest string in the array that matches with prefix of the given string str i.e. the string must be prefix of str. Examples: Input: arr[] = {"GeeksForGeeks", "GeeksForGeeksd", "Arnab", "
8 min read
Longest Common Substring in an Array of Strings We are given a list of words sharing a common stem i.e the words originate from same word for ex: the words sadness, sadly and sad all originate from the stem 'sad'. Our task is to find and return the Longest Common Substring also known as stem of those words. In case there are ties, we choose the s
7 min read
Maximize length of the String by concatenating characters from an Array of Strings Find the largest possible string of distinct characters formed using a combination of given strings. Any given string has to be chosen completely or not to be chosen at all. Examples: Input: strings ="abcd", "efgh", "efgh" Output: 8Explanation: All possible combinations are {"", "abcd", "efgh", "abc
12 min read