Only q is getting printed out in my String Window code

Here’s my approach to the question -

  1. I make a hashmap of character and index
  2. I store all the characters of str2 onto my map with 0 as default
  3. I check if str1 contains the characters in the hashmap and if it does then I update the index on the hashmap with the current index
  4. I find the min and max values of the hashmap
  5. My resultant substring would be from the min index to the max index of str1

I dry run the code on my book and it’s supposed to work but the only output I’m getting is q for the given example.

Here’s my code - https://ide.codingblocks.com/s/236667

@lousybrick,
If the input is:
qwerty asdfgh qazxsw
qas

Your str1 is qwerty and str2 is being stored as asdfgh. The input breaks after there is a space in the input string. Also, you need to print “No String” and not “no such window can exist”

I’ve noticed that none of my chars of string1 are getting adding to the hashmap. Could you please check the code and tell me where’s my mistake.

@lousybrick,

 String str1 = "";
		str1    += sc.nextLine();
		String str2 = "";
		str2 += sc.nextLine();

Use the above code for input. Also, you need to modify your approach.

Suggested approach:

  1. First check if length of string is less than the length of given pattern, if yes then "no such window can exist ".
  2. Store the occurrence of characters of given pattern in a hashMap.
  3. Start matching the characters of pattern with the characters of string i.e. increment count if a character matches
  4. Check if (count == length of pattern ) this means a window is found
  5. If such window found, try to minimize it by removing extra characters from beginning of current window.
  6. Update min_length
  7. Print the minimum length window.

Also, you need to print “No String” and not “no such window can exist”

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.