Amazon Interview Question for SDE-2s


Country: United States
Interview Type: In-Person




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

Kind of challenging to do this from scratch by writing algorithms, but using in-built libraries, we can come up with elegant code that gets the job done! :) For this problem, we need to use a mix of dictionaries/hashmaps + combinations generator + max-heaps. If we were doing this from scratch, obviously, this would amount to a lot of code! Therefore, I have outlined an elegant solution below.

Elegant solution in Python below:

import itertools
from collections import defaultdict
import heapq

class Product:
  def __init__(self, aisleId, productId, price):
    self.aisleId = aisleId
    self.productId = productId
    self.price = price

def getKHighestPrices(products, k):
  # Structure of the data structure will be as follows:
  # Aisle IDs: [Prices]
  aisleMap = defaultdict(list)
  for product in products:
    aisleMap[product.aisleId].append(product.price)

  heap = []
  for combination in itertools.product(*aisleMap.values()):
    # The negation is for max-heaps
    heapq.heappush(heap, (-sum(combination), combination))
  result = []
  while k > 0:
    priceList = heapq.heappop(heap)[1]
    formattedStringPriceList = ','.join([('$%s' % price) for price in sorted(priceList,reverse=True)])
    result.append(formattedStringPriceList)
    k = k - 1

  return result

Test code:

# Aisle 1 Products
p11 = Product(1,100,4)
p12 = Product(1,101,2)
p13 = Product(1,102,5)

# Aisle 2 Products
p21 = Product(2, 200, 1)
p22 = Product(2, 201, 6)

totalProducts = [p11, p12, p13, p21, p22]
print(getKHighestPrices(totalProducts, 2)) #['$6,$5', '$6,$4']
print(getKHighestPrices(totalProducts, 5)) #['$6,$5', '$6,$4', '$6,$2', '$5,$1', '$4,$1']

- prudent_programmer March 09, 2018 | 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