FB Interview Question: Periodic String

Image placeholder 9899

(This question has been seen in the interviews of the following companies: Facebook)

Find whether string S is periodic.
Periodic indicates S = nP.
e.g.
S = "ababab", then n = 3, and P = "ab"
S = "xxxxxx", then n = 1, and P = "x"
S = "aabbaaabba", then n = 2, and P = "aabba"

follow up:
Given string S, find out the P (repetitive pattern) of S.

//Solution to question O(n)

   boolean isPeriod(String s) {
        StringBuilder str = new StringBuilder(s   s);
        str.deleteCharAt(0);
        str.deleteCharAt(str.length() - 1);
        return strStr(str.toString(), s); //KMP strStr(T, S) to find if T has S in it.
    }

    //Solution to follow-up
    //This method looks for the repeating pattern in string
    private static String getPeriod(String string) { // O(n * n)
        //for every possible period size i, check if it's valid
        for (int i = 1; i <= string.length() / 2; i  ) {
            if (string.length() % i == 0) {
                String period = string.substring(0, i);
                int j = i;
                while(j + i <= string.length()) {
                    if (period.equals(string.substring(j, j   i))) {
                        j = j + i;
                        if(j == string.length()) { //period valid through entire string
                            return period;
                        }
                    } else {
                        break;
                    }
                }
            }

        }
        return null; //string is not periodic
    }



Get one-to-one training from Google Facebook engineers

Top-notch Professionals

Learn from Facebook and Google senior engineers interviewed 100+ candidates.
Most recent interview questions and system design topics gathered from aonecode alumnus.
One-to-one online classes. Get feedbacks from real interviewers.

Customized Private Class

Already a coding expert? - Advance straight to hard interview topics of your interest.
New to the ground? - Develop basic coding skills with your own designated mentor.
Days before interview? - Focus on most important problems in target company question bank.