Sobes.tech
Junior — Senior

Validation of transaction list relative to balance

livecode

Task condition

The method checks the correctness of each operation. It takes a list of transactions and the current balance as input, against which the check is performed. The output is a map where the key is the transaction, and the value is a boolean indicating its validity. The number of elements in the input list and the resulting map are the same.

Check conditions:

  • Transactions are processed in ascending order of their id.
  • If a transaction with a certain id has already been processed, it is considered invalid.
  • All transactions with the same orderId as those already marked invalid are also considered invalid.
  • There are two types of operations – UP (increases balance) and DOWN (decreases balance).
  • If a DOWN operation results in a negative balance, that transaction is considered invalid.
public class TransactionService {

    public Map<Transaction, Boolean> validate(List<Transaction> transactions, long balance) {
        final var map = new HashMap<Transaction, Boolean>();
        final var ids = new ArrayList<UUID>();
        final var orderIds = new HashSet<Long>();

        for (Transaction transaction : transactions) {
            boolean isValid = false;
            final var orderId = transaction.getOrderId();
            final var isAddId = ids.add(transaction.getId());

            if (isAddId && !orderIds.contains(orderId)) {
                isValid = isValid(transaction, balance);
            }

            if (!isValid) {
                orderIds.add(orderId);
            }

            map.put(transaction, isValid);
        }

        return map;
    }

    public boolean isValid(Transaction transaction, Long balance) {
        final var tempBalance = switch (transaction.getType()) {
            case "UP" -> balance + transaction.getAmount();
            case "DOWN" -> balance - transaction.getAmount();
            default -> balance;
        };

        final var isValid = tempBalance >= 0;

        if (isValid) {
            balance = tempBalance;
        }

        return balance >= 0;
    }

    @Value
    public static class Transaction {
        UUID id;
        long orderId;
        String type;
        long amount;
    }
}