Password Cracker
Problem Statement :
There are n users registered on a website CuteKittens.com. Each of them has a unique password represented by pass[1], pass[2], ..., pass[N]. As this a very lovely site, many people want to access those awesomely cute pics of the kittens. But the adamant admin does not want the site to be available to the general public, so only those people who have passwords can access it. Yu, being an awesome hacker finds a loophole in the password verification system. A string which is a concatenation of one or more passwords, in any order, is also accepted by the password verification system. Any password can appear or more times in that string. Given access to each of the passwords, and also have a string , determine whether this string be accepted by the password verification system of the website. If all of the string can be created by concatenating password strings, it is accepted. In this case, return the passwords in the order they must be concatenated, each separated by a single space on one line. If the password attempt will not be accepted, return 'WRONG PWASSWORD'. Concatenate the passwords in index order to match 'abba', to match 'baab', to match 'abab' or to match $baba'. No combination of 1 or more passwords can be concatenated to match 'aba'. Return 'WRONG PASSWORD'. Function Description Complete the passwordCracker function in the editor below. passwordCracker has the following parameters: - string passwords[n]: a list of password strings - string loginAttempt: the string to attempt to create Returns - string: Return the passwords as a single string in the order required for the password to be accepted, each separated by a space. If it is not possible to form the string, return the string WRONG PASSWORD. Input Format The first line contains an integer t, the total number of test cases. Each of the next sets of three lines is as follows: - The first line of each test case contains n, the number of users with passwords. - The second line contains n space-separated strings, passwords[i], that represent the passwords of each user. - The third line contains a string, loginAttempt, which Yu must test for acceptance.
Solution :
Solution in C :
In C :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void solve(int idx);
char a[10][11],str[2001];
int dp[2000],N,len;
int main(){
int T,i;
scanf("%d",&T);
while(T--){
memset(dp,-1,sizeof(dp));
scanf("%d",&N);
for(i=0;i<N;i++)
scanf("%s",&a[i][0]);
scanf("%s",str);
len=strlen(str);
solve(0);
if(dp[0]==-2)
printf("WRONG PASSWORD\n");
else{
i=0;
while(i<len){
printf("%s ",&a[dp[i]][0]);
i+=strlen(&a[dp[i]][0]);
}
printf("\n");
}
}
return 0;
}
void solve(int idx){
int i;
if(idx>=len || dp[idx]!=-1)
return;
for(i=0;i<N;i++)
if(!strncmp(&str[idx],&a[i][0],strlen(&a[i][0])))
if(!str[idx+strlen(&a[i][0])]){
dp[idx]=i;
break;
}
else{
solve(idx+strlen(&a[i][0]));
if(dp[idx+strlen(&a[i][0])]>=0){
dp[idx]=i;
break;
}
}
if(dp[idx]==-1)
dp[idx]=-2;
return;
}
Solution in C++ :
In C++ :
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_set>
using namespace std;
void putReverses(vector< string > &words, unordered_set< string > &wordSet)
{
int n = words.size();
for(int i = 0;i != n;i++)
{
reverse(words[i].begin(), words[i].end());
wordSet.insert(words[i]);
}
}
vector< string > findComb(const string &str, vector< string > &words)
{
vector< string > result;
int m = str.size();
unordered_set< string > wordSet;
putReverses(words, wordSet);
vector< char > valid(m + 1, 0);
valid[0] = 1;
vector< int > validLens(m + 1);
for(int len = 1;len <= m;len++)
{
int i = len - 1;
string word;
for(int j = i;j >= 0;j--)
{
word += str[j];
if(valid[j] && wordSet.find(word) != wordSet.end())
{
valid[len] = 1;
validLens[len] = len - j;
break;
}
}
}
if(valid[m] == 0) { return result; }
int len = m;
while(len)
{
result.push_back(str.substr(len - validLens[len], validLens[len]));
len -= validLens[len];
}
reverse(result.begin(), result.end());
return result;
}
int main()
{
int T, N;
string word, str;
cin >> T;
while(T--)
{
cin >> N;
vector< string > words;
while(N--)
{
cin >> word;
words.push_back(word);
}
cin >> str;
vector< string > comb(findComb(str, words));
if(comb.empty()) { cout << "WRONG PASSWORD"; }
else
{
int m = comb.size();
cout << comb[0];
for(int i = 1;i != m;i++)
{
cout << " " << comb[i];
}
}
cout << endl;
}
return 0;
}
Solution in Java :
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 sc = new Scanner(System.in);
int N = sc.nextInt();
for(int i = 0; i < N; i++){
int cnt = sc.nextInt();
Set<String> dict = new HashSet<String>();
Map<String,Boolean> map = new HashMap<String,Boolean>();
for(int j = 0; j < cnt; j++){
dict.add(sc.next());
}
String s = sc.next();
boolean res = dfs(s,dict,"",map);
if (!res){
System.out.println("WRONG PASSWORD");
}
}
}
private static boolean dfs(String s, Set<String> dict, String path,Map<String,Boolean> map){
if (s == null || s.length() == 0){
System.out.println(path.trim());
return true;
}
if (map.containsKey(s)){
return map.get(s);
}
for(String word : dict){
if (!s.startsWith(word)) continue;
if (dfs(s.substring(word.length()),dict,path + word + " ",map)){
map.put(s,true);
return true;
}
}
map.put(s,false);
return false;
}
}
Solution in Python :
In Python3 :
t = int(input().strip())
def solve(ws, x):
dead_end = set()
stack = []
stack.append(([], x))
while stack:
acc, cur = stack.pop()
if cur == "":
return acc
is_dead_end = True
for w in ws:
if cur.startswith(w):
cur2 = cur[len(w):]
if cur2 in dead_end:
continue
is_dead_end = False
acc2 = acc[:]
acc2.append(w)
stack.append((acc2, cur2))
if is_dead_end:
dead_end.add(cur)
for ti in range(t):
n = int(input().strip())
ws = [tmp for tmp in input().strip().split(' ')]
x = input().strip()
answer = solve(ws, x)
if answer is None:
print("WRONG PASSWORD")
else:
print(" ".join(answer))
View More Similar Problems
Counting On a Tree
Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n
View Solution →Polynomial Division
Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie
View Solution →Costly Intervals
Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the
View Solution →The Strange Function
One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting
View Solution →Self-Driving Bus
Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever
View Solution →Unique Colors
You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti
View Solution →