Invalid Transactions Problem
Description
LeetCode Problem 1169.
A transaction is possibly invalid if:
- the amount exceeds
$1000, or; - if it occurs within (and including)
60minutes of another transaction with the same name in a different city.
You are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction.
Return a list of transactions that are possibly invalid. You may return the answer in any order.
Example 1:
Input: transactions = ["alice,20,800,mtv","alice,50,100,beijing"]
Output: ["alice,20,800,mtv","alice,50,100,beijing"]
Explanation: The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.
Example 2:
Input: transactions = ["alice,20,800,mtv","alice,50,1200,mtv"]
Output: ["alice,50,1200,mtv"]
Example 3:
Input: transactions = ["alice,20,800,mtv","bob,50,1200,mtv"]
Output: ["bob,50,1200,mtv"]
Constraints:
transactions.length <= 1000- Each
transactions[i]takes the form"{name},{time},{amount},{city}" - Each
{name}and{city}consist of lowercase English letters, and have lengths between1and10. - Each
{time}consist of digits, and represent an integer between0and1000. - Each
{amount}consist of digits, and represent an integer between0and2000.
Solution
Approach: Check Every Pair
There are at most 1000 transactions, so we can simply compare each one with all the others.
First split every transaction into its name, time, amount and city. Then a transaction i is possibly invalid if:
- its amount is greater than
1000, or - some transaction
jhas the same name, a different city, and|time[i] - time[j]| <= 60.
Each invalid transaction is added to the answer once, even if it conflicts with several others. A transaction never conflicts with itself, because its city is the same; but identical copies of a transaction are separate entries, and each one is kept or dropped on its own.
Complexity: O(n2) time, which is fine for n ≤ 1000, and O(n) space for the parsed fields.
class Solution:
def invalidTransactions(self, transactions: List[str]) -> List[str]:
parsed = []
for t in transactions:
name, time, amount, city = t.split(",")
parsed.append((name, int(time), int(amount), city))
ans = []
for i, (name, time, amount, city) in enumerate(parsed):
bad = amount > 1000 or any(
name == other_name and city != other_city and abs(time - other_time) <= 60
for other_name, other_time, _, other_city in parsed
)
if bad:
ans.append(transactions[i])
return ans