Invalid Transactions — LeetCode 1169 Python Solution

MediumArrayHash TableStringSorting
Problem
#1169
Pattern
Sorting
Reading time
3 min

The problem

A transaction is possibly invalid if: the amount exceeds $1000, or; if it occurs within (and including) 60 minutes 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.

Example

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.

Python solution

Python
class Solution:
    def invalidTransactions(self, transactions: List[str]) -> List[str]:
        d = defaultdict(list)
        idx = set()
        for i, x in enumerate(transactions):
            name, time, amount, city = x.split(",")
            time, amount = int(time), int(amount)
            d[name].append((time, city, i))
            if amount > 1000:
                idx.add(i)
            for t, c, j in d[name]:
                if c != city and abs(time - t) <= 60:
                    idx.add(i)
                    idx.add(j)
        return [transactions[i] for i in idx]

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1169. Invalid Transactions is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1169. Invalid Transactions?
LeetCode 1169. Invalid Transactions is rated Medium on LeetCode.
What is the time complexity of LeetCode 1169. Invalid Transactions?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 1169. Invalid Transactions?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1169. Invalid Transactions cover?
LeetCode 1169. Invalid Transactions is tagged Array, Hash Table, String and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview