cswork / libraryOpen practice workspace

Coding questions · Microsoft

Compute most popular location with weights

This question evaluates a candidate's ability to perform weighted aggregation, data cleaning, tie-breaking logic, and handling of malformed or missing text fields using SQL and/or Python.

You are given a dataset of voting records for concert locations. Each record includes voter_id, location_text, and an optional numeric weight (default 1). Write SQL and/or Python to compute the most popular location by total vote weight. Explain how you handle ties, missing or malformed location_text, and verify correctness with a small example. Analyze the time and space complexity of your solution.

Compute Most Popular Concert Location by Weighted Votes

You are given a table of voting records for concert locations. Each record includes a voter_id, a location_text (free-form text), and an optional numeric weight. If weight is NULL, treat it as 1.

Write an SQL query to compute the most popular location(s) by total vote weight, with the following requirements:

  1. Ignore records where location_text is missing or malformed, defined as:
    • location_text IS NULL, or
    • location_text is an empty string '', or
    • location_text consists only of whitespace characters.
  2. When weight is NULL, treat it as the default value 1.
  3. Aggregate the total vote weight for each valid location_text.
  4. Return all location(s) whose total vote weight is equal to the maximum total vote weight (i.e., if there is a tie, return every tied location), along with that total weight.

Output columns:

  • location_text
  • total_weight

Additionally (no need to implement this in SQL), briefly describe how you would analyze the time and space complexity of your solution in Big-O terms, assuming an index on location_text.

Use the table definition and sample data provided below.

Table votes

columntypeconstraints
voter_idINTPRIMARY KEY
location_textVARCHAR(100)
weightINT

Sample data:

location_textvoter_idweight
Central Park11
Central Park23
Downtown Arena3NULL
Downtown Arena44
Riverside Stage5NULL
Riverside Stage6NULL
NULL74
82
91
Central Park10NULL

Expected output

Return all locations with the maximum total vote weight, after excluding records with missing/malformed location_text and treating NULL weights as 1. In the sample data, valid votes aggregate as:

  • Central Park: weights 1 + 3 + (NULL -> 1) = 5
  • Downtown Arena: (NULL -> 1) + 4 = 5
  • Riverside Stage: (NULL -> 1) + (NULL -> 1) = 2 The maximum total weight is 5, shared by Central Park and Downtown Arena, so both should be returned.
location_texttotal_weight
Central Park5
Downtown Arena5

Hints

  1. Filter out rows where TRIM(location_text) is NULL or an empty string before aggregating.
  2. Use COALESCE(weight, 1) to apply the default weight, then GROUP BY location_text and filter to rows with the maximum SUM(weight).