Solve Triangle Rows and Top Frequencies
Company: Ericsson
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question set evaluates understanding of combinatorial number patterns and frequency-based selection, specifically the ability to generate an additive number triangle and to identify the k most frequent elements, assessing skills in array/list manipulation, counting, and selection algorithms.
Part 1: Build an Additive Number Triangle
Constraints
- 0 <= numRows <= 30
- Row 0 is `[1]`
- Each row `i` contains exactly `i + 1` integers
Examples
Input: 0
Expected Output: []
Explanation: Edge case: zero rows means the triangle is empty.
Input: 1
Expected Output: [[1]]
Explanation: Only the first row is needed.
Input: 2
Expected Output: [[1], [1, 1]]
Explanation: The first two rows both start and end with 1.
Input: 5
Expected Output: [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
Explanation: Each interior value is formed by summing the two adjacent values above it.
Hints
- Build the triangle one row at a time, starting from row 0.
- For each new row, set the first and last elements to 1, then fill the middle using the previous row.
Part 2: Return the K Most Frequent Values
Constraints
- 1 <= len(nums) <= 100000
- -10^9 <= nums[i] <= 10^9
- 1 <= k <= number of distinct values in nums
Examples
Input: ([1, 1, 1, 2, 2, 3], 2)
Expected Output: [1, 2]
Explanation: Value 1 appears 3 times and value 2 appears 2 times, so they are the top 2.
Input: ([5], 1)
Expected Output: [5]
Explanation: Edge case: with one element, that element is the most frequent.
Input: ([-1, -1, -2, -2, -2, 3], 2)
Expected Output: [-2, -1]
Explanation: -2 appears 3 times and -1 appears 2 times.
Input: ([1, 2, 2, 3, 3, 3], 3)
Expected Output: [3, 2, 1]
Explanation: All distinct values must be returned because k equals the number of unique values.
Hints
- Use a hash map or `Counter` to compute how often each value appears.
- Keep a min-heap of size `k` so the least useful candidate can be removed when a better one appears.