Find Total Imbalance Amazon OA 2022 Solution

Page Contents

Want to solve Find Total Imbalance Amazon OA?, if yes then this article is for you.

We have research and collected a bundle of questions which was asked in Amazon OA in the year of 2021 and 2022. Today, we are going to see another problem from amazon oa called Find Total Imbalance which was asked in 2022, this questions might be still active in some of the Amazon OA so save all the solutions and lets see how can we solve this problem.

Find Total Imbalance Amazon OA Solution

Given an array ranks of ranks of students in a school. All students need to be split into groups k. Find the total ‘imbalance’ of all groups. An imbalance of a group can be found as :

  1. Sorting each group in the order of their ranks.
  2. A group contributes to imbalance if any 2 students in the sorted array have a rank difference of more than 1.

Find the total sum of imbalance of all such groups.

This is the example that was given :
[4,1,3,2]
[1] contributes 0 to imbalance
[2] contributes 0 to imbalance
[3] contributes 0 to imbalance
[4] contributes 0 to imbalance
[4,1] contributes 1 to imbalance
[4,3] contributes 0 to imbalance
[4,2] contributes 1 to imbalance
[4,1,3,2] contributes 0 to imbalance
[1,3] contributes 1 to imbalance
[1,2] contributes 0 to imbalance
[3,2] contributes 0 to imbalance
Answer = 1 + 1 + 1 = 3

Looped over the array to find subarrays and then loop over them to check condition. Passed 8 out of 14 test cases. TLE for rest.

Related: Google Online Assessment 2022 Questions List

Find Total Imbalance Amazon OA 2022
Find Total Imbalance Amazon OA 2022

SOLUTION

Program: Find Total Imbalance Amazon OA Solution in Java

public static long imbalance(List<Integer> rank) {
	long imbalance = 0;
	int r = 0;
	TreeSet<Integer> set = new TreeSet<>();
	while(r < rank.size()-1) {
		set.clear();
		set.add(rank.get(r));
		long curImbalance = 0;
		for(int i=r+1; i<rank.size(); i++) {
			Integer e = rank.get(i);
			set.add(e);
			Integer f = set.lower(e);
			Integer c = set.higher(e);
			
			if(f == null) { // added at beginning
				curImbalance += (((c - e) > 1) ? 1 : 0);
			}
			else if(c == null) {// added at end
				curImbalance += (((e - f) > 1) ? 1 : 0);
			}
			else {
				curImbalance += (c - f) > 1 ? -1 : 0;
				curImbalance += (((c - e) > 1) ? 1 : 0);
				curImbalance += (((e - f) > 1) ? 1 : 0);
			}
			imbalance += curImbalance;
		}
		r++;
	}
	return imbalance;
}

Program: Find Total Imbalance Amazon OA Solution in Python

result = 0
ranks = sorted(ranks)
num_of_ranks = len(ranks)

    for index in range(num_of_ranks - 1):
        if ranks[index + 1] - ranks[index] > 1:
            result += num_of_ranks - index - 1
        elif ranks[index + 1] - ranks[index] == 1:
            result += num_of_ranks - index - 2

    return result

Related: Amazon Online Assessment 2022 Questions List