Group By Average

MediumData EngineeringArrayMathSorting

Description

Given an array of [key, value] pairs, group by key and return [key, average] for each distinct key, where average is the mean of that key’s values rounded to 4 decimal places. Order the groups by each key’s first appearance.

Examples

Input:[[1,10],[1,20],[2,30]]
Output:[[1,15],[2,30]]
Explanation:

Rows sharing a key are collapsed into one carrying the average of their values, with keys ordered by first appearance.

Input:[[5,2],[5,4],[5,6]]
Output:[[5,4]]
Explanation:

Rows sharing a key are collapsed into one carrying the average of their values, with keys ordered by first appearance.

Input:[[1,1],[2,2],[3,3]]
Output:[[1,1],[2,2],[3,3]]
Explanation:

Rows sharing a key are collapsed into one carrying the average of their values, with keys ordered by first appearance.

Constraints

  • 1 ≤ number of pairs ≤ 10⁴

Ready to solve this problem?

Practice solo and sharpen your skills for technical interviews.