Transformer Voltage Stability

Moderate
0/80
0 upvote
Asked in company
ServiceNow

Problem statement

You are given an n-ary tree representing a network of transformers. Each node in the tree is a transformer with a specific integer voltage value.

The entire network is considered stable if and only if every transformer in the network adheres to a strict stability rule. The rule is as follows:

For any given transformer (node), the average voltage of all its descendants must be strictly less than the voltage of the transformer itself.

Your task is to determine if the given transformer network is stable.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains an integer 'N', the number of transformers (nodes).
The second line contains 'N' space-separated integers, where the i-th integer is the voltage of node i.
The third line contains 'N' space-separated integers, representing a parent array. The i-th integer is the parent of node i. The root node has a parent of -1.


Output Format:
Print the string STABLE if every node in the tree satisfies the stability rule.
Otherwise, print the string UNSTABLE.


Note:
A node's descendants are all the nodes in its subtree, excluding the node itself.
A leaf node has no descendants. The sum and count of its descendants are both 0. A leaf node is always considered stable by definition.
The problem uses 0-based indexing for nodes.
Sample Input 1:
4
20 10 5 8
-1 0 0 1


Sample Output 1:
STABLE


Explanation for Sample 1:
The tree structure is: 0 is the root with children 1 and 2. Node 1 has a child 3.
- Node 3 (leaf): Stable by definition.
- Node 2 (leaf): Stable by definition.
- Node 1: Has one descendant, node 3 (voltage 8). Average = 8/1 = 8. Node 1's voltage is 10. Since `8 < 10`, node 1 is stable.
- Node 0: Has three descendants: 1, 2, and 3 (voltages 10, 5, 8). Sum = 23, Count = 3. Average = 23/3 ≈ 7.67. Node 0's voltage is 20. Since `7.67 < 20`, node 0 is stable.
Since all nodes are stable, the entire network is STABLE.


Sample Input 2:
3
5 8 6
-1 0 0


Sample Output 2:
UNSTABLE


Explanation for Sample 2:
The tree has root 0 with children 1 and 2.
- Node 1 (leaf): Stable.
- Node 2 (leaf): Stable.
- Node 0: Has two descendants: 1 and 2 (voltages 8, 6). Sum = 14, Count = 2. Average = 14/2 = 7. Node 0's voltage is 5. The condition `7 < 5` is false.
Since node 0 is not stable, the entire network is UNSTABLE.


Expected Time Complexity:
The expected time complexity is O(N).


Constraints:
1 <= N <= 10^5
1 <= voltage <= 10^9

Time limit: 1 sec
Approaches (1)
Transformer Voltage Stability
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Transformer Voltage Stability
Full screen
Console