Facebook Interview Question for Software Engineers


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
2
of 2 vote

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
    }

Looking for interview experience sharing and mentors?
Visit A++ Coding Bootcamp at aonecode.com.

Taught by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greed and other advanced algo problems),
and mock interviews.

Our students got offers from Google, Uber, Facebook, Amazon and other top companies after a few weeks of training.

Welcome to email us with any questions. Thanks for reading.

- acoding167 June 07, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

def factors(n):
    f=[]
    for i in range(1,n):
        if n%i==0:
            f.append(i)
    return f
            
        
def periodic(s):
    
    f=factors(len(s))
    for i in f:
        m=len(s)/i
        #return s[:i]*3
        if s[:i]*int(m)==s:
            return True
    return False
    
print(periodic('abcabc'))                 
        def factors(n):
    f=[]
    for i in range(1,n):
        if n%i==0:
            f.append(i)
    return f
            
        
def periodic(s):
    
    f=factors(len(s))
    for i in f:
        m=len(s)/i
        #return s[:i]*3
        if s[:i]*int(m)==s:
            return True
    return False

- Anonymous June 07, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

What am I missing about example number 2 in the question:

S = "xxxxxx", n = 1, then P = "x"

This doesn't seem consistent with the other examples.
In the first example, if n=3 and P=ab, then 3ab => ababab, that makes sense.
In the third example, if n = 2 and P=aabba, then 2aabba => aabbaaabba, that make sense.

But for exmple 2, if n=1 and P=x, then 1x should be x, not xxxxxx. I feel that in this case, if the P is x, then n should be 6, because 6x => xxxxxx

What am I missing? Am I fundamentally misunderstanding the problem here?

- Imposter June 07, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def factors(n):
    f=[]
    for i in range(1,n):
        if n%i==0:
            f.append(i)
    return f
            
        
def periodic(s):
    
    f=factors(len(s))
    for i in f:
        m=len(s)/i
        #return s[:i]*3
        if s[:i]*int(m)==s:
            return True
    return False

- Abid June 07, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

a slightly improved version

#!/usr/bin/env python3
"""
  Find whether string S is periodic. Periodic indicates S = nP. e.g.
  if S = abcabc, then n = 3, and P = abc
  if S = xxxx, n = 1, and P = x
  follow up, given string S, find out repetitive pattern of P
"""
def factors(n):
    f = []
    for i in range(1, n):
        if n % i == 0:
            f.append(i)
    return f
def periodic(s):
    f = factors(len(s))
    for i in f:
        m = len(s)/i
        if s[:i] * int(m) == s:
            print(i, s[:i], s)
            return True
    return False
# driver
if __name__ == "__main__":
  assert True == periodic('abcabc')
  assert False == periodic('abcabcd')

- KB2 June 12, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

pattern = []
string = "sarojasaroja"
if len(set(string)) ==1:
print(string[0])
else:
for outer in range(2,int(len(string)/2)+1):
listt = []
if len(string)%outer == 0:
for inner in range(outer):
for innermost in range(inner,int(len(string)/outer)):
if(string[innermost+inner] != string[innermost + outer]):
break
else :
listt.append(string[inner])
if len(listt) == int(len(string)/outer) :
pattern.append(string[inner])
if len(pattern) == outer :
break
print (pattern)

- saroja kumar pradhan(kumar.saroja5@gmail.com) June 24, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

pattern = []
string = "sarojasaroja"
if len(set(string)) ==1:
    print(string[0])
else:
    for outer in range(2,int(len(string)/2)+1):
        listt = []
        if len(string)%outer == 0:
            for inner in range(outer):
                for innermost in range(inner,int(len(string)/outer)):
                    if(string[innermost+inner] != string[innermost + outer]):
                        break
                    else :
                        listt.append(string[inner])
                if len(listt) == int(len(string)/outer) :
                    pattern.append(string[inner])
            if len(pattern) == outer :
                break
    print (pattern)

- saroja kumar pradhan(kumar.saroja5@gmail.com) June 24, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

pattern = []
string = "sarojasaroja"
if len(set(string)) ==1:
    print(string[0])
else:
    for outer in range(2,int(len(string)/2)+1):
        listt = []
        if len(string)%outer == 0:
            for inner in range(outer):
                for innermost in range(inner,int(len(string)/outer)):
                    if(string[innermost+inner] != string[innermost + outer]):
                        break
                    else :
                        listt.append(string[inner])
                if len(listt) == int(len(string)/outer) :
                    pattern.append(string[inner])
            if len(pattern) == outer :
                break
    print (pattern)

- saroja kumar pradhan(kumar.saroja5@gmail.com) June 24, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

pattern = []
string = "sarojasaroja"
if len(set(string)) ==1:

print(string[0])

else:

for outer in range(2,int(len(string)/2)+1):
        listt = []
        if len(string)%outer == 0:
            for inner in range(outer):
                for innermost in range(inner,int(len(string)/outer)):
                    if(string[innermost+inner] != string[innermost + outer]):
                        break
                    else :
                        listt.append(string[inner])
                if len(listt) == int(len(string)/outer) :
                    pattern.append(string[inner])
            if len(pattern) == outer :
                break
    print (pattern)

- saroja kumar pradhan(kumar.saroja5@gmail.com) June 24, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote
{{{pattern = [] string = "sarojasaroja" if len(set(string)) ==1: {{{ print(string[0])}}} else: {{{for outer in range(2,int(len(string)/2)+1):}}} {{{ listt = []}}} {{{if len(string)%outer == 0:}}} {{{ for inner in range(outer):}}} {{{ for innermost in range(inner,int(len(string)/outer)):}}} {{{if(string[innermost+inner] != string[innermost + outer]):}}} {{{ break}}} {{{else :}}} {{{ listt.append(string[inner])}}} {{{if len(listt) == int(len(string)/outer) :}}} {{{pattern.append(string[inner])}}} {{{ if len(pattern) == outer :}}} {{{break}}} {{{print (pattern)}}} - saroja kumar pradhan(kumar.saroja5@gmail.com) June 24, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

test

- test June 24, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

test

- test June 24, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def isPeriodic(input, start, end=1):

    if end-start > len(input) - end:
        return False

    did_match = True
    for x in range(start, end):
        #print (" check " + str(x) + " " + str(start) + " " + str(end) + " => " + str(len(input)))
        if input[x] != input[end - start + x]:
            did_match = False
            break

    if did_match:
        delta = end - start
        start2 = end

        if end + delta == len(input):
            return True

        did_match = isPeriodic(input, end, end + delta)

    if not did_match:
        return isPeriodic(input, start, end+1)

    return did_match


if __name__ == "__main__":
    S = "ababab"
    print(S + " => " + str(isPeriodic(S, 0)))
    S = "xxxxxx"
    print(S + " => " + str(isPeriodic(S, 0)))
    S = "aabbaaabba"
    print(S + " => " + str(isPeriodic(S, 0)))
    S = "aabbaabbaabb"
    print(S + " => " + str(isPeriodic(S, 0)))
    S = "abcd"
    print(S + " => " + str(isPeriodic(S, 0)))
    S = "abbaabbaabba"
    print(S + " => " + str(isPeriodic(S,

- Recursive June 26, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static boolean isPeriodic(String s) {
		for(int i=s.length(); i>1; i--) {
			int length = s.length();
			String p = s.substring(0, length / i);
			if (isSubstring(s, p)) {
				System.out.println(p);
				return true;
			}
		}
		return false;
	}

	static boolean isSubstring(String s, String p) {
		for (int i=0; i<s.length(); i+=p.length()) {
			if (!s.substring(i, i+p.length()).equals(p)) return false;
		}
		return true;
	}

- Oleg June 27, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static boolean isPeriodic(String s) {
		for(int i=s.length(); i>1; i--) {
			int length = s.length();
			String p = s.substring(0, length / i);
			if (isSubstring(s, p)) {
				System.out.println(p);
				return true;
			}
		}
		return false;
	}

	static boolean isSubstring(String s, String p) {
		for (int i=0; i<s.length(); i+=p.length()) {
			if (!s.substring(i, i+p.length()).equals(p)) return false;
		}
		return true;
	}

- omikheev June 27, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.Optional;

class Main {
  public static void main(String[] args) {
    System.out.print("String: " + args[0]);
    Optional<String> patOp = findPattern(args[0]);
    if (patOp.isPresent()) {
      System.out.println(" Pattern: " + patOp.get());
    } else {
      System.out.println(" No pattern found.");
    }
  }

  // The algorithm is to concatenate the string to itself, take the result without
  // the first and the last characters and look for the string inside this result.
  // If present - the string is periodic.
  // To find the pattern, take the index of the string in the result, cut the result
  // up until this index and add the first character of the original string in 
  // the beginning.
  // Example:   
  //   original: aabbaaabba                    
  //   result to look in:            [a]abbaaabbaaabbaaabb[a]
  //   found the original at index 4:   0123|--------|  
  //   prefix: abba, add back the first character -> aabba
  public static Optional<String> findPattern(String str) {
    String test = str + str;
    String sub = test.substring(1, test.length() - 1);
    int index = sub.indexOf(str);
    if (index < 0) {
      return Optional.empty();
    }
    return Optional.of(str.charAt(0) + sub.substring(0, index));
  }
}

- vladiu June 28, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function printIsPeriodAndCount(str) {

    for (let i = 1; i < str.length; i++) {

        let splitFactor = str.substr(0, i);

        let parts = str.split(splitFactor);

        if (splitFactor !== str && parts.length > 1 && !parts.find(s=>s !== '')) {
            console.log(true);
            console.log(parts.length - 1);
        }

    }

}

- yakir.rotem July 01, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

const isPeriodic = (str) => {

    let currStr = str.charAt(0);
    let n = 1;
    let i = 1;

    while (i < str.length) {

        if (currStr.charAt(0) === str.charAt(i)) {
            if (currStr === str.substring(i, i + currStr.length)) {
                n++;
            } else {
                currStr += str.substring(i, i + currStr.length);
            }
            
            i += currStr.length - 1;
        } else {
            let newStr = "";
            while (n >= 1) {
                newStr += currStr;
                n--;
            }
            n = 1;
            newStr += str.charAt(i);
            currStr = newStr;
        }

        i++;

    }

    console.log(`n: ${n}, p: ${currStr}`);
};

- Jonathan Mor July 07, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

const isPeriodic = (str) => {

    let currStr = str.charAt(0);
    let n = 1;
    let i = 1;

    while (i < str.length) {

        if (currStr.charAt(0) === str.charAt(i)) {
            if (currStr === str.substring(i, i + currStr.length)) {
                n++;
            } else {
                currStr += str.substring(i, i + currStr.length);
            }
            
            i += currStr.length - 1;
        } else {
            let newStr = "";
            while (n >= 1) {
                newStr += currStr;
                n--;
            }
            n = 1;
            newStr += str.charAt(i);
            currStr = newStr;
        }

        i++;

    }

    console.log(`n: ${n}, p: ${currStr}`);
};

- Jonathan Mor July 07, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class PeriodicStringTest {
    
    public static void main(String[] args) {
        findRepetitivePattern("aabbaaabba");
        findRepetitivePattern("xxxxxxxxxx");
        findRepetitivePattern("ababab");
        findRepetitivePattern("aa");
        findRepetitivePattern("aaabaa");
    }
    
    public static void findRepetitivePattern(String str) {
        if (str.length() <= 1) {
            System.out.println("String '" + str + "' is not periodic.");
            return;
        }
        String repititivePattern = null;
        boolean periodic = false;
        for (int i = 0; i < str.length() - 1; i++) {
            repititivePattern = str.substring(0, i+1);
            String splits[] = str.split(repititivePattern, -1);
            for (String split : splits) {
                if (split.equals("")) {
                    periodic = true;
                } else {
                    periodic = false;
                    break;
                }
            }
            if (periodic) {
                System.out.println("String '" + str + "' ===> P = " + repititivePattern + ", n = " + (splits.length-1));
                return;
            }
        }
        System.out.println("String '" + str + "' is not periodic.");
    }

}

Output:
String 'aabbaaabba' ===> P = aabba, n = 2
String 'xxxxxxxxxx' ===> P = x, n = 10
String 'ababab' ===> P = ab, n = 3
String 'aa' ===> P = a, n = 2
String 'aaabaa' is not periodic.

- Samrat July 08, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class PeriodicStringTest {
    
    public static void main(String[] args) {
        findRepetitivePattern("aabbaaabba");
        findRepetitivePattern("xxxxxxxxxx");
        findRepetitivePattern("ababab");
        findRepetitivePattern("aa");
        findRepetitivePattern("aaabaa");
    }
    
    public static void findRepetitivePattern(String str) {
        if (str.length() <= 1) {
            System.out.println("String '" + str + "' is not periodic.");
            return;
        }
        String repititivePattern = null;
        boolean periodic = false;
        for (int i = 0; i < str.length() - 1; i++) {
            repititivePattern = str.substring(0, i+1);
            String splits[] = str.split(repititivePattern, -1);
            for (String split : splits) {
                if (split.equals("")) {
                    periodic = true;
                } else {
                    periodic = false;
                    break;
                }
            }
            if (periodic) {
                System.out.println("String '" + str + "' ===> P = " + repititivePattern + ", n = " + (splits.length-1));
                return;
            }
        }
        System.out.println("String '" + str + "' is not periodic.");
    }

}

- samband14 July 08, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def period_string(string):
    k = len(string)
    for i in range (k, 0, -1):
        if not k%i:
            if string[:k//i] == string[k//i:2*k//i]:
                return (k//(k//i), string[:k//i])   
    return "non periodic string"

- Alexey Gorovoy July 14, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def period_string(string):
    k = len(string)
    for i in range (k, 0, -1):
        if not k%i:
            if string[:k//i] == string[k//i:2*k//i]:
                return (k//(k//i), string[:k//i])   
    return "non periodic string"

- Alexey Gorovoy July 14, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/*
 * T: O(n^2)
 * S: O(n)
 * */
public class PeriodicPattern{
    static boolean ans = false;
    public static void main(String[] args){
        String str = "aabbaaabba";
        for(int i=0; i<str.length()/2+1; i++){
            String s = str.substring(0, i+1);
            dfs(str, s.length(), s);
        }
        System.out.println(ans);
    }

    public static void dfs(String str, int start, String p){
        if(start == str.length()){
            ans = true;
            System.out.println(p);
            return;
        }

        if(str.indexOf(p, start) == start)
            dfs(str, start+p.length(), p);
    }
}

- xzhan211@binghamton.edu July 22, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

S = nP
based on the definition, any string is always periodic.
because "anystring" = 1 * "anystring".

So "n must be more than 1" should be a part of the definition. Otherwise its

def isPeriodic
return true
end

- michael July 26, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

S = nP
based on the definition, any string is always periodic.
because "anystring" = 1 * "anystring".

So "n must be more than 1" should be a part of the definition. Otherwise its

def isPeriodic
return true
end

- michael July 26, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def periodic (my_str):
str_len = len(my_str)
period_sizes = []
reaps = []
for i in range(1, int(str_len/2)+1):
if str_len%i == 0:
period_sizes.append(i)

for period_size in period_sizes:
reaps.append(my_str.count(my_str[:period_size]))

for i in range (0,len(period_sizes)):
if period_sizes[i] * reaps [i] == str_len:
return True
return (False)

- Leah Bor August 04, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def periodic (my_str = "aaaaabbbbb"):
    str_len = len(my_str)
    period_sizes = []
    reaps = []
    for i in range(1, int(str_len/2)+1):
        if str_len%i == 0:
            period_sizes.append(i)

    for period_size in period_sizes:
        reaps.append(my_str.count(my_str[:period_size]))

    for i in range (0,len(period_sizes)):
        if period_sizes[i] * reaps [i] == str_len:
            return True
    return (False)

- Leah Bor August 04, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static string FindPeriodicPattern(string s)
        {
            StringBuilder currPatt = new StringBuilder();
            int n = 1, i = 0, innerI = 0;

            bool isCurrMatch = false;

            while (i < s.Length)
            {
                innerI = i;
                foreach (var ch in currPatt.ToString())
                {
                    if (s[innerI] == ch)
                    {
                        isCurrMatch = true;
                        innerI++;
                        continue;
                    }
                    else
                    {
                        isCurrMatch = false;
                        currPatt.Append(s[i]);
                        break;
                    }
                }

                if (isCurrMatch)
                {
                    i = innerI;
                    n++;
                }
                else
                {
                    if(string.IsNullOrEmpty(currPatt.ToString()))
                        currPatt.Append(s[i]);
                    i++;
                }

            }

            return n > 1 ? currPatt.ToString() : null;
        }

- Abubakar August 14, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import textwrap
for i in range(2, len(S)):
    if len(S)%i ==0:
        if len(set(textwrap.wrap(S,i)))==0:
        	print(i, textwrap.wrap(S,i)[0])
            print("True")
            break

- Anonymous August 17, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// S = "ababab", then n=3, P= "ab"
// S = "xxxxxx", then n = 1, and P = "x"
// S = "aabbaaabba", then n = 2, and P = "aabba"

function findPattern(str) {
  var pattern = '';
  var n = 1;
  
  for (var i = 0; i < str.length;) {
    var step = pattern.length > 0 ? pattern.length : 1;
    var test = str.substr(i, step);
        
    if (test == pattern) {
      // Possible a pattern
      i += step;
      n += 1;
    } else {
      i += 1;
      pattern = str.substr(0, i);
      n = 1;
    }
  }
  
  return {n, pattern};
}

console.log("ababab => " + JSON.stringify(findPattern("ababab")))
console.log("xxxxxx => " + JSON.stringify(findPattern("xxxxxx")))
console.log("aabbaaabba => " + JSON.stringify(findPattern("aabbaaabba")))

- sheng August 21, 2019 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More