## Wednesday, 6 June 2012

### How to find a String is a circular representation of other String

Many Interviewer may ask this question, "How will you find a string is circular of other String." Suppose we have two strings A and B. we have to check or tell that the B is circular of String A or not. A and B can be any string. If we think for a while , we will get the different solutions like using nested loop we can compare each alphabet of B and A. Other way is we can use the linked list. For both approaches time and space complexity would be high. If you told above solution your answer would be right but it is not optimized . Interviewer might be expecting optimize answer, our answer won't be impress to interviewer.

Now we have to think how we can optimize the time and space complexity for a given problem, so our answer can imprint the image of us on mind of interviewer. To do the needful in the optimize way, we have a solution. Solution is

public class CircularString{
public static void main(String[] args) {
String A="ABCDEFG";
String B="FGABCDE";
String C=A+A;//ABCDEFGABCDEFG
boolean status= C.contains(B);
System.out.println(status);
}
}

In the above example complexity would always be 1. Here C represent ABCDEFGABCDEFG. B conatains "FGABCDE". highlight portion of C equals to the String B. If you tell this solution instead of other solution, it will help you to crack the interview.

1. 2. 3. 4. 