# HackerRank String Construction Solution

Hello Programmers, In this post, you will learn how to solve HackerRank String Construction Solution. This problem is a part of the HackerRank Algorithms Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

## HackerRank String Construction

Amanda has a string of lowercase letters that she wants to copy to a new string. She can perform the following operations with the given costs. She can perform them any number of times to construct a new string p:

• Append a character to the end of string p at a cost of 1 dollar.
• Choose any substring of p and append it to the end of p at no charge.

Given n strings s[i], find and print the minimum cost of copying each s[i] to p[i] on a new line.

For example, given a string s = abcabc, it can be copied for 3 dollars. Start by copying ab and c individually at a cost of 1 dollar per character. String p = abc at this time. Copy p[0 : 2] to the end of p at no cost to complete the copy.

Function Description

Complete the stringConstruction function in the editor below. It should return the minimum cost of copying a string.

stringConstruction has the following parameter(s):

• s: a string

### Input Format

The first line contains a single integer n, the number of strings.
Each of the next n lines contains a single string, s[i].

### Constraints

• 1 <= n <= 5
• 1 <= |s[i]| <= 105

• 1 <= |s[i]| <= 103 for 45% of the maximum score.

### Output Format

For each string s[i] print the minimum cost of constructing a new string p[i] on a new line.

Sample Input

2
abcd
abab

Sample Output

4
2

Explanation

Query 0: We start with s = “abcd and p = “”.

1. Append character a to p at a cost of 1 dollar, p = “a.
2. Append character b to p at a cost of 1 dollar, p = “ab.
3. Append character c to p at a cost of 1 dollar, p = “abc.
4. Append character d to p at a cost of 1 dollar, p = “abcd”.

Because the total cost of all operations is 1 + 1 + 1 + 1 = 4 dollars, we print 4 on a new line.

Query 1: We start with s = “abab” and p = “”.

1. Append character ‘a’ to p at a cost of 1 dollar, p = “a.
2. Append character ‘b’ to p at a cost of 1 dollar, p = “ab.
3. Append substring “ab” to p at no cost, p = “abab”.

Because the total cost of all operations is 1 + 1 = 2 dollars, we print 2 on a new line.

Note

A substring of a string S is another string S that occurs “in” S (Wikipedia). For example, the substrings of the string “abc” are “a“, “b” ,”c“, “ab“, “bc“, and “abc“.

## HackerRank String Construction Solution

### HackerRank String Construction Solution in C

```#include <stdio.h>
#include <string.h>

int main(void) {
int t;scanf("%d",&t);
while(t--)
{	char inp;
int i,c=0,l,arr;
for(i=0;i<26;i++)arr[i]=0;
scanf("%s",inp);
l=strlen(inp);
for(i=0;i<l;i++)
{
arr[inp[i]-'a']+=1;
}
for(i=0;i<26;i++)
if(arr[i]!=0)
c+=1;
printf("%d\n",c);}
return 0;
}
```

### HackerRank String Construction Solution in Cpp

```#include <cmath>
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
long t;
cin>>t;
while(t--)
{long r=0;
string s;
cin>>s;
vector<char> m;
for(long i=0;i<s.length();++i)
{
if(find(m.begin(),m.end(),s[i])==m.end()) m.push_back(s[i]);

}
cout<<m.size()<<endl;
}
return 0;
}```

### HackerRank String Construction Solution in Java

```import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int a0 = 0; a0 < n; a0++){
String s = in.next();

Set<Character> uniqueChars = new HashSet<>();
for(char c : s.toCharArray())
{
}
System.out.println(uniqueChars.size());
}
}
}```

### HackerRank String Construction Solution in Python

```import sys

def stringConstruction(s):
return len(set(s))

if __name__ == "__main__":
q = int(input().strip())
for a0 in range(q):
s = input().strip()
result = stringConstruction(s)
print(result)```

### HackerRank String Construction Solution using JavaScript

```process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
input_stdin += data;
});

process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});

return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function main() {
for(var a0 = 0; a0 < n; a0++){
var m = {};
var ans = 0;
for (var i = 0; i < s.length; i++) {
if (!m[ s[i]  ]) ans++;
m[ s[i] ] = true;

}
console.log(ans)
}

}```

### HackerRank String Construction Solution in Scala

```import scala.io.StdIn._
object Solution {

def main(args: Array[String]) {
(1 to t).foreach(_ => {
println(str.groupBy(identity).size)
})
}
}```

### HackerRank String Construction Solution in Pascal

```var s:ansistring;
t,sl,i,j:longint;
c:char;
gt:array['a'..'z'] of longint;
begin
for i:=1 to t do
begin
for c:='a' to 'z' do gt[c]:=0;
for j:=1 to length(s) do gt[s[j]]:=1;
sl:=0;
for c:='a' to 'z' do sl:=sl+gt[c];
writeln(sl);
end;
end.
```

Disclaimer: This problem (HackerRank String Construction ) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.

## FAQ:

1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume.

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite.

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedia

Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.