DEV Community

loading...

LeetCode 1169. Invalid Transactions (javascript solution)

codingpineapple
・1 min read

Description:

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.

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

Solution:

Time Complexity : O(n^2)
Space Complexity: O(n)

const isInvalid = (transaction, map) => {
  const [name, time, amount, city] = transaction.split(',')

  if (amount > 1000) return true

  const prevTrans = map[name]

  for (const trans of prevTrans) {
    if (city !== trans.city && Math.abs(time - trans.time) <= 60) return true
  }

    return false
}

const invalidTransactions = transactions => {
  const invalid = []
  const map = {}

  // Sepearate transactions by name
  for (const trans of transactions) {
    const [name, time, amount, city] = trans.split(',')

    // Create a list of transactions under each name
    if (name in map) map[name].push({ time, city })
    else map[name] = [{ time, city }]
  }

  // Validate transactions
  for (const trans of transactions) {    
    if (isInvalid(trans, map)) invalid.push(trans)
  }

  return invalid
};
Enter fullscreen mode Exit fullscreen mode

Discussion (0)