Consolidated Account Balances
At Paytm, managing user accounts and their associated balances is fundamental. Users or entities might have multiple accounts that are linked due to various reasons, such as joint ventures, shared ownership, or related business operations. For accurate financial reporting, risk assessment, or even just providing a unified view to a customer, it's crucial to consolidate the balances of all accounts that belong to the same 'network' of related accounts.
This problem asks you to implement a system that takes a list of individual accounts and a list of known relationships between account IDs. Your task is to identify all distinct networks of related accounts and report the total consolidated balance for each network.
Implement the function consolidateAccountBalances that:
relatedPairs, merging accounts that are directly or indirectly linked into larger networks.Input:
accounts: An array of Account objects. Each Account has two properties: id (a unique number representing the account ID) and balance (a number representing the current balance in that account).
interface Account {
id: number;
balance: number;
}
relatedPairs: An array of pairs of account IDs, where each inner array [id1, id2] signifies that account id1 and account id2 are related. This relationship is transitive; if A is related to B, and B is related to C, then A, B, and C are all part of the same network.Output:
numbers, where each number represents the total consolidated balance of a distinct network of related accounts. The order of balances in the output array does not matter.Examples
Example 1
Input:
accounts = [{id: 1, balance: 100}, {id: 2, balance: 200}, {id: 3, balance: 300}], relatedPairs = [[1, 2]]
Output:
[300, 300]
Note:
Accounts 1 and 2 are related, forming a network with a total balance of 100 + 200 = 300. Account 3 is unrelated and forms its own network with a balance of 300. The order of balances in the output does not matter.
Example 2
Input:
accounts = [{id: 1, balance: 100}, {id: 2, balance: 200}, {id: 3, balance: 300}, {id: 4, balance: 400}], relatedPairs = [[1, 2], [3, 4], [2, 3]]
Output:
[1000]
Note:
Initially, (1,2) are linked, and (3,4) are linked. Then (2,3) links these two groups, making all four accounts part of a single network. The total balance is 100 + 200 + 300 + 400 = 1000.
Example 3
Input:
accounts = [{id: 1, balance: 50}, {id: 2, balance: -20}, {id: 3, balance: 100}], relatedPairs = []
Output:
[50, -20, 100]
Note:
No accounts are explicitly related. Each account forms its own network, and their individual balances are returned. The order of balances in the output does not matter.
Constraints
1 <= accounts.length <= 10^40 <= relatedPairs.length <= 10^41 <= account.id <= 10^5 (Account IDs are positive integers)-10^9 <= account.balance <= 10^9relatedPairs are guaranteed to exist in the accounts input array.relatedPairs.relatedPairs containing non-existent account IDs).Loading editor...