Apple Interview Question for Software Engineer / Developers


Country: United States
Interview Type: In-Person




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

public class TopNEntriesFromFiles {
	
	/**
	 * Read given files and find top n customers by expenses.
	 * Assume that file format is comma separated values:  
	 * customer_id, product_id, expenses
	 * (e.g. 1,32,5564)
	 * @param n 
	 * 		number of map entries to return
	 * @param paths 
	 * 		files to process
	 * @return top n entries from given files
	 */
	private static Map<Integer, Integer> processFiles(int n, String... paths) {
		Map<Integer, Integer> temp = new LinkedHashMap<>();
		Map<Integer, Integer> result = new LinkedHashMap<>();
		for (String path : paths) {
			try (BufferedReader br = new BufferedReader(new FileReader(path))) {
				String line = br.readLine();
				while (line != null) {
					int customerId = Integer.parseInt(line.split(",")[0]);
					int expences = Integer.parseInt(line.split(",")[2]);
					if (temp.containsKey(customerId)) {
						temp.put(customerId, temp.get(customerId) + expences);
					} else {
						temp.put(customerId, expences);
					}
					line = br.readLine();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		List<Integer> sortedKeys = sortMap(temp);
		for (Integer key : sortedKeys.subList(sortedKeys.size() - n, sortedKeys.size())) {
			result.put(key, temp.get(key));
		}
		return result;
	}
	
	/**
	 * Test
	 * @param args 
	 * 		paths to files
	 */
	public static void main(String[] args) {
		Map<Integer, Integer> m = processFiles(5, args);
		for (Integer k : m.keySet()) {
			System.out.println("customer_id: " + k + "\t expenses: " + m.get(k));
		}
	}
	
	/**
	 * Sort map by values
	 * @param map
	 * 		unsorted map
	 * @return map sorted by values
	 */
	private static List<Integer> sortMap(final Map<Integer, Integer> map) {
	    Set<Integer> set = map.keySet();
	    List<Integer> keys = new ArrayList<Integer>(set);
	    Collections.sort(keys, new Comparator<Integer>() {
	        @Override
	        public int compare(Integer i1, Integer i2) {
	            return map.get(i1) - map.get(i2);
	        }
	    });
	    return keys;
	}
}

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

The method sortMap is sorting the map by keys (customerIDs) and not the expenses. You should get the entries of the map Map.Entry<Integer,Integer> and sort by entry.value(), which would be the expense.

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

Create a max heap of size 5. Read the elements from the file and put it in to heap. finally u will be left with max 5 values

- bharadwajSrivatsa September 17, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

*min-heap. Whenever we find an expense less than top, remove top and add new expense element

- iwanna November 17, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Public class StaticM {



public static List<File> filesInDirectory(String sDirectory){

List<File> listFiles = new ArrayList<>();

File file = new File(sDirectory);

for(File file1: Arrays.asList(file.listFiles())){
if(file1.isDirectory()){
filesInDirectory(file1.toString());
}
else{
listFiles.add(file1);
}
}


return listFiles;
}


public static Map<String, Integer> FindMostExpCust() throws IOException{

MultiValueMap custExp = new MultiValueMap();
// keep all your files in temp directory
for(File file:StaticM.filesInDirectory("C:\\temp")){

FileReader reader = new FileReader(file);
BufferedReader bufRead = new BufferedReader(reader);
String line = "";
while((line=bufRead.readLine())!=null){
// CustomerID=12345, ProductID=456, Expenses=3200
custExp.put(line.split(",")[0].split("=")[1], Integer.parseInt(line.split(",")[2].split("=")[1]));
}

}

Map<String, Integer> mp1 = new HashMap<>();
int value=0;
Iterator<?> it = custExp.keySet().iterator();
while(it.hasNext()){
String key = (String) it.next();
for(int i=0;i<custExp.getCollection(key).toArray().length;i++){
value+=(int)custExp.getCollection(key).toArray()[i];
}
mp1.put(key, value);
}
return mp1;
}


public static void SortMap(Map<String,Integer> map){

List<?> list = new LinkedList(map.entrySet());
Collections.sort(list, new Comparator<Object>(){
public int compare(Object o1, Object o2){
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
});
HashMap sortedHashMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
sortedHashMap.put(entry.getKey(), entry.getValue());
}

System.out.println(sortedHashMap);

}

public static void main(String[]args) throws IOException{

StaticM.SortMap(StaticM.FindMostExpCust());

}

}

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

public class StaticM {



public static List<File> filesInDirectory(String sDirectory){

List<File> listFiles = new ArrayList<>();

File file = new File(sDirectory);

for(File file1: Arrays.asList(file.listFiles())){
if(file1.isDirectory()){
filesInDirectory(file1.toString());
}
else{
listFiles.add(file1);
}
}


return listFiles;
}


public static Map<String, Integer> FindMostExpCust() throws IOException{

MultiValueMap custExp = new MultiValueMap();
// keep all your files in temp directory
for(File file:StaticM.filesInDirectory("C:\\temp")){

FileReader reader = new FileReader(file);
BufferedReader bufRead = new BufferedReader(reader);
String line = "";
while((line=bufRead.readLine())!=null){
// CustomerID=12345, ProductID=456, Expenses=3200
custExp.put(line.split(",")[0].split("=")[1], Integer.parseInt(line.split(",")[2].split("=")[1]));
}

}

Map<String, Integer> mp1 = new HashMap<>();
int value=0;
Iterator<?> it = custExp.keySet().iterator();
while(it.hasNext()){
String key = (String) it.next();
for(int i=0;i<custExp.getCollection(key).toArray().length;i++){
value+=(int)custExp.getCollection(key).toArray()[i];
}
mp1.put(key, value);
}
return mp1;
}


public static void SortMap(Map<String,Integer> map){

List<?> list = new LinkedList(map.entrySet());
Collections.sort(list, new Comparator<Object>(){
public int compare(Object o1, Object o2){
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
});
HashMap sortedHashMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
sortedHashMap.put(entry.getKey(), entry.getValue());
}

System.out.println(sortedHashMap);

}

public static void main(String[]args) throws IOException{

StaticM.SortMap(StaticM.FindMostExpCust());

}

}

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

public class StaticM {



public static List<File> filesInDirectory(String sDirectory){

List<File> listFiles = new ArrayList<>();

File file = new File(sDirectory);

for(File file1: Arrays.asList(file.listFiles())){
if(file1.isDirectory()){
filesInDirectory(file1.toString());
}
else{
listFiles.add(file1);
}
}


return listFiles;
}


public static Map<String, Integer> FindMostExpCust() throws IOException{

MultiValueMap custExp = new MultiValueMap();
// keep all your files in temp directory
for(File file:StaticM.filesInDirectory("C:\\temp")){

FileReader reader = new FileReader(file);
BufferedReader bufRead = new BufferedReader(reader);
String line = "";
while((line=bufRead.readLine())!=null){
// CustomerID=12345, ProductID=456, Expenses=3200
custExp.put(line.split(",")[0].split("=")[1], Integer.parseInt(line.split(",")[2].split("=")[1]));
}

}

Map<String, Integer> mp1 = new HashMap<>();
int value=0;
Iterator<?> it = custExp.keySet().iterator();
while(it.hasNext()){
String key = (String) it.next();
for(int i=0;i<custExp.getCollection(key).toArray().length;i++){
value+=(int)custExp.getCollection(key).toArray()[i];
}
mp1.put(key, value);
}
return mp1;
}


public static void SortMap(Map<String,Integer> map){

List<?> list = new LinkedList(map.entrySet());
Collections.sort(list, new Comparator<Object>(){
public int compare(Object o1, Object o2){
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
});
HashMap sortedHashMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
sortedHashMap.put(entry.getKey(), entry.getValue());
}

System.out.println(sortedHashMap);

}

public static void main(String[]args) throws IOException{

StaticM.SortMap(StaticM.FindMostExpCust());

}

}

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

Use threads with volatile keyword,
Each file will have its own hashmap, product id as key
Create thread for each file.
Increment volatile variable with each customer find.

- AJ October 28, 2015 | 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