Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Choosing the Right Data Structure for Business Problems

Wrong structure = Slow code + crashed apps RIGHT structure = 1000x faster + promotion

This decision matrix = Interview question #1


🎯 The Business Decision Matrix

ProblemBEST StructureWhyWrong Choice Cost
Sales historyListOrdered time seriesMessy dicts
Customer profilesDictKey-value lookupSlow list search
Unique productsSetDuplicate removal1000x slower
Fixed recordsTupleImmutable + fastBuggy lists
Product catalogDict of tuplesFast + safeMemory explosion

REAL BUSINESS PROBLEMS → RIGHT SOLUTIONS

Buckle up, you data-wrestling wannabe—this is the main event where data structures throw down to solve real business problems! Lists, dicts, sets, and tuples are in the cage, and only the right one walks out with your company’s cash. Pick wrong, and your app’s slower than a jobber eating a suplex. These code snippets are cage matches with punchlines that’ll hit harder than a steel chair. Watch the champs dominate and the losers get pinned!

Problem 1: Monthly Sales Analysis – Lists Slam the Competition Lists are the heavyweight champ for ordered sales data, slicing quarters like a pro wrestler cutting promos. Dicts in this ring? They’re just extra baggage.

## Champ: Lists body-slam time series
sales = [25000, 28000, 32000, 29000]
q1 = sales[:3]  # Slice like a steel chair swing
print(f"📊 Q1 Knockout: ${sum(q1):,.0f}")  # $85,000—List wins by pinfall!

## Loser: Dict tries to wrestle ordered data
bad_sales = {1: 25000, 2: 28000, 3: 32000}
## q1 = ? No slicing! Dict taps out in shame.

Use a dict here? It’s like bringing a folding chair to a title match—awkward and useless. List gloats, “No keys needed, you overcomplicated chump!”

Problem 2: Customer Lookup – Dicts Deliver a TKO Dicts are the speedy striker, fetching customer data faster than a flying dropkick. Lists in this fight? They’re crawling through a million rows.

## Champ: Dicts land a knockout punch
customers = {'alice': {'spend': 5000, 'vip': True}, 'bob': {'spend': 1200}}
print(f"💥 Alice’s Spend: ${customers['alice']['spend']:,}")  # Instant TKO!

## Loser: List stumbles in the ring
bad_customers = [{'id': 'alice', 'spend': 5000}, {'id': 'bob', 'spend': 1200}]
## for c in bad_customers: if c['id'] == 'alice': ... SLOW AS HELL!

Try a list for lookups? It’s a 10-count pin, with “O(n) search time, you punch-drunk rookie!” KeyError taunts, “Wrong key? Back to the locker room!”

Problem 3: Product Deduplication – Sets Crush the Clones Sets are the grappler who body-slams duplicates out of the ring. Lists trying to de-dupe? They’re stuck in a chokehold writing loops.

## Champ: Sets pin duplicates in one move
products = ['laptop', 'phone', 'laptop', 'tablet']
unique = set(products)
print(f"🎯 Unique Gear: {len(unique)} ({sorted(unique)})")  # 3—Duplicates crushed!

## Loser: List fumbles with manual cleanup
bad_products = ['laptop', 'phone', 'laptop']
## unique = [] for p in bad_products: if p not in unique: ... 10 lines of pain!

Keep duplicates in a list? Set flexes, “Repeats in my ring? You’re disqualified, you repetitive reject!”

Problem 4: Fixed Records – Tuples Tank the Changes Tuples are the ironclad tank, locking records like a cage with no key. Lists here? They’re begging to be rewritten by some rookie coder.

## Champ: Tuples lock it down
store = (40.7, -74.0, 'NYC')
try:
    store[0] = 0
except TypeError:
    print("🔒 Tuple tanks your edit: No changes, you ring-rattling reject!")
print(f"📍 Secure Store: {store}")

## Loser: List leaves the vault open
bad_store = [40.7, -74.0, 'NYC']
bad_store[0] = 0  # Whoops, NYC’s now in Narnia!

Change a tuple? TypeError slams, “Immutable, you data-dropping dumbass—go rewrite a list!”

Problem 5: Combined Power – The Tag-Team Finisher Mix structures like a tag-team dream match: dicts for lookups, tuples for records, sets for uniques, lists for history. Wrong combo? You’re pinned.

business_data = {
    'customers': {'alice': ('Alice', 5000, True), 'bob': ('Bob', 1200, False)},  # Dict + Tuple
    'sales': [25000, 28000, 32000],  # List
    'products': {'laptop', 'phone'}   # Set
}
total_sales = sum(business_data['sales'])
vips = {k for k, v in business_data['customers'].items() if v[2]}
unique_products = len(business_data['products'])
print("🥊 Tag-Team Takedown:")
print(f"   Total Sales: ${total_sales:,.0f}")
print(f"   VIPs: {vips}")
print(f"   Unique Products: {unique_products}")

Wrong structure? The ref calls, “Bad pick! Your app’s crashing harder than a botched moonsault!”

# Your code here

Exercise

Add best_sales_month(sales) to find the month with highest revenue and return it as a string.