## Facebook Interview Question for SDE1s

Country: United States

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

My algorithm uses the following idea:
1. keep a HashMap of <Char, Int> as each char and its occurence in string.
2. Use a Deque to keep the current used window of K last inserted chars.
3. Build result picking the best available candidate as:
. has the max. number of count and was not recently inserted in the deque of K last chars.
. if none available pick an already existing element from deque starting from head and keep track of its cost of insertion to result.

Using a custom Tuple<Char, Int> class since Java 8 doesn't support Tuples out-of-the-box as to keep track of selected candidate <Char> and its cost to add to result <Int>.

Implementation in Java:

``````public class TaskCountString {
public static void main(String[] args) {
}

public static int rearrangeTasks(String s, int k) {

List<Character> listC = new ArrayList<Character>();
for (char c : s.toCharArray()) {
}

// create a map of each char as key and its count num. of occurences in string
Map<Character, Long> mapCount = listC.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

int i = 0;
int numChars = s.length();

StringBuilder sb = new StringBuilder();
Deque<Character> deque = new LinkedList<>(); // use a deque to keep track of last used chars
int totalCost = 0;

while(i < numChars) {
Tuple<Character,Integer> t = getMaxCount(mapCount, deque, k);
sb.append(t.x);
totalCost += t.y;
long countOfChar = mapCount.get(t.x);
if (countOfChar == 1) {
mapCount.remove(t.x);
} else {
mapCount.put(t.x, countOfChar - 1);
}
if (deque.size() > k) {
deque.removeFirst();
}
i++;
}

System.out.println(sb);
}

private static Tuple<Character,Integer> getMaxCount(Map<Character, Long> mapCount, Deque<Character> deque, int k) {
long max = 0;
Character maxChar = null;
Map<Character, Long> mapCopy = new HashMap<>(mapCount);

for(Character c : deque) {
mapCopy.remove(c);
}

if (!mapCopy.isEmpty()) {
for(Map.Entry<Character, Long> e : mapCopy.entrySet()) {
if (e.getValue() > max) {
max = e.getValue();
maxChar = e.getKey();
}
}
return new Tuple<>(maxChar, 1);
}
int cost = 2;
for(Character c : deque) {
if (mapCount.get(c) != null)
return new Tuple<>(c, cost);
cost++;
}

return null;
}
}
class Tuple<X, Y> {
public final X x;
public final Y y;
public Tuple(X x, Y y) {
this.x = x;
this.y = y;
}
}``````

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

1. Use a hashmap to store the Character Count.
2. Then iterate through the char array again, and keep track of the last character used.
3. Remove the entries from hashmap when the count becomes 0.

``````public static int getJob(char[] arr, int k){
if(arr.length == 0){
return 0;
}
HashMap<Character, Integer> map = new HashMap<>();
for(int i=0; i<arr.length; i++){
if(map.containsKey(arr[i]))
map.put(arr[i], map.get(arr[i])+ 1);
else
map.put(arr[i], 1);
}
int res = 0;
char l = ' ';
int i = 0;
while(!map.isEmpty()){
if(i == arr.length){
i = 0;
}
if(arr[i] == ' '){
i++;
continue;
}
else if(arr[i] != l){
res +=1;
map.put(arr[i], map.get(arr[i])-1);
if(map.get(arr[i]) == 0){
map.remove(arr[i]);
}
l = arr[i];
arr[i] = ' ';
i++;
}
else if(map.size() == 1){
int val = map.get(arr[i]);
res += val * k + val;
map.remove(arr[i]);
i++;
}else
i++;
}
return res;
}
public static void main(String[] args){
char[] arr1 = {'A','A','A','B','B','B','C','C','C'};
char[] arr2 = {'A','A','A','B','C'};
System.out.println(getJob(arr1, 3));
System.out.println(getJob(arr2, 2));
}``````

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

Map<Character,Integer> map=new HashMap<Character, Integer>();
//Storing string in may by character as key and number of repetions of it as value
if(map.containsKey(c)){
map.put(c, map.get(c)+1);
}
else{
map.put(c, 1);
}
}
//looping through map and removing each character in every unique alphabet for cooltime period
int c=0;
boolean newLoop=false;
while(!map.isEmpty()){
newLoop=true;
Iterator<Character> it=map.keySet().iterator();
while(it.hasNext()){
char ch=it.next();
if(!newLoop && c!=0 && c%(coolDown+1)==0) break;
newLoop=false;
map.put(ch, map.get(ch)-1);
c++;
if(map.get(ch)==0) it.remove();
}
while(c%(coolDown+1)!=0 && !map.isEmpty()) c++;
}
return c;

}

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

``````public static int reArrangeTasks(String tasks,int coolDown){
Map<Character,Integer> map=new HashMap<Character, Integer>();
//Storing string in may by character as key and number of repetions of it as value
if(map.containsKey(c)){
map.put(c, map.get(c)+1);
}
else{
map.put(c, 1);
}
}
//looping through map and removing each character in every unique alphabet for cooltime period
int c=0;
boolean newLoop=false;
while(!map.isEmpty()){
newLoop=true;
Iterator<Character> it=map.keySet().iterator();
while(it.hasNext()){
char ch=it.next();
if(!newLoop && c!=0 && c%(coolDown+1)==0) break;
newLoop=false;
map.put(ch, map.get(ch)-1);
c++;
if(map.get(ch)==0) it.remove();
}
while(c%(coolDown+1)!=0 && !map.isEmpty()) c++;
}
return c;

}``````

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

``````string OptimizeTasks(string const &tasks)
{
for (char c : tasks) {
}
string optimized;
optimized += it->first;
if (--it->second == 0) {
}
}
}
return optimized;
}``````

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

//C# Code working for me

``````private static Tuple<string, int> optTaskSeqK(string tasks, int coolTime)
{
int totalExeTime = 0;
for (int seq = 0; seq < tasks.Length; seq++)
{
{
}
}
{
var taskGP = taskDic.Where(i => i.Value > 0).GroupBy(i => i.Value).OrderByDescending(i => i.Key).First().ToList();

{
if (ti.Value > 0)
{
}
}
};

{
if (t1.exeTime != t2.exeTime)
return t1.exeTime < t2.exeTime ? t1 : t2;
if (t1.count != t2.count)
return t1.count > t2.count ? t1 : t2;
if (t1.seq != t2.seq)
return t1.seq < t2.seq ? t1 : t2;
return t2;
}
}

{
public int exeTime;
public int count { get; set; }
public int seq { get; set; }
}``````

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

Example 1 (k=3, ie distance should be 3 in between same tasks) does not match with examples 2 & 3

test runs:

``````public int rearrangeTasks(String tasks, int cooldown){

HashMap<Character, Integer> occurMap = new HashMap<>();

//compute map
for (int i=0; i < tasks.length();i++) {
Integer occurence = occurMap.get(c);
if (occurence == null) {
occurMap.put(c, 1);
} else {
occurMap.put(c, occurence+1);
}
}

HashMap<Character, Integer> distMap = new HashMap<>();
final AtomicInteger startPos = new AtomicInteger(0);
occurMap.entrySet().stream().forEach( (e) -> {
char c = e.getKey();
int occurence = e.getValue();

//placing same tasks far apart within minDist
int charDist = minDist.get() / occurence;
if (charDist <= cooldown) {
int newCharDist = (cooldown + 1);
distMap.put(c, newCharDist);
int newDist = (occurence-1) * newCharDist +
startPos.incrementAndGet();
if (minDist.get() < newDist) {
minDist.set(newDist);
}
} else {
distMap.put(c, charDist);
}
});

//only to print output task order, not required otherwse
AtomicInteger writePos = new AtomicInteger(-1);
char[] out = new char[minDist.get()];
Arrays.fill(out, '_');
occurMap.entrySet().stream().forEach( (e) -> {
char c = e.getKey();
int occurence = e.getValue();

int pos = writePos.incrementAndGet();
int charDist = distMap.get(c);
while(occurence > 0) {
while (out[pos] != '_' ||
anyInRange(out, pos-cooldown, pos+cooldown, c)) {
pos += (charDist + 1); //conflicts, moveover
pos %= minDist.get();
}
out[pos] = c;
occurence--;
pos += (charDist);
pos %= minDist.get();
}
});
System.out.println(new String(out) + " " + out.length);

return minDist.get();
}

private boolean anyInRange(char[] out, int i, int j, char c) {
if (i < 0) {
i = 0;
}

if (j >= out.length) {
j = out.length - 1;
}

for (int k = i; k <= j; k++) {
if (out[k] == c) {
return true;
}
}

return false;
}``````

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

Output:

ABC_ABC_ABC 11
ABCDEABCDEABCDEABCDEABCDE 25
ABCA__A 7
ABCABDA 7
BC_BC_BC 8
BC__BC__BC 10

``````public class TaskDistance {

public static void main(String[] args) {
}

HashMap<Character, Integer> occurMap = new HashMap<>();

//compute map
for (int i=0; i < tasks.length();i++) {
Integer occurence = occurMap.get(c);
if (occurence == null) {
occurMap.put(c, 1);
} else {
occurMap.put(c, occurence+1);
}
}

HashMap<Character, Integer> distMap = new HashMap<>();
final AtomicInteger startPos = new AtomicInteger(0);
occurMap.entrySet().stream().forEach( (e) -> {
char c = e.getKey();
int occurence = e.getValue();

//placing same tasks far apart within minDist
int charDist = minDist.get() / occurence;
if (charDist <= cooldown) {
int newCharDist = (cooldown + 1);
distMap.put(c, newCharDist);
int newDist = (occurence-1) * newCharDist +
startPos.incrementAndGet();
if (minDist.get() < newDist) {
minDist.set(newDist);
}
} else {
distMap.put(c, charDist);
}
});

//only to print output task order, not required otherwse
AtomicInteger writePos = new AtomicInteger(-1);
char[] out = new char[minDist.get()];
Arrays.fill(out, '_');
occurMap.entrySet().stream().forEach( (e) -> {
char c = e.getKey();
int occurence = e.getValue();

int pos = writePos.incrementAndGet();
int charDist = distMap.get(c);
while(occurence > 0) {
while (out[pos] != '_' ||
anyInRange(out, pos-cooldown, pos+cooldown, c)) {
pos += (charDist + 1); //conflicts, moveover
pos %= minDist.get();
}
out[pos] = c;
occurence--;
pos += (charDist);
pos %= minDist.get();
}
});
System.out.println(new String(out) + " " + out.length);

return minDist.get();
}

private boolean anyInRange(char[] out, int i, int j, char c) {
if (i < 0) {
i = 0;
}

if (j >= out.length) {
j = out.length - 1;
}

for (int k = i; k <= j; k++) {
if (out[k] == c) {
return true;
}
}

return false;
}

}``````

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

``````public class TaskDistance {

public static void main(String[] args) {
}

HashMap<Character, Integer> occurMap = new HashMap<>();

//compute map
for (int i=0; i < tasks.length();i++) {
Integer occurence = occurMap.get(c);
if (occurence == null) {
occurMap.put(c, 1);
} else {
occurMap.put(c, occurence+1);
}
}

HashMap<Character, Integer> distMap = new HashMap<>();
final AtomicInteger startPos = new AtomicInteger(0);
occurMap.entrySet().stream().forEach( (e) -> {
char c = e.getKey();
int occurence = e.getValue();

//placing same tasks far apart within minDist
int charDist = minDist.get() / occurence;
if (charDist <= cooldown) {
int newCharDist = (cooldown + 1);
distMap.put(c, newCharDist);
int newDist = (occurence-1) * newCharDist +
startPos.incrementAndGet();
if (minDist.get() < newDist) {
minDist.set(newDist);
}
} else {
distMap.put(c, charDist);
}
});

//only to print output task order, not required otherwse
AtomicInteger writePos = new AtomicInteger(-1);
char[] out = new char[minDist.get()];
Arrays.fill(out, '_');
occurMap.entrySet().stream().forEach( (e) -> {
char c = e.getKey();
int occurence = e.getValue();

int pos = writePos.incrementAndGet();
int charDist = distMap.get(c);
while(occurence > 0) {
while (out[pos] != '_' ||
anyInRange(out, pos-cooldown, pos+cooldown, c)) {
pos += (charDist + 1); //conflicts, moveover
pos %= minDist.get();
}
out[pos] = c;
occurence--;
pos += (charDist);
pos %= minDist.get();
}
});
System.out.println(new String(out) + " " + out.length);

return minDist.get();
}

private boolean anyInRange(char[] out, int i, int j, char c) {
if (i < 0) {
i = 0;
}

if (j >= out.length) {
j = out.length - 1;
}

for (int k = i; k <= j; k++) {
if (out[k] == c) {
return true;
}
}

return false;
}

}``````

Output:

ABC_ABC_ABC 11
ABCDEABCDEABCDEABCDEABCDE 25
ABCA__A 7
ABCABDA 7
BC_BC_BC 8
BC__BC__BC 10

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

``````public int rearrange(List<Character> tasks, int k) {
if (tasks.size() == 1) return 1;

HashMap<Character, Integer> hm = new HashMap<>();

if (hm.contains(c)) hm.put(c, hm.get(c) + 1);
}

ArrayList<Map.Entry> sortedTasks = Collections.sort(hm.entrySet().toArray(), (p1, p2) -> p1.value > p2.value);

int sum = 0;
for (int i = 1; i < sortedTasks.size(); i++) {
}

// If X is #of tasks of highest frequency, the formula for total duration is
// X + (X-1)k - S
}``````

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.

### 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.