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
The k Strongest Values in an Array INPUT arr = [1, 2, 3, 4, 5] 1 2 3 4 5 0 1 2 3 4 Median (m) = 3 pos = (5-1)/2 = 2 k = 2 Strength Rule: |arr[i] - m| {'>'} |arr[j] - m| or if equal, larger value wins ALGORITHM STEPS 1 Sort Array [1,2,3,4,5] (already sorted) 2 Find Median m = arr[(n-1)/2] = 3 3 Calculate Strengths |val - median| for each Val |val-3| Str Rank 1 2 HIGH 2nd 2 1 LOW 4th 3 0 MIN 5th 4 1 LOW 3rd 5 2 HIGH 1st 4 Two Pointers Pick k strongest from ends FINAL RESULT Two Pointer Selection: 1 2 3 4 5 left right Compare: |5-3|=2 vs |1-3|=2 Equal strength, 5 {'>'} 1 Pick 5 first, then 1 Output Array: 5 1 [5, 1] -- OK Key Insight: Use two pointers on sorted array! Compare elements from both ends since strongest values are farthest from median. Time: O(n log n) for sorting, O(n) for selection. Space: O(1) extra. No need to compute all strengths - just compare endpoints! TutorialsPoint - The k Strongest Values in an Array | Optimal Solution (Two Pointers)
Asked in
Facebook 15 Amazon 12 Google 8
25.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen