Amazon Interview Question
Country: United States
a = ["User:A Bandwidth:50 CountryCode:IND",
"User:B Bandwidth:60 CountryCode:USA",
"User:C Bandwidth:60 CountryCode:IND",
"User:D Bandwidth:80 CountryCode:IND",
"User:A Bandwidth:70 CountryCode:IND"]
const parsed = a.map(line => {
const [user, bandwidth, countryCode] = line.split(' ').map(value=>value.split(':')[1])
return { user, bandwidth, countryCode}
})
const users = parsed.reduce( (output, {user,bandwidth,countryCode}) => {
const existing = output[user]
output[user] = {
bandwidth: parseInt(bandwidth) + (existing? parseInt(existing.bandwidth) : 0),
countryCode
}
return output
} , {})
const countries = Object.entries(users).reduce( (output, [user, {bandwidth, countryCode}]) => {
const existing = output[countryCode]
const rank = existing? [...existing.rank, {user,bandwidth}] : [{user,bandwidth}]
output[countryCode] = {
rank: rank.sort((a,b)=> b.bandwidth - a.bandwidth).slice(0,5)
}
return output;
}
,{})
console.log(JSON.stringify(countries))
a = ["User:A Bandwidth:50 CountryCode:IND",
"User:B Bandwidth:60 CountryCode:USA",
"User:C Bandwidth:60 CountryCode:IND",
"User:D Bandwidth:80 CountryCode:IND",
"User:A Bandwidth:70 CountryCode:IND"]
const parsed = a.map(line => {
const [user, bandwidth, countryCode] = line.split(' ').map(value=>value.split(':')[1])
return { user, bandwidth, countryCode}
})
const users = parsed.reduce( (output, {user,bandwidth,countryCode}) => {
const existing = output[user]
output[user] = {
bandwidth: parseInt(bandwidth) + (existing? parseInt(existing.bandwidth) : 0),
countryCode
}
return output
} , {})
const countries = Object.entries(users).reduce( (output, [user, {bandwidth, countryCode}]) => {
const existing = output[countryCode]
const rank = existing? [...existing.rank, {user,bandwidth}] : [{user,bandwidth}]
output[countryCode] = {
rank: rank.sort((a,b)=> b.bandwidth - a.bandwidth).slice(0,5)
}
return output;
}
,{})
console.log(JSON.stringify(countries))
Create two maps A) User -> BW - each time update BW for that user,
- Sunny August 19, 2017and B) Country -> MaxHeap( Object holding User and BW ) based on BW
(i) Get total BW by map.get(user)
(ii) Get top 5 by popping max element and rebuilding the heap - O(klogk) k = 5.