The k Strongest Values in an Array - Problem
You're given an array of integers arr and an integer k. Your task is to find the k strongest values in the array based on a unique strength metric.
What makes a value "stronger"?
A value arr[i] is considered stronger than arr[j] if:
|arr[i] - m| > |arr[j] - m|wheremis the median of the array- If the distances are equal (
|arr[i] - m| == |arr[j] - m|), then the larger value wins (arr[i] > arr[j])
Finding the median: Sort the array and take the element at position ((n - 1) / 2) using 0-based indexing.
Example: For [6, -3, 7, 2, 11], sorted becomes [-3, 2, 6, 7, 11]. The median is at index (5-1)/2 = 2, which is 6.
Return the k strongest values in any order.
Input & Output
example_1.py โ Basic Case
$
Input:
arr = [1, 2, 3, 4, 5], k = 2
โบ
Output:
[5, 1]
๐ก Note:
Median is 3 (middle of sorted array). Strengths: |1-3|=2, |2-3|=1, |3-3|=0, |4-3|=1, |5-3|=2. Both 1 and 5 have strength 2, but we can return in any order.
example_2.py โ Original Example
$
Input:
arr = [6, -3, 7, 2, 11], k = 3
โบ
Output:
[11, 7, 6]
๐ก 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: -3(9), 11(5), 2(4). But since 11 > -3 in tie-breaking, result includes [11, 7, 6] or similar.
example_3.py โ Single Element
$
Input:
arr = [1], k = 1
โบ
Output:
[1]
๐ก Note:
Only one element, so it's automatically the strongest (and weakest). Median is 1, strength is |1-1|=0.
Constraints
- 1 โค arr.length โค 105
- -105 โค arr[i] โค 105
- 1 โค k โค arr.length
- The answer can be returned in any order
Visualization
Tap to expand
Understanding the Visualization
1
Find the Median
Sort all athletes by performance and find the middle performer (median)
2
Calculate Deviations
Measure how far each athlete's performance is from the median
3
Rank by Extremeness
The athletes with the largest deviations (positive or negative) are 'strongest'
4
Break Ties by Performance
If two athletes have the same deviation, the higher performer wins
Key Takeaway
๐ฏ Key Insight: After sorting, the strongest values will always be at the extremes (left and right ends) since they have the maximum distance from the median. Two pointers efficiently capture this without needing to calculate all strengths explicitly!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code