Love letter String rotation company test programming question base testcase passed, hidden testcase failing

Viewed 17811

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.

10 Answers

This is the solutionin Python 3

def rotatedWords(cls, input1,input2):
    rotateString = input1.split(' ')
    count = 0
    for i in range(1,input2+1):
        for j in range(len(rotateString)):
            rotateString[j]= rotateString[j][1:]+rotateString[j][0]
        
    actualWrod = input1.split(' ')

    for i in range(len(rotateString)):
        for j in range(len(actualWrod)):
            if rotateString[i]==actualWrod[j]:
                count+=1
    return count

print(rotatedWords(1,"adaada",3))
print(rotatedWords(1,"llohe ereth",2))
#include<bits/stdc++.h>
using namespace std;
 
// In-place rotates s towards left by d
void leftrotate(string &s, int d)
{
    reverse(s.begin(), s.begin()+d);
    reverse(s.begin()+d, s.end());
    reverse(s.begin(), s.end());
}
 
// In-place rotates s towards right by d
int rightrotate(string &s, int d)
{  
  string s1="";
  int i=0,flag=0;
  vector<string>str;
  while(s[i]!='\0'){
    if(s[i] != ' '){
      s1 = s1+s[i];
      i++;
    }
    else{
      if(s1 != ""){ //checking for extra space
        str.push_back(s1);
        s1 = "";
        i++;
      }
      else
        i++;
    }
  }
  str.push_back(s1);
  vector<string>str2;
  for(int i=0;i<str.size();i++){
    str2.push_back(str[i]);
  }
  for(int i=0;i<str.size();i++){
    leftrotate(str[i], str[i].length()-d);
  }
  for(int i=0;i<str.size();i++){
    if(str[i] == str2[i]){
      flag++;
    }
  }
  return flag;
}
 
int main()
{
 
    string str1;
    getline(cin, str1);
    int k;
    cin>>k;
    cout<<rightrotate(str1, k);
    return 0;
}
 def check(_str):
    length = len(_str)
    for i in range(length):
        if (_str[i]!=_str[(input2+i)%length]):
            return 0
    return 1
words = input1.split()
ans = list(map(check,words))
print(sum(ans))

code in Python

package fun;

public class Test1 {

    public static void main(String[] args) {
        System.out.println(rotatedWords("llohe ereth", 2));
        System.out.println(rotatedWords("adaada", 3));
    }

    public static 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++) {
                System.out.println("Orginal Word :" + arr[i]);
                int start = arr[i].length() - input2;
                String s1 = arr[i].substring(start);
                System.out.println("s1 : " + s1);
                String s2 = arr[i].substring(0, start);
                System.out.println("s2 : " + s2);
                System.out.println("New Word : " + s1 + s2);
                if ((s1 + s2).equals(arr[i])) {
                    count++;
                }
            }
        }
        return count;
    }

}
$str = "Hello Friend";
$kTime = 5;
$arr = explode (' ',$str);
$sizeOfArr = count($arr);
$char = array();
$count = 0;
foreach($arr as $k=>$v)
{
  $ln = $kTime%strlen($v);
  $char = substr($v,$ln).substr($v,0,$ln);
  if($v == $char)
    {
      $count++;
    }
}
echo 'Number of Original word after rotation found : '.$count;

This is the solution in Python 3 for the right move

def rotatedWords(cls, input1,input2):
    rotate_string = input1.split(' ') # converting string to list
    count = 0
    for i in range(1,input2+1):
        for j in range(len(rotate_string)):
            rotate_string[j]= rotate_string[j][-1]+rotate_string[j][0:-1]
        
    actual_word = input1.split(' ')

    for i in range(len(rotate_string)):
        for j in range(len(actual_word)):
            if rotate_string[i]==actual_word[j]:
                count+=1
    return count

print(rotatedWords(1,"adaada",3))
print(rotatedWords(1,"llohe ereth",2))
package com.code;
public class LoveLetter {
public static void main(String args[])
{
    String str="llohe ereth";
    int n=2;
    solution(str,n);
}
public static void solution(String str,int n)
{
    int l=str.length();
    String a[]=str.split("\\s+");
    String str1="";
    int c=0;
    for(int i=0;i<a.length;i++)
    {
        String s=a[i];
        String k=rightrotate(s,n);
        if(a[i].equals(k)){
            c++;
        }
        else
            continue;
    }
    System.out.println(c);
}
static String rightrotate(String str, int d)
{
    d=str.length()-d;
    String ans = str.substring(d) + str.substring(0, d);
    return ans;
}
}

It is given that someone rotates the characters of each word from left to right K times.So,if we want to know the original words,we have to rotate each characters from right to left K times

def rotatedWords(cls, input1, input2):
    original_string = input1.split(' ')  # the string is split into list
    count = 0  # for counting the words that remains same even after rotation

    for i in range(0, input2):
        for j in range(len(original_string)):
            original_string[j] = original_string[j][-1]+original_string[j][0:-1]  # taking the last character and all characters from first to second last of each word,then concatenating them

    given_string = input1.split(' ')

    for i in range(len(given_string)):
        if original_string[i] == given_string[i]:   #comparing each words from both lists
            count += 1
    return count

print(rotatedWords(1,"adaada", 3))
print(rotatedWords(1,"llohe ereth", 2))

Problem Statement tells that the space between words can be one or more. So you will pass all test cases if split removes all spaces. Use input1.split("\\s+") regex expression instead.

Java solution*

 import java.util.Scanner;
    public class Main
    {
     //rotate every word of the given string by the given rotation value
      public static String rotate_string (String str, int d) 
      {
        String ans = str.substring (d) + str.substring (0, d);
          return ans;
      }
      public static void rotated (String str, int rotated)
      {
        String[]wordsarr = str.split ("\\s"); // convert string to an array of strings.
        String rotatedarr[] = new String[wordsarr.length]; // to store the rotated array.
        for (int i = 0; i < wordsarr.length; i++)
          {
        rotatedarr[i] = rotate_string(wordsarr[i], wordsarr[i].length () - rotated);
          }
        int count = 0;
        for (int i = 0; i < wordsarr.length; i++)
          {
        if (wordsarr[i].equals (rotatedarr[i]))
          {
            count++;
          }
          }
        System.out.println (count);
      }

      public static void main (String[]args)
      {
        Scanner s= new Scanner(System.in);
        String str= s.nextLine(); //input string
        int rotate_by= s.nextInt(); 
        rotated(str,rotate_by);
      }
    }
Related