#1471

The k Strongest Values in an Array

Medium
ArrayTwo PointersSortingSortingCustom Comparator
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n log n)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution improves efficiency by directly sorting the array once and using a custom comparator to determine the strongest elements in a single pass, avoiding unnecessary sorting.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the array to find the center value m.
  2. 2Step 2: Use a custom sort function to sort elements based on their strength and value.
  3. 3Step 3: Return the first k elements from the sorted array.
solution.py6 lines
1def getStrongest(arr, k):
2    arr.sort()
3    n = len(arr)
4    m = arr[(n - 1) // 2]
5    arr.sort(key=lambda x: (abs(x - m), x), reverse=True)
6    return arr[:k]

Complexity note: The time complexity remains O(n log n) due to sorting, but we efficiently handle the selection of k elements. The space complexity is O(n) due to the storage of the sorted array.

  • 1Understanding the concept of strength based on distance from the center is crucial.
  • 2Sorting the array is a key step in both approaches, but the optimal solution leverages it more effectively.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.