The k Strongest Values in an Array - Problem
Given an array of integers arr and an integer k.
A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array.
If |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j].
Return a list of the k strongest values in the array. Return the answer in any arbitrary order.
The median is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed).
Input & Output
Example 1 — Basic Case
$
Input:
arr = [1,2,3,4,5], k = 2
›
Output:
[5,1]
💡 Note:
Array sorted: [1,2,3,4,5], median = 3 at position (5-1)/2 = 2. Strengths: |1-3|=2, |2-3|=1, |3-3|=0, |4-3|=1, |5-3|=2. Elements 1 and 5 have highest strength 2. Since both have equal strength, we can return either order.
Example 2 — Equal Strengths with Tie-Breaking
$
Input:
arr = [1,1,3,5,5], k = 2
›
Output:
[5,5]
💡 Note:
Sorted: [1,1,3,5,5], median = 3. Strengths: |1-3|=2, |1-3|=2, |3-3|=0, |5-3|=2, |5-3|=2. Multiple elements with strength 2, but 5 > 1, so we pick the 5s first.
Example 3 — Small Array
$
Input:
arr = [6,-3,7,2,11], k = 3
›
Output:
[-3,11,2]
💡 Note:
Sorted: [-3,2,6,7,11], median = 6. Strengths: |-3-6|=9, |2-6|=4, |6-6|=0, |7-6|=1, |11-6|=5. Top 3 strongest are -3 (strength 9), 11 (strength 5), and 2 (strength 4).
Constraints
- 1 ≤ arr.length ≤ 104
- 1 ≤ k ≤ arr.length
- -105 ≤ arr[i] ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [6,-3,7,2,11] and k=2
2
Find Median
Sort to get [-3,2,6,7,11], median = 6
3
Calculate Strengths
Distance from median: 9,4,0,1,5
4
Select Top k
Choose 2 strongest: -3(strength 9) and 11(strength 5)
Key Takeaway
🎯 Key Insight: The strongest elements are those farthest from the median, making sorted array extremes the prime candidates
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code