Invalid Transactions

We need to find the transactions that are possibly invalid according to the given criteria. We can do this by following these steps:

  1. Parse the Transactions: Parse the transactions into a more accessible structure, separating the name, time, amount, and city.

  2. Create a Dictionary to Store User Transactions: This will allow us to easily access all transactions for a particular user.

  3. Iterate through the Transactions: Check each transaction to see if it’s invalid. A transaction is invalid if either: a. The amount exceeds $1000. b. There is another transaction with the same name, in a different city, and within 60 minutes of the current transaction.

  4. Add Invalid Transactions to the Result: If a transaction is found to be invalid, add it to the result list.

Here’s the code implementing these steps:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from collections import defaultdict

class Solution:
    def invalidTransactions(self, transactions: List[str]) -> List[str]:
        # Dictionary to store user transactions
        user_transactions = defaultdict(list)

        # Parsing transactions and populating user_transactions
        for transaction in transactions:
            name, time, amount, city = transaction.split(',')
            time, amount = int(time), int(amount)
            user_transactions[name].append((time, amount, city, transaction))

        # List to store invalid transactions
        invalid_transactions = []

        # Function to check if two transactions are within 60 minutes and different cities
        def isInvalid(t1, t2):
            return abs(t1[0] - t2[0]) <= 60 and t1[2] != t2[2]

        # Checking each user's transactions
        for transactions in user_transactions.values():
            # Dictionary to mark already checked invalid transactions
            checked = {}
            for i, t1 in enumerate(transactions):
                if t1[1] > 1000:
                    invalid_transactions.append(t1[3])
                    continue

                # Compare with other transactions of the same user
                for j, t2 in enumerate(transactions):
                    if i != j and isInvalid(t1, t2) and not checked.get(i, False):
                        invalid_transactions.append(t1[3])
                        checked[i] = True
                        break

        return invalid_transactions

This code will identify the invalid transactions based on the provided criteria.