LeetCode- 1169. Invalid Transactions

1 minute read

Problem statement :-

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. Each transaction string transactions[i] consists of comma separated values representing the name, time (in minutes), amount, and city of the transaction.

Given a list of transactions, return a list of transactions that are possibly invalid. You may return the answer in any order.

Example

Input: transactions = ["alice,20,800,mtv","alice,50,100,beijing"]
Output: ["alice,20,800,mtv","alice,50,100,beijing"]
Input: transactions = ["alice,20,800,mtv","alice,50,1200,mtv"]
Output: ["alice,50,1200,mtv"]
Input: transactions = ["alice,20,800,mtv","bob,50,1200,mtv"]
Output: ["bob,50,1200,mtv"]

Solution

The input is a list of strings which has name, time (in minutes), amount, and city separated by commas. So first we need to split the string into individual components, We can do this by following.

records = []
for t in transactions:
  rec = t.split(',')
  rec[1] = int(rec[1])
  rec[2] = int(rec[2])
  records.append(rec)

As the question implies there are two conditions where the a transaction is said to be invalid. First one is pretty straight forward when the amount is greater than 1000. Second condition requires to compare each of transaction with every other transaction to check whether there exist any other transaction with same name and different city & time difference = 60.

for rec in records:
  if rec[2] > 1000:
    rec[1] = str(rec[1]
    rec[2] = str(rec[2])
    res.append(','.join(rec))
    continue
    for x in records:
      if rec[0] == x[0] and abs(rec[1]-int(x[1])) <= 60 and rec[3] != x[3]:
        rec[1] = str(rec[1])
        rec[2] = str(rec[2])
        res.append(','.join(rec))
        break

Output should be a list of string similar to the input using join you can combine multiple variables into a string. Here is the full code

class Solution:
  def invalidTransactions(self, transactions):
    res = []
    records = []
    for t in transactions:
      rec = t.split(',')
      rec[1] = int(rec[1])
      rec[2] = int(rec[2])
      records.append(rec)
    for rec in records:
      if rec[2] > 1000:
        rec[1] = str(rec[1])
        rec[2] = str(rec[2])
        res.append(','.join(rec))
        continue
      for x in records:
        if rec[0] == x[0] and abs(rec[1]-int(x[1])) <= 60 and rec[3] != x[3]:
          rec[1] = str(rec[1])
          rec[2] = str(rec[2])
          res.append(','.join(rec))
          break
  return res