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.

HackerRank String Construction Solution
HackerRank String Construction Solution

HackerRank String Construction

Task

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

Subtasks

  • 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) {
	// your code goes here
	int t;scanf("%d",&t);
	while(t--)
{	char inp[100005];
	int i,c=0,l,arr[26];
	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())
            {
                uniqueChars.add(c);
            }
            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();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

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

function main() {
    var n = parseInt(readLine());
    for(var a0 = 0; a0 < n; a0++){
        var s = readLine();
        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]) {
        val t = readInt
        (1 to t).foreach(_ => {
            val str = readLine
            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
    readln(t);
    for i:=1 to t do 
    begin
        readln(s);
        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.

Sharing Is Caring