2

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.

ASharma7
  • 726
  • 3
  • 8
  • 27
  • 1
    Try a few more test cases of your own. Have you tested that the case mentioned in their note works? – tgdavies Jan 19 '21 at 00:47
  • Yes both of the testcases were working fine. Checked on my machine as well. i have also mentioned that in question that base testcases were getting passed. – ASharma7 Jan 19 '21 at 00:49
  • 1
    Try to imagine some things which the hidden tests cases might check, e.g. the requirement which is specifically pointed out in the note, and try your code with them. – tgdavies Jan 19 '21 at 00:58
  • 1
    Think how actual letter will look like. Maybe there are some other symbols you need to handle. Like comma and dot. What about other special characters? Numbers? Tabs? New lines? – Monitoria Jan 19 '21 at 01:04
  • @Monitoria yes that night be the case, i should have removed the original string containing special characters – ASharma7 Jan 19 '21 at 01:23

10 Answers10

0

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))
0
#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;
}
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

  • Please explain what was wrong with the code in the question and how this code solves the problem. – Null Feb 19 '21 at 22:06
0
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;
    }

}
Frightera
  • 4,773
  • 2
  • 13
  • 28
  • It seems K means how many characters he shifted left to right or right to left for each word in sentence, try this it may pass other test cases. – Arvind Sharma Apr 09 '21 at 12:10
0
$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;
user3599005
  • 69
  • 1
  • 3
0

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))
0
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;
}
}
swapnil
  • 280
  • 2
  • 10
0

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))
Kshitij
  • 1
  • 1
0

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.

-1

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);
      }
    }
  • 1
    Please read [How to answer](https://stackoverflow.com/help/how-to-answer) and update your answer. – fartem Apr 15 '21 at 05:39