Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 16, 2023 06:56 am GMT

Sparse Arrays hackerrank solution in java

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 'matchingStrings' function below.     *     * The function is expected to return an INTEGER_ARRAY.     * The function accepts following parameters:     *  1. STRING_ARRAY stringList     *  2. STRING_ARRAY queries     */    public static List<Integer> matchingStrings(List<String> stringList, List<String> queries) {        HashMap<String,Integer> hm = new HashMap<>();        for(int i=0;i<stringList.size();i++){            String s = stringList.get(i);             hm.put(s,hm.getOrDefault(s,0)+1);        }        List<Integer> res = new ArrayList<>();        for(int i=0;i<queries.size();i++){            String s = queries.get(i);            if(hm.containsKey(s)){                res.add(hm.get(s));            }else{                res.add(0);            }         }        return res;    }}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 stringListCount = Integer.parseInt(bufferedReader.readLine().trim());        List<String> stringList = IntStream.range(0, stringListCount).mapToObj(i -> {            try {                return bufferedReader.readLine();            } catch (IOException ex) {                throw new RuntimeException(ex);            }        })            .collect(toList());        int queriesCount = Integer.parseInt(bufferedReader.readLine().trim());        List<String> queries = IntStream.range(0, queriesCount).mapToObj(i -> {            try {                return bufferedReader.readLine();            } catch (IOException ex) {                throw new RuntimeException(ex);            }        })            .collect(toList());        List<Integer> res = Result.matchingStrings(stringList, queries);        bufferedWriter.write(            res.stream()                .map(Object::toString)                .collect(joining("
")) + "
" ); bufferedReader.close(); bufferedWriter.close(); }}

Original Link: https://dev.to/realnamehidden1_61/sparse-arrays-hackerrank-solution-in-java-2lic

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To