ComeçarComece de graça

Implementing a duplicate transaction finder

Financial transaction logs must be validated to ensure each transaction ID is unique. Your task is to implement a method that efficiently checks for the presence of any duplicate transaction IDs.

Este exercício faz parte do curso

Optimizing Code in Java

Ver curso

Instruções do exercício

  • Initialize the seen variable as an empty Set.
  • Add transactions to seen if you've not encountered them before.
  • Return the appropriate boolean value if the loop ends without finding a duplicate.

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        TransactionProcessor processor = new TransactionProcessor();
        
        String[] transactions = {
            "TXN001", "TXN002", "TXN003", "TXN001", 
            "TXN004", "TXN005", "TXN003", "TXN006"
        };

        boolean hasDuplicates = processor.hasDuplicateTransactions(transactions);
        if (hasDuplicates) {
            System.out.println("Duplicate transactions detected!");
        } else {
            System.out.println("All transactions are unique.");
        }
    }
}

class TransactionProcessor {
    public boolean hasDuplicateTransactions(String[] transactionIds) {
        // Initialize an empty HashSet
        ____ seen = new ____<>();
        
        for (String transactionId : transactionIds) {
            if (seen.contains(transactionId)) {
                return true;
            } else {
                // First time seeing this transaction, add it to the set
                ____
            }
        }
        
        // Return true/false if no duplicates found
        return ____;
    }
}
Editar e executar o código