Domain 2MediumMEDIUM

Capital Gain/Loss

Calculate net capital gain/loss per stock by summing sell prices and subtracting buy prices using a hash map, then sort results alphabetically.

Domain: medium•Updated: 2026-09-15
#hash map#aggregation#sorting

Problem Breakdown

The goal of this problem is to calculate the total capital gain or loss for each stock name based on a series of transactions (buys and sells).

Inputs:

  • A collection of transaction records, typically represented as rows with columns: stock_name (string), operation_type (‘buy’/‘sell’), and price (integer/float). Note: While LeetCode 1393 is often presented in SQL contexts where the schema might vary slightly across platforms, for a Python walkthrough we assume standard transaction data.

Outputs:

  • A list or dictionary mapping each unique stock name to its net capital gain/loss. The result should typically be sorted alphabetically by stock_name (mimicking SQL’s default ordering).

Implicit Constraints & Edge Cases:

  1. Empty Input: If there are no transactions, the output should reflect an empty list or zero gains for all stocks if applicable.
  2. Missing Operations: A stock might only have ‘buy’ records without a corresponding ‘sell’. The net gain will be negative (loss). Conversely, it could start with sells? Usually, we assume valid sequences, but mathematically Sum(Sell) - Sum(Buy) holds regardless of order for the final balance.
  3. Data Types: Prices can be large integers; Python handles arbitrary precision automatically so overflow is not a concern like in C++/Java without care.
  4. Sorting: SQL queries usually require results ordered by stock_name. We must ensure our output maintains this order for consistency with the expected schema behavior.

Intuition

Brute Force Approach: We could iterate through every pair of ‘buy’ and ‘sell’ transactions to match them up (e.g., matching a buy at price P1P_1 with a sell at P2P_2, calculating profit). This is complex because we don’t know which specific buy corresponds to which sell without timestamps or IDs, leading to an O(N^2) complexity.

Key Insight: Capital gain/loss for a stock over time is simply the sum of all revenue (sells) minus the cost basis (buys). We do not need to match individual transactions; we can aggregate them per stock name independently. The net value is ∑(Price if Sell)−∑(Price if Buy)\sum (\text{Price if Sell}) - \sum (\text{Price if Buy}).

Optimal Approach: Use a hash map (dictionary in Python) keyed by stock_name. Iterate through the transaction list once, adding to or subtracting from the running total for each stock. Finally, sort and return results. This mirrors an SQL GROUP BY with conditional aggregation (SUM(CASE WHEN ...)).

Approach

  1. Initialize Storage: Create a dictionary (or use collections.defaultdict) where keys are stock_names and values store the cumulative gain/loss initialized to zero.
  2. Iterate Transactions: Loop through each transaction record in the input list:
    • If operation is ‘sell’, add the price to the stock’s total.
    • If operation is ‘buy’, subtract the price from the stock’s total (treating cost as negative gain).
  3. Sort Results: Convert the dictionary items into a list of tuples/dicts and sort them by stock_name alphabetically, matching typical SQL output requirements.
  4. Return Output: Return the sorted list containing (stock_name, capital_gain_loss).

Complexity Analysis

  • Time Complexity: O(Nlog⁡K)O(N \log K) or O(N+Klog⁡K)O(N + K \log K) where NN is the number of transactions and KK is the number of unique stocks. We iterate through all rows once (O(N)O(N)), then sort the results by stock name (O(Klog⁡K)O(K \log K)). Since K≤NK \le N, this simplifies to roughly linear-logarithmic time relative to input size, dominated by sorting if many distinct stocks exist.
  • Space Complexity: O(K)O(K) where KK is the number of unique stock_names stored in our hash map/dictionary.

Solution

from collections import defaultdict
from typing import List, Tuple

def capital_gain_loss(transactions: List[Tuple[str, str, int]]) -> List[List]:
    """
    Calculates total capital gain/loss per stock name based on buy/sell operations.
    
    Args:
        transactions: A list of tuples (stock_name, operation_type, price).
                      operation_type is 'buy' or 'sell'.
                      
    Returns:
        List of lists [[stock_name, gain_loss], ...] sorted by stock_name.
    """
    # Dictionary to accumulate net value per stock name
    capital_map = defaultdict(int)
    
    for stock_name, op_type, price in transactions:
        if op_type == 'sell':
            capital_map[stock_name] += price
        elif op_type == 'buy':
            capital_map[stock_name] -= price
            
    # Convert to list of lists and sort by stock name (alphabetical)
    result = [[name, val] for name, val in sorted(capital_map.items())]
    
    return result

# Example usage / Mock Test Data matching typical schema expectations:
if __name__ == "__main__":
    # Sample input mimicking the SQL table rows converted to Python list of tuples/objects
    data = [
        ("Stock A", "buy", 10), 
        ("Stock A", "sell", 25), 
        ("Stock B", "buy", 30)
    ]
    
    # Expected Output: [['Stock A', 15], ['Stock B', -30]] (Sorted by name)
    print(capital_gain_loss(data))

Edge Cases Handled

  • Empty Input: The loop simply doesn’t execute, returning an empty list [], which is the correct mathematical identity for sums.
  • Single Operation Type per Stock: If a stock only has ‘buy’ records, it correctly accumulates negative values (loss). Only sells results in positive gain; mixed operations result in net difference.
  • Sorting Consistency: The use of sorted() ensures the output is deterministic and ordered by stock_name, satisfying typical SQL query expectations for grouped data presentation.