Find Highest Weighted Venue Locations with Data Cleaning
SQL & DataModel answerLast updated
Compute top venue locations by summing vote weights using SQL and Python, while handling missing values, text normalization, and ties.
You are given a dataset containing user submissions for preferred event venues. Each entry consists of a voter_id, a string representing the location_text, and an optional numeric weight (defaults to 1 when unsupplied).
Write a solution in SQL and/or Python to determine the location(s) with the highest total vote weight.
Your solution must address the following requirements:
- Normalization: Treat inputs like
" New York ","new york", and"NEW YORK"as identical. Standardize location text by stripping leading/trailing spaces, collapsing consecutive internal whitespace, and normalizing letter case. - Missing or Invalid Locations: Ignore records where
location_textisNULL, missing, or reduces to an empty string after trimming. - Weight Parsing:
- A missing or
NULLweight defaults to1. - Non-numeric strings (e.g.,
"abc"), boolean values, non-finite values (NaN,Infinity), or negative weights must be considered invalid and discarded.
- A missing or
- Tie Handling: If multiple locations share the max aggregate weight, return all tied locations sorted alphabetically.
- Deduplication: Assume each row represents an independent valid vote unless stated otherwise (treat rows as additive).
Provide both SQL and Python implementations, walk through a sample execution, and analyze the time and space complexity.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying Assumptions & Edge Case Rules
Before diving into code, let's specify the required data transformation rules:
-
Text Normalization:
- Trim leading/trailing whitespace.
- Collapse internal multi-space gaps into a single space (e.g.,
"San Francisco"becomes"san francisco"). - Case-fold all strings to lowercase.
-
Weight Validation:
NULL/None/ empty string $\rightarrow$ Default weight of1.0.- String representations of positive finite numbers (e.g.,
"2.5") $\rightarrow$ Parse to float (2.5). - Non-numeric, negative, infinite (
inf),NaN, or boolean types $\rightarrow$ Reject the record.
-
Tie Resolution:
- Use
DENSE_RANK()in SQL or float tolerance comparisons (math.isclose) in Python to capture all locations matching the maximum aggregate sum. - Sort tied winners in alphabetical order.
- Use
1. SQL Solution
In SQL, we standardize strings using built-in functions, filter invalid rows, aggregate total weights, and rank the results using DENSE_RANK().
WITH cleaned_votes AS (
SELECT
-- Strip extra spaces and lower-case text
LOWER(TRIM(REGEXP_REPLACE(location_text, '\s+', ' ', 'g'))) AS norm_location,
-- Handle missing weights vs. invalid/malformed values
CASE
WHEN weight IS NULL THEN 1.0
WHEN TRY_CAST(weight AS NUMERIC) IS NOT NULL
AND CAST(weight AS NUMERIC) >= 0 THEN CAST(weight AS NUMERIC)
ELSE NULL
END AS parsed_weight
FROM votes
WHERE location_text IS NOT NULL
AND TRIM(location_text) <> ''
),
aggregated_totals AS (
SELECT
norm_location,
SUM(parsed_weight) AS total_weight
FROM cleaned_votes
WHERE parsed_weight IS NOT NULL
GROUP BY norm_location
),
ranked_locations AS (
SELECT
norm_location,
total_weight,
DENSE_RANK() OVER (ORDER BY total_weight DESC) AS rk
FROM aggregated_totals
)
SELECT
norm_location,
total_weight
FROM ranked_locations
WHERE rk = 1
ORDER BY norm_location;
2. Python Solution
In Python, we iterate through records, update aggregate sums using a hash map (defaultdict), handle precision issues via math.isclose, and sort winners alphabetically.
import math
import re
from collections import defaultdict
_REGEX_WHITESPACE = re.compile(r"\s+")
def clean_location(raw_text):
"""Normalizes string location or returns None if invalid."""
if not isinstance(raw_text, str):
return None
cleaned = _REGEX_WHITESPACE.sub(" ", raw_text).strip().lower()
return cleaned if cleaned else None
def parse_weight(raw_weight):
"""Parses weight into a non-negative float. Returns None for invalid inputs."""
if raw_weight is None or (isinstance(raw_weight, str) and raw_weight.strip() == ""):
return 1.0
if isinstance(raw_weight, bool):
return None
try:
val = float(raw_weight)
except (ValueError, TypeError):
return None
if not math.isfinite(val) or val < 0:
return None
return val
def find_most_popular_locations(records):
"""
Computes top location(s) by total weight.
Returns:
tuple: (list_of_winners, max_total_weight, skipped_count)
"""
location_weights = defaultdict(float)
skipped_count = 0
for rec in records:
loc = clean_location(rec.get("location_text"))
w = parse_weight(rec.get("weight"))
if loc is None or w is None:
skipped_count += 1
continue
location_weights[loc] += w
if not location_weights:
return [], 0.0, skipped_count
max_weight = max(location_weights.values())
# Collect all locations reaching max_weight within floating-point tolerance
top_locations = sorted([
loc for loc, total in location_weights.items()
if math.isclose(total, max_weight, rel_tol=1e-9, abs_tol=1e-9)
])
return top_locations, max_weight, skipped_count
Verification Walkthrough
Consider the following set of input votes:
| voter_id | location_text | weight | Processing Step | Resulting State |
|---|---|---|---|---|
| 1 | "Boston" | missing | Default weight 1.0 | boston: 1.0 |
| 2 | " boston " | 2 | Trimmed & lower-cased | boston: 3.0 |
| 3 | "Chicago" | 1.5 | Valid location & weight | chicago: 1.5 |
| 4 | "CHICAGO" | "1.5" | Parsed string weight | chicago: 3.0 |
| 5 | "" | 4.0 | Empty string dropped | Skipped (+1) |
| 6 | "Miami" | "invalid" | Non-numeric weight dropped | Skipped (+1) |
Execution Outcome:
boston: total aggregate weight =3.0chicago: total aggregate weight =3.0skipped_count:2- Result:
(["boston", "chicago"], 3.0, 2)
Complexity Analysis
Let $N$ be the number of raw vote entries, $L$ the average length of the location string, $K$ the number of unique normalized locations, and $T$ the number of tied top locations.
-
Time Complexity:
- Python: $O(N \cdot L)$ to iterate, clean text, and parse weights into the hash map. Finding the maximum total takes $O(K)$, and sorting top locations takes $O(T \log T)$. Overall time complexity is $O(N \cdot L + K + T \log T)$.
- SQL: Aggregation takes $O(N)$ with a hash-grouping strategy. Ranking $K$ grouped locations takes $O(K \log K)$ sorting step.
-
Space Complexity:
- Python: $O(K)$ auxiliary space to store unique locations and their aggregated totals inside the hash map.
- SQL: $O(K)$ memory used by the query engine for group-by aggregation and window function buffering.