#1169

Invalid Transactions

Medium
ArrayHash TableStringSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a single pass through the transactions while utilizing a hashmap to store transactions by name and city. This allows us to efficiently check for invalid transactions without needing nested loops.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a list to store invalid transactions and a hashmap to store transactions by name and city.
  2. 2Step 2: Iterate through the transactions and check if the amount exceeds $1000; if so, add it to the invalid list.
  3. 3Step 3: For each transaction, check the hashmap for any transactions with the same name in different cities within 60 minutes and add them to the invalid list.
solution.py24 lines
1# Full working Python code
2
3def invalidTransactions(transactions):
4    from collections import defaultdict
5    invalid = set()
6    transaction_map = defaultdict(list)
7    n = len(transactions)
8    for i in range(n):
9        name, time, amount, city = transactions[i].split(',')
10        time = int(time)
11        amount = int(amount)
12        if amount > 1000:
13            invalid.add(transactions[i])
14        transaction_map[name].append((time, city, transactions[i]))
15    for name, trans in transaction_map.items():
16        for i in range(len(trans)):
17            time1, city1, trans1 = trans[i]
18            for j in range(len(trans)):
19                if i != j:
20                    time2, city2, trans2 = trans[j]
21                    if city1 != city2 and abs(time1 - time2) <= 60:
22                        invalid.add(trans1)
23                        invalid.add(trans2)
24    return list(invalid)

Complexity note: The time complexity is O(n) because we only make a single pass through the transactions and use a hashmap for quick lookups. The space complexity is O(n) due to the storage of transactions in the hashmap.

  • 1Transactions can be invalid due to amount or timing/location conflicts.
  • 2Using a hashmap allows for faster lookups and reduces the need for nested loops.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.