Algorithm
Problem Name: Data Structures -
In this HackerRank in Data Structures -
We're going to make our own Contacts application! The application must perform two types of operations:
add name
, where name is a string denoting a contact name. This must store name as a new contact in the application.find partial
, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting with partial and print the count on a new line.
Given n sequential add and find operations, perform each operation in order.
Example
Operations are requested as follows:
add ed add eddie add edward find ed add edwina find edw find a
Three add operations include the names 'ed', 'eddie', and 'edward'. Next, find ed matches all 3 names. Note that it matches and counts the entire name 'ed'. Next, add 'edwina' and then find 'edw'. 2 names match: 'edward' and 'edwina'. In the final operation, there are 0 names that start with 'a'. Return the array [3,2,0]
Function Description
Complete the contacts function below.
contacts has the following parameters:
- string queries[n]: the operations to perform
Returns
- int[]: the results of each find operation
Input Format
The first line contains a single integer, n the number of operations to perform (the size of queries[])
Each of the following n lines contains a string queries[i]
Constraints
- 1 <= n <= 10**5
- 1 <= length of name <= 21
- 1 <= length of partial <= 21
- name and partial contain lowercase English letters only.
- The input does not have any duplicate name for the operation.
Sample Input
STDIN Function ----- -------- 4 queries[] size n = 4 add hack queries = ['add hack', 'add hackerrank', 'find hac', 'find hak'] add hackerrank find hac find hak
Sample Output
2
0
Explanation
- Add a contact named
hack
. - Add a contact named
hackerrank
. - Find the number of contact names beginning with
hac
. Both name start withhac
, add 2 to the return array. - Find the number of contact names beginning with
hak
. neither name starts withhak
, add 0 to the return array.
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
unordered_map < string,int> s;
int main(int argc, char** argv) {
int n; cin>>n;
while(n--){
string t,x; cin>>t>>x;
if(t=="add"){
for(int i = 1; i <= x.length(); i++){
s[x.substr(0,i>]++;
}
}else{
cout << s[x] << endl;
}
}
return 0;
}
Copy The Code &
Try With Live Editor
#3 Code Example with Javascript Programming
Code -
Javascript Programming
'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', function(inputStdin) {
inputString += inputStdin;
});
process.stdin.on('end', function() {
inputString = inputString.split('\n');
main();
});
function readLine() {
return inputString[currentLine++];
}
/*
* Complete the 'contacts' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts 2D_STRING_ARRAY queries as parameter.
*/
function contacts(queries) {
class TrieNode {
children = {}
isWord = false
count = 0 // -- we count while adding to be fast enough
}
class Trie {
root
constructor() {
this.root = new TrieNode()
}
insert(word) {
let node = this.root
let last = node
for (const l of word) {
if (!node.children[l]) {
node.children[l] = new TrieNode();
}
last = node
node = node.children[l]
node.count++ // counting while adding
}
last.isWord = true;
}
findNode(word) {
let node = this.root
let last = node
for (const l of word) {
if (!node.children[l])
return false
last = node
node = node.children[l]
}
return node
}
// count(node) { -- this is not fast enough
// if (!node) return 0
// let count = 0
// if (node.isWord) count++
// for (const l in node.children)
// count += this.count(node.children[l])
// return count
// }
}
let trie = new Trie()
let ret = []
for (const [command, word] of queries) {
if (command === 'add') {
trie.insert(word)
} else if (command === 'find') {
let node = trie.findNode(word)
//let count = trie.count(node) -- this is not fast enough
let count = node.count || 0
ret.push(count)
}
}
return ret
}
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const queriesRows = parseInt(readLine().trim(), 10);
let queries = Array(queriesRows);
for (let i = 0; i < queriesRows; i++) {
queries[i] = readLine().replace(/\s+$/g, '').split(' ');
}
const result = contacts(queries);
ws.write(result.join('\n') + '\n');
ws.end();
}
Copy The Code &
Try With Live Editor
#4 Code Example with Python Programming
Code -
Python Programming
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'contacts' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts 2D_STRING_ARRAY queries as parameter.
#
def contacts(queries):
mpp, res = {}, []
for cmd,word in queries :
if cmd == 'add' :
for i in range(len(word)) :
mpp[word[:i+1]] = mpp.get(word[:i+1],0)+1
else :
ans = 0
ans += mpp.get(word,0)
res.append(ans)
return res
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
queries_rows = int(input().strip())
queries = []
for _ in range(queries_rows):
queries.append(input().rstrip().split())
result = contacts(queries)
fptr.write('\n'.join(map(str, result)))
fptr.write('\n')
fptr.close()
Copy The Code &
Try With Live Editor
#4 Code Example with Java Programming
Code -
Java Programming
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'contacts' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts 2D_STRING_ARRAY queries as parameter.
*/
public static List < Integer> contacts(List results = new ArrayList();
Map namePartials = new HashMap();
for (List < String> list : queries) {
String operation = list.get(0);
String text = list.get(1);
if (operation.equals("add")) {
for (int i = 1; i < = text.length(); ++i) {
String partial = text.substring(0, i);
Integer count = namePartials.get(partial);
if (count == null) {
count = 0;
}
count++;
namePartials.put(partial, count);
}
} else if (operation.equals("find")) {
Integer count = namePartials.get(text);
if (count == null) {
count = 0;
}
results.add(count);
} else {
throw new RuntimeException("operation " + operation + " is not supported!");
}
}
return results;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int queriesRows = Integer.parseInt(bufferedReader.readLine().trim());
List < List();
IntStream.range(0, queriesRows).forEach(i -> {
try {
queries.add(
Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.collect(toList())
);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
List < Integer> result = Result.contacts(queries);
bufferedWriter.write(
result.stream()
.map(Object::toString)
.collect(joining("\n"))
+ "\n"
);
bufferedReader.close();
bufferedWriter.close();
}
}
Copy The Code &
Try With Live Editor