Given a list of transactions where each transaction is represented as [merchant_id, currency, amount], and a string group_by that is either "merchant" or "currency", group the transactions by the specified attribute.
For each group, compute the frequency (number of transactions) and the total amount. Return a list of [group_key, count, total_amount] sorted by group_key in lexicographical order.
Function Signature
def group_transactions(transactions: list[list], group_by: str) -> list[list]:
Rules
-
Each transaction is a list
[merchant_id, currency, amount]
:
merchant_id
and
currency
are strings and
amount
is an integer.
-
When
group_by
is
"merchant"
, the group key is
merchant_id
. When it is
"currency"
, the group key is
currency
.
-
Each output row is
[group_key, count, total_amount]
, with
count
and
total_amount
as integers.
-
Sort rows by group key with ordinary string comparison by character code, so digits sort before letters and
"m10"
comes before
"m2"
.
Constraints
-
1 <= transactions.length <= 10⁴
-
Each transaction is
[merchant_id, currency, amount]
.
-
merchant_id
and
currency
are non-empty strings of lowercase letters and digits.
-
1 <= amount <= 10⁶
-
group_by
is either
"merchant"
or
"currency"
.
Examples
Input: transactions = [["shop1","usd",100],["shop2","eur",200],["shop1","usd",150],["shop2","usd",300],["shop1","eur",50]], group_by = "merchant"
Output: [["shop1",3,300],["shop2",2,500]]
Grouping by merchant, "shop1" has 3 transactions totaling 100 + 150 + 50 = 300, and "shop2" has 2 transactions totaling 200 + 300 = 500.
Input: transactions = [["shop1","usd",100],["shop2","eur",200],["shop1","usd",150],["shop2","usd",300],["shop1","eur",50]], group_by = "currency"
Output: [["eur",2,250],["usd",3,550]]
Grouping by currency, "eur" has 2 transactions totaling 200 + 50 = 250, and "usd" has 3 transactions totaling 100 + 150 + 300 = 550. "eur" sorts before "usd".
Input: transactions = [["m2","usd",5],["m10","usd",7],["m2","gbp",1]], group_by = "merchant"
Output: [["m10",1,7],["m2",2,6]]
"m2" has 2 transactions totaling 5 + 1 = 6 and "m10" has 1 transaction of 7. "m10" comes first because the character "1" sorts before "2".