The k Strongest Values in an Array — LeetCode 1471 Python Solution

MediumArrayTwo PointersSorting
Problem
#1471
Reading time
2 min

The 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 centre of the array.

Example

Input
arr = [1,2,3,4,5], k = 2
Output
[5,1]
Explanation
Centre is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also accepted answer.

Python solution

Python
class Solution:
    def getStrongest(self, arr: List[int], k: int) -> List[int]:
        arr.sort()
        m = arr[(len(arr) - 1) >> 1]
        arr.sort(key=lambda x: (-abs(x - m), -x))
        return arr[:k]

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1471. The k Strongest Values in an Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1471. The k Strongest Values in an Array?
LeetCode 1471. The k Strongest Values in an Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 1471. The k Strongest Values in an Array?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 1471. The k Strongest Values in an Array?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1471. The k Strongest Values in an Array cover?
LeetCode 1471. The k Strongest Values in an Array is tagged Array, Two Pointers and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview