Most Balanced Partition solved

This Python program is designed to solve a problem related to file systems. Given a tree structure representing a file system, where each node has a parent and a size, the task is to find the most balanced partition. The balance of a partition is defined as the absolute difference between the sum of sizes in two parts of the partition.

Secure your next interview 🎯

CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷

Here is the Most Balanced Partition solved from HackerRank using CodeRankGPT:

The solution works by first creating a list of children for each node in the tree. Then, it calculates the sum of sizes for each subtree rooted at each node. This is done recursively, starting from the root. Finally, it finds the minimum absolute difference between the total size of the tree and twice the size of each subtree, excluding the root. This gives the most balanced partition.


import math
import os
import random
import re
import sys

def mostBalancedPartition(parent, files_size):
    n = len(parent)
    children = [[] for _ in range(n)]
    for i in range(1, n):
        children[parent[i]].append(i)
    size_sums = [None for _ in range(n)]
    
    def size_sums_rec(i):
        size_sums[i] = files_size[i] + sum(size_sums_rec(c) for c in children[i])
        return size_sums[i]
        
    size_sums_rec(0)
    return min(abs(size_sums[0] - 2 * ss) for ss in size_sums[1:])

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    parent_count = int(input().strip())

    parent = []

    for _ in range(parent_count):
        parent_item = int(input().strip())
        parent.append(parent_item)

    files_size_count = int(input().strip())

    files_size = []

    for _ in range(files_size_count):
        files_size_item = int(input().strip())
        files_size.append(files_size_item)

    result = mostBalancedPartition(parent, files_size)

    fptr.write(str(result) + '\n')

    fptr.close()

If you have a HackerRank Certification test or a coding interview coming up, you can use CodeRankGPT to your advantage. It will assist you during your test and help ensure you get the certification or the job.

AI is here now, and other candidates might be using it to get ahead and win the job. 🧐

Built on Unicorn Platform