## Apple Interview Question for Software Engineer in Tests

Country: United States

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

cat <filename> | tr -s [:space:] '\n' | grep -v "^\s*\$" | sort | uniq -c | sort -bnr

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

there is more efficient way because sorting hashmap based on values is not optimised way , manage heap sort with hashmap , top of heap will give the most occured word. Also, since heap will be based on number of occurence, each node of heap can maintain the list of words with same number of occurence and keep it sorted.

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

- Create a hash map to put the search words in.
- Loop through each word in the document, if the word is in the hash map. Then I increase the count of the map
- Loop through the map and sort based on its occurrence

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

HashMap[word] = occurence count , if word does not exist , else occurence++

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

``````from collections import defaultdict

hashmap = defaultdict(int)

def countWords(words):
for word in words:
hashmap[word] += 1``````

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

2 functions. One sort occurrence. One sort alphabet.

``````<?php
/**
* Suppose we are given an array of strings over some finite alphabet(say the
* letters a to z). Each string can have a different number of characters, but
* the total number of characters in all the strings is n. Show how to sort
* the strings in alphabetical order in O(n) time.
*/
function linearSort(\$s, \$p) {
\$t = [];
foreach (\$s as \$u) {
if (!isset(\$u[\$p])) \$c = 0;
else \$c = \$u[\$p];
if (!isset(\$t[\$c])) \$t[\$c] = [];
\$t[\$c][] = \$u;
}
\$s = isset(\$t[0]) ? \$t[0] : [];
foreach (range('a', 'z') as \$c) {
if (!isset(\$t[\$c])) continue;
if (count(\$t[\$c]) == 1) {\$s[] = \$t[\$c][0]; continue;}
\$u = linearSort(\$t[\$c], \$p + 1);
\$s = array_merge(\$s, \$u);
}
return \$s;
}

\$s = ['test', 'something', 'test', 'apple', 'what'];

var_dump(linearSort(\$s, 0));

/**
* There are several words in a file. Get the occurrence of every word and sort
* it based on the occurrence, if more than one word is having same occurrence
* then sort it alphabetically.
*/
function occurrenceSort(\$s) {
\$t = [];
foreach (\$s as \$u) {
if (!isset(\$t[\$u])) \$t[\$u] = 0;
\$t[\$u]++;
}
\$p = [];
\$max = 1;
foreach (\$t as \$u => \$c) {
if (!isset(\$p[\$c])) \$p[\$c] = [];
\$p[\$c][] = \$u;
\$max = \$max < \$c ? \$c : \$max;
}
\$s = [];
for (\$i = \$max; \$i > 0; \$i--) {
if (!isset(\$p[\$i])) continue;
if (count(\$p[\$i]) == 1) {
\$s[] = \$p[\$i][0];
continue;
}
\$t = linearSort(\$p[\$i], 0);
\$s = array_merge(\$s, \$t);
}
return \$s;
}

var_dump(occurrenceSort(\$s));``````

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

TreeSet<Node>
Node{word, count}

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

``````sort(vec.begin(), vec.end(),
[](const node &a, const node &b) -> bool{
if(a.val == b.val) return a.str <= b.str;
else return a.val < b.val;
});``````

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

Unix file solution :
grep -i -o -E '\w+' txtfile | tr '[:upper:]' '[:lower:]' | sort -f | uniq -c | sort

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

``````/**
* @author Dany
*
*There are several words in a file. Get the occurrence of every word and sort it based on the
*occurrence, if more than one word is having same occurrence than sort it alphabetically.
*
*ALGORITHM:
* 1. Get the input list
* 2. Put it in a hashmap and update the word occurrence count as value in the map
* 3. Iterate through the hash map and add word and count to the max heap which is implemented based on count priority
* 3. Iterate through the max heap and sort the words which has same occurrence count.
* 	  Then add the words to result list.
* 4. return the result list
*
*/
public class SortListBasedOnOccurrance {

/**
* @param args
*/
public static void main(String[] args) {
ArrayList<String> wordList = new ArrayList<String>();
ArrayList<String> res = new SortListBasedOnOccurrance().getSortedWordList(wordList);
for(String word : res)
{
System.out.println(word);
}
}

class WordObj{
String word;
int count;
public WordObj(String word, int count)
{
this.word = word;
this.count = count;
}
}

public PriorityQueue<WordObj> implementMaxHeap()
{
PriorityQueue<WordObj> pq = new PriorityQueue<WordObj>(11, new Comparator<WordObj>() {
public int compare(WordObj o1, WordObj o2)
{
int p1=o1.count;
int p2=o2.count;
return (p2-p1);
}
});
return pq;
}

public ArrayList<String> getSortedWordList(ArrayList<String> wordList)
{
ArrayList<String> resultList = new ArrayList<String>();
HashMap<String, Integer> wordMap = new HashMap<String, Integer>();

//HashMap<Integer, ArrayList<String>> valueWordMap = new HashMap<Integer, ArrayList<String>>();

for(String word : wordList)
{
if(wordMap.containsKey(word))
{
wordMap.put(word, wordMap.get(word)+1);
}else
{
wordMap.put(word, 1);
}
}
PriorityQueue<WordObj> maxHeap = implementMaxHeap();
for(String word : wordMap.keySet())
{
int count = wordMap.get(word);
}

int lastCountValue =0;
ArrayList<String> wordArrList = new ArrayList<String>();
WordObj firstWord = maxHeap.poll();
lastCountValue = firstWord.count;

while(!maxHeap.isEmpty())
{
WordObj wObj = maxHeap.poll();
if(wObj.count==lastCountValue)
{
lastCountValue = wObj.count;
}else
{
Collections.sort(wordArrList);
wordArrList = new ArrayList<String>();
lastCountValue = wObj.count;
}
}
Collections.sort(wordArrList);

return resultList;
}
}``````

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

3 step solution:
1. build the 1st hashmap with <word,occurrence> pair.
2. build the 2nd hashmap with <occurrence,array of words> pair.
3. Print 2nd hashmap on increasing order of occurrence.

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

simple groovy solution.

``````def myFile ="""hola como esta esa hola que viene por esa casa de casa asi lo queria con aaa\nNext line aaa"""

Map strMap = myFile.replaceAll('\n',' ').split(' ').countBy{it}

strMap.sort{a, b -> b.getValue() <=> a.getValue() ?: a.getKey() <=> b.getKey()}.each{
println it
}``````

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

@import Foundation;

int main() {
@autoreleasepool {
NSMutableDictionary *wordsCount = [[NSMutableDictionary alloc] init];
NSArray *words = @[@"john", @"doe", @"jane", @"doe"];
for (NSString *s in words)
{
NSNumber *count = [wordsCount objectForKey:s];
wordsCount[s] = [NSNumber numberWithInt: count ? [count intValue] + 1 : 1];
}
NSLog(@"%@", wordsCount);
} return 0;
}

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

``````public static SortedSet<WordCount> computeWordCount(BufferedReader reader) {
SortedSet<WordCount> wordCounts = new TreeSet<>();
Map<String,WordCount> map = new HashMap<>();

try {
StringTokenizer st = new StringTokenizer(line, "\t ");
st.countTokens();
while(st.hasMoreTokens()) {
String token = st.nextToken();
token = token.trim();
WordCount wordCount =null;
if(map.containsKey(token)) {
wordCount = map.get(token);
} else {
wordCount = new WordCount(token);
}
map.put(token, wordCount);
}
}

for(Entry<String,WordCount> wc: map.entrySet()) {
}

} catch (IOException e) {
e.printStackTrace();
}

return wordCounts;
}``````

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

Use TreeMap

``````public static void main(String[] args){
try {
TreeMap<String,Integer> tree = new TreeMap<>();
String line;

for(String temp: line.split("\\s+")){
if(tree.keySet().contains(temp))
tree.put(temp,tree.get(temp)+1);
else
tree.put(temp,1);
}
}

for(String temp:tree.keySet()){
System.out.println(String.format(temp + " : " + tree.get(temp)));
}

}
catch ( IOException e){
System.out.print(e.getCause());
}
}``````

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

1. Make a HashMap of word,count
2. Create a WordObject class as [word, count]
3. Create a Max heap (Priority Queue), which is fort sorted by count and then by word alphabetically
4. One by one add from Map to PQ
5. One by One remove from PQ to get the result

``````import java.util.*;

public class WordCount {

public static void getWordCount(List<String> list){

HashMap<String,Integer> wordToCountMap = new HashMap<String,Integer>();

//Build word,count map
for(String word : list){
if(wordToCountMap.containsKey(word)){
int count = wordToCountMap.get(word);
wordToCountMap.put(word, count+1);
}else{
wordToCountMap.put(word, 1);
}
}

//Make max count Priority Queue which is sorted by counts and then by string alphabetically
PriorityQueue<WordObject> maxPQ = new PriorityQueue<WordObject>(new Comparator<WordObject>(){
public int compare(WordObject o1, WordObject o2){
// sort on count and the alphabetically
if(o1.count > o2.count){
return -1;
}else if(o1.count < o2.count){
return 1;
}else{
return o1.word.compareTo(o2.word); // sort alphabetically
}
}
});

//add one by one to Max PQ
for(String word : wordToCountMap.keySet()){
}

//Build the result
List<String> result = new ArrayList<String>();
while(!maxPQ.isEmpty()){
}

//Print
System.out.println(result.toString());
}

public static void main(String[] args) {
List<String> wordList = new ArrayList<String>();

getWordCount(wordList);
}
}
//Occurrences
class WordObject{
String word;
int count;
WordObject(String word , int count){
this.word = word;
this.count = count;
}
}``````

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

``````collector = {}
import operator
from operator import itemgetter
with open('test.txt') as fh:
for lines in fh:
lines = lines.split()
for words in lines:
words = words.lower()
collector[words] = collector.get(words,0) + 1

coll_sort = sorted(collector.items(),key=lambda x:(-x[1],x[0]))``````

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

Use a binary heap DS

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.