Yet Another KMP Problem – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
Solutions of Algorithms Data Structures Hard HackerRank:
Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
C++ Yet Another KMP Problem HackerRank Solution
#include <stdexcept>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <cassert>
#include <cstring>
#include <cstdarg>
#include <cstdio>
#include <memory>
#include <random>
#include <cmath>
#include <ctime>
#include <functional>
#include <algorithm>
#include <complex>
#include <numeric>
#include <limits>
#include <bitset>
#include <vector>
#include <string>
#include <queue>
#include <deque>
#include <array>
#include <list>
#include <map>
#include <set>
using namespace std;
#define all(a) (a).begin(), (a).end()
#define sz(a) static_cast<int>((a).size())
#define FOR(i, a, b) for (int i(a), b_(b); i < b_; ++i)
#define REP(i, n) FOR (i, 0, n)
#define FORD(i, a, b) for (int i(a), b_(b); i >= b_; --i)
#define UNIQUE(a) sort(all(a)), (a).erase(unique(all(a)), (a).end())
#define CL(a, v) memset(a, v, sizeof a)
#define eb emplace_back
#define pb push_back
#define X first
#define Y second
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef pair<int, int> pii;
template <class T> using min_queue = priority_queue<T, vector<T>, greater<T>>;
const int INF = static_cast<int>(1e9);
const long long INF_LL = static_cast<long long>(4e18);
const double pi = acos(-1.0);
template <class T> T& smin(T& x, const T& y) { if (x > y) x = y; return x; }
template <class T> T& smax(T& x, const T& y) { if (x < y) x = y; return x; }
template <class T> T sqr(const T& x) { return x * x; }
template <class T> T gcd(T a, T b) {
for (a = abs(a), b = abs(b); a && b; a >= b ? a %= b : b %= a);
return a + b;
}
template <typename Iterator>
void print(const char* format, Iterator first, Iterator last,
const char* delimiter = " ", const char* closing = "\n") {
for (; first != last; ++first != last ? printf("%s", delimiter) : 0)
printf(format, *first);
printf("%s", closing);
}
const int A = 26;
int x[A];
string ans;
int main() {
cin.tie(NULL);
//ios_base::sync_with_stdio(false);
#ifdef LocalHost
freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
#endif
int n = 0;
REP(i, A) scanf("%d", x+i), n += x[i];
ans.reserve(n);
int a = 0;
while (x[a] == 0) ++a;
int u = a;
REP(i, A) if (x[i] > 0 && x[i] < x[u]) u = i;
ans += 'a' + u;
--x[u];
--n;
if (a == u && x[u] > 0 && x[u] <= n - x[u] + 1) {
ans += u + 'a';
--x[u];
++a;
while (x[u] > 0) {
while (x[a] == 0) ++a;
ans += a + 'a';
ans += u + 'a';
--x[a];
--x[u];
}
}
REP(i, A) ans += string(x[i], i + 'a');
printf("%s\n", ans.c_str());
#ifdef LocalHost
cerr << endl << endl << static_cast<double>(clock()) / CLOCKS_PER_SEC << endl;
#endif
return 0;
}
Java Yet Another KMP Problem HackerRank Solution
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class D2 {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = 26;
int[] f = na(n);
int nz = 0;
for(int v : f)if(v > 0)nz++;
int fsum = 0;
for(int v : f)fsum += v;
if(nz == 1){
for(int i = 0;i < n;i++){
for(int j = 0;j < f[i];j++){
out.print((char)('a'+i));
}
}
out.println();
}else{
int minf = 99999999;
int arg = -1;
for(int z = 0;z < n;z++){
if(f[z] > 0 && f[z] < minf){
minf = f[z];
arg = z;
}
}
if(f[arg] <= 2){
out.print((char)('a'+arg));
f[arg]--;
for(int i = 0;i < n;i++){
for(int j = 0;j < f[i];j++){
out.print((char)('a'+i));
}
}
out.println();
return;
}
int y = -1;
for(int z = 0;z < n;z++){
if(z != arg && f[z] > 0){
y = z;
break;
}
}
if(arg < y){
// 4 3
// 5 3
// 6 4
if(f[arg] <= fsum/2+1){
out.print((char)('a'+arg));
out.print((char)('a'+arg));
f[arg]-=2;
for(int i = arg+1;i < n;i++){
for(int j = 0;j < f[i];j++){
out.print((char)('a'+i));
if(f[arg] > 0){
out.print((char)('a'+arg));
f[arg]--;
}
}
}
out.println();
return;
}else{
out.print((char)('a'+arg));
if(f[arg] + f[y] == fsum){
for(int j = 0;j < f[y];j++){
out.print((char)('a'+y));
}
for(int j = 0;j < f[arg]-1;j++){
out.print((char)('a'+arg));
}
out.println();
return;
}
out.print((char)('a'+y));
f[arg]--; f[y]--;
for(int j = 0;j < f[arg];j++){
out.print((char)('a'+arg));
}
f[arg] = 0;
for(int x = y+1;x < n;y++){
if(f[x] > 0){
out.print((char)('a'+x));
f[x]--;
break;
}
}
for(int i = arg+1;i < n;i++){
for(int j = 0;j < f[i];j++){
out.print((char)('a'+i));
if(f[arg] > 0){
out.print((char)('a'+arg));
}
}
}
out.println();
return;
}
}else{
out.print((char)('a'+arg));
f[arg]--;
for(int i = 0;i < n;i++){
for(int j = 0;j < f[i];j++){
out.print((char)('a'+i));
}
}
out.println();
return;
}
}
}
public static int[] kmpTable(char[] str)
{
int n = str.length;
int[] kmp = new int[n+1];
kmp[0] = -1; kmp[1] = 0;
for(int i = 2, j = 0;i <= n;i++){
while(j > 0 && str[i-1] != str[j])j = kmp[j];
kmp[i] = str[i-1] == str[j] ? ++j : 0;
}
return kmp;
}
void run() throws Exception
{
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new D2().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }
}
Python 3 Yet Another KMP Problem HackerRank Solution
from string import ascii_lowercase as A
import sys
x = list(map(int, input().split()))
used = [i for i in range(26) if x[i]]
if len(used) == 0:
sys.exit()
if len(used) == 1:
print(A[used[0]] * x[used[0]])
else:
f = min(used, key=lambda a: (x[a], a))
used = [a for a in used if a != f]
if x[f] == 1:
print(A[f] + ''.join(A[c]*x[c] for c in used))
elif f > used[0]:
x[f] -= 1
print(A[f] + ''.join(A[c]*x[c] for c in range(26)))
elif 2*(x[f]-2) <= sum(x)-2:
res = 2*A[f]
b = ''.join(A[c]*x[c] for c in used)
x[f] -= 2
i = 0
while x[f]:
res += b[i] + A[f]
i += 1
x[f] -= 1
res += b[i:]
print(res)
else:
x[f] -= 1
x[used[0]] -= 1
print(A[f] + A[used[0]] + A[f]*x[f] + ''.join(A[c]*x[c] for c in used))
Python 2 Yet Another KMP Problem HackerRank Solution
# Enter your code here. Read input from STDIN. Print output to STDOUT
C = map(int, raw_input().split())
S = sum(C)
L = [[i, C[i]] for i in xrange(26) if C[i]]
n = len(L)
if not n:
print ''
elif n == 1:
print chr(97+L[0][0]) * S
else:
idx = -1
mincnt = S + 1
for i, cnt in L:
if cnt < mincnt:
idx, mincnt = i, cnt
index = L.index([idx, mincnt])
res = [chr(97+idx)]
L[index][1] -= 1
if index == 0:
tmp = chr(97+idx) + chr(97+L[1][0])
res.append(tmp * (mincnt-1))
res.append(chr(97+L[1][0]) * (L[1][1] - mincnt + 1))
for i in xrange(2, n):
res.append(chr(97+L[i][0]) * L[i][1])
else:
for i, cnt in L:
res.append(chr(97+i) * cnt)
print ''.join(res)
Warmup
Implementation
Strings
Sorting
Search
Graph Theory
Greedy
Dynamic Programming
Constructive Algorithms
Bit Manipulation
Recursion
Game Theory
NP Complete
Debugging
Leave a comment below