Search code examples
javaregexstringstringbuildertestcase

Why all the test cases are not getting passed for the below question?


The Coding Question which I am trying to solve is this. I tried to solve but not all the test cases passed I am not able to find what could be the reason?

Identify possible words: Detective Bakshi while solving a case stumbled upon a letter which had many words whose one character was missing i.e. one character in the word was replaced by an underscore. For e.g.“Fi_er”. He also found thin strips of paper which had a group of words separated by colons, for e.g. “Fever:filer:Filter:Fixer:fiber:fibre:tailor:offer”. He could figure out that the word whose one character was missing was one of the possible words from the thin strips of paper. Detective Bakshi has approached you (a computer programmer) asking for help in identifying the possible words for each incomplete word.

You are expected to write a function to identify the set of possible words. The function identifyPossibleWords takes two strings as input where,

input1 contains the incomplete word, and input2 is the string containing a set of words separated by colons.

The function is expected to find all the possible words from input2 that can replace the incomplete word input1, and return the result in the format suggested below.

Example1 -

input1 = “Fi_er” input2 = “Fever:filer:Filter:Fixer:fiber:fibre:tailor:offer”

output string should be returned as “FILER:FIXER:FIBER” Note that –

The output string should contain the set of all possible words that can replace the incomplete word in input1 all words in the output string should be stored in UPPER-CASE all words in the output string should appear in the order in which they appeared in input2, i.e. in the above example we have FILER followed by FIXER followed by FIBER. While searching for input1 in input2, the case of the letters are ignored, i.e “Fi_er” matches with “filer” as well as “Fixer” as well as “fiber”. IMPORTANT: If none of the words in input2 are possible candidates to replace input1, the output string should contain the string “ERROR-009” Assumption(s):

Input1 will contain only a single word with only 1 character replaced by an underscore “_” Input2 will contain a series of words separated by colons and NO space character in between Input2 will NOT contain any other special character other than underscore and alphabetic characters.

My solution for the question is:

 import java.io.*;
import java.util.*;
class UserMaincode
{
   public String indentifyPossibleWords(String input1, String input2)
{
       input1=input1.toUpperCase();
       input2=input2.toUpperCase();

       String arr1[]=input1.split("_");
       String arr2[]=input2.split(":");
       StringBuilder sb=new StringBuilder("");
       for(int i=0;i<arr2.length;i++){
           if(arr2[i].matches(arr1[0]+"."+arr1[1])){
               sb.append(arr2[i]+":");
           }
       }

       if(sb.length()!=0){
           sb.deleteCharAt(sb.length()-1);
       }

       String s=sb.toString();
       if(s==""){
           return "ERROR-009";
       }
       return s;
}
}

But some of hidden testcases did not pass. Where could be the problem.

I found one code from web which passes all the test case. Please refer this link for that.

https://www.csinfo360.com/2020/01/cracking-coding-interview-step-11.html


Solution

  • There are many ways to achieve the result as expected in the mentioned problem. Since; you've mentioned regex in the tag; therefore I'll try to provide a possible solution using regex. Although; this can be achieved without them too.

    Proposed Procedure:

    
     1. Create a regex from the given input1 i.e. replace the _ present anywhere inside input1 with regex dot (.) meta-character.
     2. Split the string based on :.
     3. Keep a count of length of spliced array of input2.
     4. for each item in input2:
          5. match using the regex formed in step 1
                If successful
                  append to upper-cased result.
                else:
                     increment the counter.
    6. if counter == length of spliced array i.e. no match found
        return "ERROR-009"
       else   
        return the appended result.
    

    Implementation of the above procedure in java:

    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    public class Main
    {
        public static void main(String[] args) {
            System.out.println(identifyPossibleWords("Fi_er", "Fever:filer:Filter:Fixer:fiber:fibre:tailor:offer"));
    //      Fever:fiqqer:Filter:Fixxer:fibber:fibre:tailor:offer return ERROR-009
        }
    
        public static String identifyPossibleWords(String input1, String input2){
            input1 = input1.replace("_", ".");
            StringBuilder sb = new StringBuilder();
            int counter = 0;
            int lengthOfInput2 = input2.split(":").length;
            final Pattern pattern = Pattern.compile(input1, Pattern.CASE_INSENSITIVE);
            for(String str: input2.split(":")){
                Matcher matcher = pattern.matcher(str);
                if(matcher.matches())sb.append(matcher.group(0).toUpperCase() + "\n"); // \n to print in new line. You can edit the code accordingly.
                else counter++;
            }
            if(counter == lengthOfInput2)return "ERROR-009";
            return sb.toString();
        }
    }
    
    

    You can find the sample run of the above implementation in here.