Apple | Phone | Basic sorting

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2022-02-05Added By Anonymous
Source: Link

Basically had a phone interview today and was pretty disappointed with the interviewer. I was told to compare two strings based on the second character. If we have list like this [["Hello", 2, 2.2342], ["World", 1, 2.7589], ["Jello", 3, 2.8373]]. It basically has to return [["World", 1, 2.7589], ["Hello", 2, 2.2342], ["Jello", 3, 2.8373]]. I suggested using a comparator since my preferred language is Java but I was unsure of the syntax and he wasn't positive on me checking me how to use it.


I basically implemented comparator using Collections.sort() then checked the .split(",") and then compared str1[1] to str2[1]. He seemed like he wanted a one liner instead.


I suggested something like this.

1 list.add("hello,1, 2.672"); 2 list.add("Gello,3, 3.14"); 3 list.add("adsfaello,2, 4.123"); 4 // Sort the array based on the second input 5 Collections.sort(list, new Comparator<String>() { 6 @Override 7 public int compare(String o1, String o2) { 8 String[] split1 = o1.split(","); 9 String[] split2 = o2.split(","); 10 return Integer.parseInt(split2[1]) - Integer.parseInt(split1[2]); 11 } 12 }); 13 System.out.println(list);


I then suggested a HashMap and PQ and he liked the of a HashMap but was confused on the PQ. I am not sure what he was looking for before he cut the call he told me its an easy one liner.


I feel really stupid. Did I just over think the problem too much or is there an actual one liner?

Comments