DEV Community

codingpineapple
codingpineapple

Posted on

LeetCode 1169. Invalid Transactions (javascript solution)

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

Top comments (2)

Collapse
 
cjleverett profile image
CJLeverett

I don't get it, I did something almost exactly the same but not sure why it won't pass.

function invalidTransactions(transactions) {
  const review = {};
  const invalidTransactions = [];

  for (const t of transactions) {
    const [name, time, , city] = t.split(',');

    if (name in review) review[name].push({ time, city });
    else review[name] = [{ time, city }];
  }

  for (const transaction of transactions) {
    const [name, time, amount, city] = transaction.split(',');
    const prevTransactions = review[name];

    if (amount > 1000) {
      invalidTransactions.push(transaction);
    }

    for (const prevTransaction of prevTransactions) {
      const { time: prevTime, city: prevCity } = prevTransaction;

      if (city !== prevCity && Math.abs(time - prevTime) <= 60) {
        invalidTransactions.push(transaction);
      }
    }
  }

  return Array.from(invalidTransactions);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
radoncreep profile image
radoncreep

nice