Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Summarize Python Sales Records

Easy
EasyCodingHash TablesMathArrays

Problem

At Acme Analytics, raw sales events are represented as Python dictionaries. Write a function that groups valid records by category, sums revenue per category, and returns the top k categories.

A record is valid only if it contains the keys category, price, and quantity, where category is a non-empty string and both price and quantity are non-negative numbers. Revenue for one record is price * quantity. If multiple valid records share the same category, their revenues should be added together. Return the result as a list of [category, total_revenue] pairs sorted by descending total revenue; if two categories have the same revenue, sort them by ascending category name. Return only the first k pairs. If k is larger than the number of categories, return all categories.

Constraints

  • 1 <= len(records) <= 10^4
  • Each record is a Python dictionary
  • 0 <= price, quantity <= 10^6 for valid records
  • 1 <= k <= 10^4
  • Ignore records missing required keys or containing invalid values

Function Signature

def top_category_revenue(records, k):
Take this as a live interview session →

You are practicing as a guest. Sign up free to run your code against the sample data. Your draft stays right here.

Sign up freeI have an account
def solve(rows):
    counts = {}
    for row in rows:
        ...
    return result
Sign up to unlock solutions
Next questions
SupermicroAggregate Sales by CategoryMediumClean and Summarize Event RecordsEasySalesforceTop Customers by Event SpendMedium