top of page
Search
Writer's pictureAbhinaw Tripathi

Amazon Interview Question:Check if a string can be obtained by rotating another string 2 places in J


Given two strings, the task is to find if a string can be obtained by rotating another string two places. Input : string1 = "amazon" string2 = "azonam" // rotated anti-clockwise Output : Yes Input : string1 = "amazon" string2 = "onamaz" // rotated clockwise Output : Yes Solution: 1- There can be only two cases: a) Clockwise rotated b) Anti-clockwise rotated 2- If clockwise rotated that means elements are shifted in right. So, check if a substring[2.... len-1] of string2 when concatenated with substring[0,1] of string2 is equal to string1. Then, return true. 3- Else, check if it is rotated anti-clockwise that means elements are shifted to left. So, check if concatenation of substring[len-2, len-1] with substring[0....len-3] makes it equals to string1. Then return true. 4- Else, return false. Sample Code: /** * @author Abhinaw.Tripathi * */ public class RotatingString { /** * @param args */ public static void main(String[] args) { String str1 = "amazon"; String str2 = "azonam"; isRotated(str1, str2) ; } public static boolean isRotated(String str1, String str2) { String s = str1 + str2; if(s.contains(str2)) return true; else return false; } } Output: Yes


27 views0 comments

Recent Posts

See All
bottom of page