Facebook Interview Question for Software Engineer / Developers


Country: United States
Interview Type: Phone Interview




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

Another possibility in python using a simple generator:

max( string.count(char) for char in set(string) )

And of course, you can always add in the

string = string.lower()

bit before that if you want...

- Oblique63 March 27, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
2
of 2 vote

//C# implmentation 
static int MaxCharacterRepeatation(string _str)
        {
            int Max = 1;
            Dictionary<int,int> charset = new Dictionary<int, int>();
            for (int i = 0; i <_str.Length; i++)
            {
                int val = _str[i];
                if (!charset.ContainsKey(val))
                {
                    charset.Add(val, 1);
                }
                else
                {
                    charset[val] = charset[val]+1;
                    if (charset[val] > Max)
                    {
                        Max = charset[val];
                    }
                }
            }
            return (Max);

        }

}

- anup.h.nair December 16, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

Just use an auxiliary array of size equal to character set ( 130 would suffice ) => ch[130]

let given string is s.

ch[130] = { 0 } //initialize all by 0
for each s[i] in s :
              ch[s[i]]++
return chracater K for which ch[K] is max

Complexity : O(n)

- Cerberuz December 08, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def get_iden(s)
ident=0
for i in 0..s.to_s().length-1
temp_iden=0
for j in i..s.to_s().length-1
if s[i]==s[j]
temp_iden=temp_iden+1
end
end

if (temp_iden>ident)
ident=temp_iden
end
end
return ident
end



A="ddccaaaabcd"
puts get_iden(A)

- Walid December 08, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Just do as Cerbeuz showed, I cannot figure out any more effective algorithm either

- Rocky December 08, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#JavaScript
s = "dfsdfsasd"
function getHighestCharCount(s){
var count = {};
for(c in s){
var key = s[c];
if( count[key] == undefined){
count[key] = 1;
}else{
count[key]++;
}
}
var highest = 0;
for(i in count){
highest = count[i] > highest ? count[i] : highest;
}
return highest;
}
getHighestCharCount(s);
O(n)

- answer in JavaScript January 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#JavaScript
s = "dfsdfsasd"
function getHighestCharCount(s){
	var count = {};
	for(c in s){
		var key = s[c];
		if( count[key] == undefined){
			count[key] = 1;
		}else{
			count[key]++;
		}
	}
	var highest = 0;
	for(i in count){
		highest = count[i] > highest ? count[i] : highest;
	}
	return highest;
}
getHighestCharCount(s);
O(n)

- answer in JavaScript January 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#JavaScript
s = "dfsdfsasd"
function getHighestCharCount(s){
	var count = {}, highest = 0;
	for(c in s){
		var key = s[c];
		count[key] = count[key] ? count[key]+1 : 1;
	}
	for(i in count){
		highest = count[i] > highest ? count[i] : highest;
	}
	return highest;
}
getHighestCharCount(s);
O(n)

- dry JavaScript January 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Something that might be a bit more effcient

from collections import defaultdict
def parseword(a_word):
    a_dict = defaultdict(lambda: 0)
    max = None
    for l in a_word:
    	l = l.lower()
        a_dict[l] += 1
        max = a_dict[l] if a_dict[l] > max else max
    return max

- Justin January 14, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int PasswordCount(char * password)
{
    int r[256] = {0}; //256 characters in ascii
    int max = 0;
    int l = strlen(password);

    for(int i=0;i<l;i++)
    {
        int c = password[i];
        int count = 1;
        for(int n=i+1;n<l;n++)
        {
            if(r[c] != 0)
                break;
            if(c == password[n])
            {
                count++;
            }
        }
        if(count > max)
        {
            max = count;
        }
    }
    return max;
}

- Isaac Levy January 30, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <vector>
#include <string>
#include <functional>
#include <iostream>
#include <unordered_map>


std::pair<char, int> countCharsAndReturnMax(std::string str, std::unordered_map<char, int>& counts)
{
    std::pair<char, int> max;
    
    for(auto c : str) 
    {
        if(counts[c]++ > max.second)
            max = std::make_pair(c, counts[c]);
    }
    
    return max;
}

int main(int argc, char** argv)
{
    std::unordered_map<char, int> counts;
    auto maxEntry = countCharsAndReturnMax("Facebook", counts);

    std::cout << "Given strings has following char histogram:" << std::endl << std::endl;
    
    for(auto e : counts)
    {
        if(e.first == maxEntry.first)
            std::cout << ">>";
        else
            std::cout << "  ";
            
        std::cout << " '" << e.first << "' : " << e.second << " times" << std::endl;
    }
    
    return 0;
}

- FBNerd February 26, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

If you want a short Python code:

a = 'coffee cuffee'
max(len(list(g)) for k, g in itertools.groupby(sorted(a)))

But in big O term, it is not best.

- bill.z.li March 21, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def countmax ( word_):
    charlist= list(word_)
    maxim=0
    
    for s in charlist:
        charcount=charlist.count(s)
        if charcount > maxim:
            maxim=charcount
    return maxim

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

maxstring = lambda s: max(map(s.count, iter(s)))

Testing:
maxstring('coffee tuffee')
4


# Handle Empty String:
maxstring = lambda s: 0 if len(s) == 0 else max(map(s.count, iter(s)))

maxstring('')
0

- junk July 11, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def parseword(a_word):
	return max([a_word.count(c) for c in a_word.lower()])

- m3th0d.itbhu July 31, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

from collections import Counter
def count_max(string):
    return max(dict(Counter(string)).values())

- Pavel September 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Python has some ways of doing this very elegantly, but typically interviewers want you to implement it at its base level, as can be seen here:

def get_max_repeated(string):
	chars = {}
	max = 1
	for c in string:
		if c not in chars:
			chars[c] = 1
		else:
			current = chars[c]+1
			chars[c] = current
			if current > max:
				max = current
	return max

print get_max_repeated("coffee tuffee")

- DevonMeyer212 September 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote
You can use collections.Counter on this as well {{{ import collections c = 'coffee tuffee' print collections.Count(c).most_common()[0][0] - Ellison Leão November 26, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

from collections import Counter
s = "coffee tuffee"
c = Counter(s)
c.most_common(n=1)[0]

- xu.xeno January 03, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def getMaxDuplLetters(word):
return max(map(a.lower().count,a.lower()))

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

def getMaxDuplLetters(word):
return max(map(a.lower().count,a.lower()))

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

charcount = dict()

def addchar(x):
  if x in charcount:
    charcount[x]+=1
  else:
    charcount[x]=1

def parseword(a_word):
  a_word=a_word.lower()
  map(addchar, a_word)
  return (max(charcount.itervalues()))
  

print parseword(a_word)

- Anonymous September 10, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#in JavaScript

var str = "coffee tuffee";
var str_alph_highest_count = function(s){
	var c=0,s2,s1 = s.split("");
	for(var i=0;i<s1.length;i++){
		if(s1[i] != ""){
			s2 = s.split(s1[i]);
			c = s2.length < c ? c: (s2.length-1);
		}
	}
	return c;
}

- naresh October 10, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

max(map(string.lower().count, string.lower()))

- Elena Henderson October 16, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

A java version:

public int countChar(String s){
    int[] count=new int[256] ;

    for(int i=0;i<s.length();i++){
        int index=handleCase(s.charAt(i));
        count[index]++;
    }

    int max=0;
    for(int i=0;i<256;i++){
        max=Math.max(max,count[i]);
    }
    return max;
  }

  public int handleCase(char c){
    if (c>='a'&&c<='z')
        return c-32;
    else return c;
  }

- dv January 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Notice that 'coffee tuffee' actually has character counts of 4 for both char e and char f. It might be useful to know which characters return the highest count to discriminate multiple max counts. Here is a definition that will do just that:

def parsewords(the_words):
        return sorted([(list(words).count(c), c) for c in list(set(list(words)))])[::-1])

I have left off the exceptions that might want to be handled, e.g. white spaces, upper versus lower case, etc. to simplify the code.

The idea is to create a list of length N from the_words, and then using list comprehension, create a reverse-sorted list. Given 'coffee tuffee' the definition returns:

[(4, 'f'), (4, 'e'), (1, 'u'), (1, 't'), (1, 'o'), (1, 'c'), (1, ' ')]

- Aaron February 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Correction: the_words in nthe argument should be replaced with words.

A more readable form is given by:

def pwords(words):
    list_chars = list(words)
    set_chars = set(list_chars)
    result = []
    for c in set_chars:
        result.append([list_chars.count(c), c])

    
    return sorted(result)[::-1]

- Anonymous February 09, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Just a nit that really bothers me:

return sorted([(list(words).count(c), c) for c in set(list(words))])[::-1])

Get rid of the conversion from set to list. Not needed.

- Aaron February 09, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

word = "coffee toffee"
lis = [c for c in word]
lis2 = []
for l in lis:
	lis2.append(lis.count(l))
print max(lis2)

- dark_knight July 17, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

str1 = "coffee toffee"
collections.Counter(str1).most_common(2)

- Anonymous October 24, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class Solution(object):
    def get_highest_char_count(self, s):
        summary = {}
        max_count = 0
        for ss in s:
            summary[ss] = summary.get(ss, 0) + 1
            max_count = max(max_count, summary[ss])

        return max_count

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

class Solution(object):
    def get_highest_char_count(self, s):
        summary = {}
        max_count = 0
        for ss in s:
            summary[ss] = summary.get(ss, 0) + 1
            max_count = max(max_count, summary[ss])

        return max_count

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

from collections import counter
string="coffee tuffee"
print(max(Counter(list(string)).values()))

- mukesh July 26, 2017 | 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