I Gave a test on platform named mettl for hiring of a company.
Problem statement :
You write a love letter to you friend. However, before your friend can read it, someone else read it and rotates the characters of each word to the right K times. Find the number of words that remain the same even after this shifting of letters.
Note: There can be more than one spaces between the words.
Input specifications:
Input1: String of words
Input2: K number of times rotation happens
Output specifications:
Your function should return the numbers of correct words.
Example 1:
Input1: llohe ereth
Input 2: 2
Output: 0
Explanation: In example 1, "llohe ereth" is a rotated string with K factor 2. Hence after moving the last two letters of right to left , we get the original string as "Hello there".
Example 2:
Input1: adaada
Input 2: 3
Output: 1
Explanation: In example 2, "adaada" when rotated 3 times gives back "adaada". Hence answer is 1.
I wrote below Solution which passed the above 2 base cases, but was failing for hidden testcases (also includes time complexity testcase). Only one corner testcase passed because I was checking String input1 not to be empty. Solution is as below:
public int rotatedWords(String input1, int input2) {
int count = 0;
String arr[] = input1.split(" ");
if (input1 != null && !input1.isEmpty()) {
for (int i = 0; i < arr.length; i++) {
String s1 = arr[i] + arr[i];
int start = arr[i].length() - input2;
System.out.println("arr[i] : " + arr[i]);
String s2 = s1.substring(start, start + arr[i].length());
System.out.println("s2 : " + s2);
if (s2.equalsIgnoreCase(arr[i])) {
count++;
}
}
}
return count;
}
Ask is that , I wasn't able to understand why the hidden testcases were failing. Please help me.