NewProject Coding is here — build features and fix bugs in real codebases with an AI assistantSee what's new

Design a stateful loan processor. The processor is initialized with direct parent-child relationships between companies and then receives loan records one at a time.

Implement the LoanProcessor class:

  • LoanProcessor(List<List<String>> companyRelations) initializes the processor with the company hierarchy.

    • Each entry in companyRelations has the format [parentCompany, childCompany] and represents a direct ownership relationship.
    • The company hierarchy is acyclic, and each company has at most one direct parent.
  • void createLoan(List<String> loan) processes and stores one loan. Each loan has the format [loanId, userId, merchant, amount].

    • Follow the merchant's parent chain and associate the loan with its top-level company.
    • A non-empty merchant with no parent is its own top-level company, even if it does not appear in companyRelations.
    • If the merchant is empty, ignore the loan.
  • List<List<String>> getAggregatedLoans() calculate the current aggregation. Return one group for every top-level company with at least one stored loan. Each group has the format [topLevelCompany, loanId1, loanId2, ...].

    • Only loan IDs are included in the returned result, although the processor retains the information required for later operations.
    • The order of groups and loan IDs is not specified.

Constraints:

  • 0 ≤ companyRelations.size() ≤ 105.
  • The company hierarchy is acyclic, and each company has at most one direct parent.
  • loanId, userId, and amount are non-empty; merchant may be empty.
  • At most 105 total method calls will be made.
  • The total number of loan IDs returned across all calls to getAggregatedLoans does not exceed 105.

Example:

Input: ["LoanProcessor", "createLoan", "createLoan", "createLoan", "createLoan", "getAggregatedLoans"] [[[["AA", "BB"], ["AA", "CC"], ["DD", "AA"], ["FF", "EE"]]], [["L1", "U1", "CC", "100"]], [["L2", "U2", "AA", "200"]], [["L3", "U3", "EE", "300"]], [["L4", "U4", "", "400"]], []]

Output: [null, null, null, null, null, [["DD", "L1", "L2"], ["FF", "L3"]]]

Explanation:

  • processor = new LoanProcessor(companyRelations);
  • processor.createLoan(["L1", "U1", "CC", "100"]); // "CC" resolves through "AA" to "DD", so "L1" is stored under "DD".
  • processor.createLoan(["L2", "U2", "AA", "200"]); // "AA" resolves to "DD", so "L2" is stored under the same group.
  • processor.createLoan(["L3", "U3", "EE", "300"]); // "EE" resolves to "FF", so "L3" is stored under "FF".
  • processor.createLoan(["L4", "U4", "", "400"]); // Returns null. The merchant is empty, so the loan is ignored.
  • processor.getAggregatedLoans(); // Returns [["DD", "L1", "L2"], ["FF", "L3"]].

Accepted
720/2.6k
Acceptance Rate28.0%
Test Cases
Input
Output
Expected