question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
random-point-in-non-overlapping-rectangles | Simple pure C solution (with prefix sum) | simple-pure-c-solution-with-prefix-sum-b-lwul | Code | ggandrew1218 | NORMAL | 2025-02-25T10:40:05.751759+00:00 | 2025-02-25T10:40:25.568331+00:00 | 4 | false |
# Code
```c []
typedef struct {
int** coord;
int num;
int* prefix;
} Solution;
Solution* solutionCreate(int** rects, int rectsSize, int* rectsColSize) {
srand( (unsigned) time(NULL) );
Solution* obj = malloc(sizeof(Solution));
obj->num=0;
obj->coord = malloc(sizeof(int*)*rectsSize);
for(int i=0;i<rectsSize;i++)
{
int* coord = malloc(sizeof(int)*4);
// rects[i][0] //down left x
// rects[i][1] //down left y
// rects[i][2] //top right x
// rects[i][3] //top right y
coord[0]=rects[i][0];
coord[1]=(rects[i][2]-rects[i][0])+1;
coord[2]=rects[i][1];
coord[3]=(rects[i][3]-rects[i][1])+1;
obj->coord[obj->num++]=coord;
}
obj->prefix = calloc(rectsSize+1, sizeof(int));
for(int i=1;i<=rectsSize;i++)
{
obj->prefix[i]=obj->prefix[i-1]+(obj->coord[i-1][1]*obj->coord[i-1][3]);
}
return obj;
}
int* solutionPick(Solution* obj, int* retSize) {
//printf("%d\n", rand());
int random_idx = rand()%obj->prefix[obj->num];
//printf("sum = %d\n", obj->prefix[obj->num]);
// int random_x = obj->coord[random_idx][0]+rand()%obj->coord[random_idx][1];
// int random_y = obj->coord[random_idx][2]+rand()%obj->coord[random_idx][3];
int* ans = malloc(sizeof(int)*2);
for(int i = 1;i<=obj->num;i++)
{
if(random_idx<obj->prefix[i])
{
ans[0]= obj->coord[i-1][0]+rand()%obj->coord[i-1][1];
ans[1]= obj->coord[i-1][2]+rand()%obj->coord[i-1][3];
break;
}
}
*retSize=2;
return ans;
}
void solutionFree(Solution* obj) {
free(obj->coord);
free(obj);
}
/**
* Your Solution struct will be instantiated and called as such:
* Solution* obj = solutionCreate(rects, rectsSize, rectsColSize);
* int* param_1 = solutionPick(obj, retSize);
* solutionFree(obj);
*/
``` | 0 | 0 | ['C', 'Prefix Sum'] | 0 |
random-point-in-non-overlapping-rectangles | My Rust solution | my-rust-solution-by-omgeeky1-85s1 | ApproachCalculate the area of each rectangle and use that as weight when picking rects, to choose a point from. This ensures that each point has the same chance | omgeeky1 | NORMAL | 2025-01-17T18:39:58.809168+00:00 | 2025-01-17T18:39:58.809168+00:00 | 2 | false | # Approach
Calculate the area of each rectangle and use that as weight when picking rects, to choose a point from. This ensures that each point has the same chance of being picked.
# Note
sometimes, while optimizing the code, it would just say the solution was wrong, even though it hasn't changed logically. On the second run it worked as it should.
This is why i don't like randomness in questions like this. you could just get unlucky and get denied, even though you're correct...
# Code
```rust []
use rand::distributions::{Distribution, WeightedIndex};
use rand::Rng;
struct Solution {
rects: WeightedList<Rect>,
}
struct WeightedList<T> {
items: Vec<T>,
distribution: WeightedIndex<f64>,
}
#[derive(Clone,Copy, Debug)]
struct Rect{
a:i32,
b:i32,
x:i32,
y:i32,
}
#[derive(Clone,Copy, Debug)]
struct Point {
x: i32,
y: i32,
}
impl<T> WeightedList<T> {
fn new(items: Vec<T>, weights: Vec<f64>) -> Self {
assert_eq!(items.len(), weights.len());
let distribution = WeightedIndex::new(&weights).unwrap();
WeightedList { items, distribution }
}
}
impl<T> Distribution<T> for WeightedList<T> where T: Clone {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> T {
self.items[self.distribution.sample(rng)].clone()
}
}
impl Point {
fn to_vec(&self)-> Vec<i32>{
vec![self.x, self.y]
}
}
impl Rect {
fn from_slice(x: &[i32]) -> Self {
Rect {
a: x[0],
b: x[1],
x: x[2],
y: x[3],
}
}
fn get_point_inside<R: Rng + ?Sized>(&self, rng: &mut R)-> Point {
let x = rng.gen_range(self.a..=self.x);
let y = rng.gen_range(self.b..=self.y);
Point{x,y}
}
fn get_size(&self)-> f64 {
( (self.x - self.a+1) * (self.y - self.b+1) ) as f64 // do not forget the +1 here, since we are looking for points, including the border
}
}
impl Solution {
fn new(rects: Vec<Vec<i32>>) -> Self {
let (rects, weights) = rects.into_iter().map(|x|{
let rect = Rect::from_slice(&x);
(rect, 1.0 + rect.get_size() )
}).collect();
Self{
rects: WeightedList::new(rects, weights)
}
}
fn pick(&self) -> Vec<i32> {
use rand::Rng;
let mut rng = rand::thread_rng();
let rect = self.rects.sample(&mut rng);
let point = rect.get_point_inside(&mut rng);
point.to_vec()
}
}
``` | 0 | 0 | ['Rust'] | 0 |
random-point-in-non-overlapping-rectangles | Random Point Picker in Rectangles | random-point-picker-in-rectangles-by-lee-bmm2 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | leet_coderps050303 | NORMAL | 2025-01-13T17:06:53.816770+00:00 | 2025-01-13T17:06:53.816770+00:00 | 4 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
import java.util.*;
public class Solution {
private int[][] rects;
private int[] areas;
private int totalArea;
private Random rand;
public Solution(int[][] rects) {
this.rects = rects;
this.areas = new int[rects.length];
this.totalArea = 0;
this.rand = new Random();
for (int i = 0; i < rects.length; i++) {
int width = rects[i][2] - rects[i][0] + 1;
int height = rects[i][3] - rects[i][1] + 1;
areas[i] = width * height;
totalArea += areas[i];
}
}
public int[] pick() {
int target = rand.nextInt(totalArea);
int rectIndex = 0;
while (target >= areas[rectIndex]) {
target -= areas[rectIndex];
rectIndex++;
}
int[] rect = rects[rectIndex];
int x = rect[0] + rand.nextInt(rect[2] - rect[0] + 1);
int y = rect[1] + rand.nextInt(rect[3] - rect[1] + 1);
return new int[] {x, y};
}
}
``` | 0 | 0 | ['Java'] | 0 |
random-point-in-non-overlapping-rectangles | C++ solution of Random point in non-overlapping rectangles | c-solution-of-random-point-in-non-overla-sdv8 | Intuitionfollow the approach of algomonster blog --> https://algo.monster/liteproblems/497Complexity
Time complexity:O(log n)
Space complexity:O(n)
Code | gjit515 | NORMAL | 2025-01-09T07:22:22.351180+00:00 | 2025-01-09T07:22:22.351180+00:00 | 10 | false | # Intuition
follow the approach of algomonster blog --> https://algo.monster/liteproblems/497
# Complexity
- Time complexity:O(log n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
vector<int> prefixSums;
vector<vector<int>>rectangles;
Solution(vector<vector<int>>& rects) {
rectangles=rects;
int numRectangles = rectangles.size();
prefixSums.resize(numRectangles + 1, 0);
for(int i=0;i<numRectangles;i++){
prefixSums[i + 1] = prefixSums[i] +
(rectangles[i][2] - rectangles[i][0] + 1) *
(rectangles[i][3] - rectangles[i][1] + 1);
}
srand(static_cast<unsigned int>(time(nullptr)));
}
vector<int> pick() {
int target = 1 + rand() % prefixSums.back();
// Find the rectangle that will contain the point.
int idx = static_cast<int>(lower_bound(prefixSums.begin(), prefixSums.end(), target) - prefixSums.begin()) - 1;
// Get the rectangle information.
auto& rect = rectangles[idx];
// Pick a random point within the chosen rectangle.
int x = rect[0] + rand() % (rect[2] - rect[0] + 1);
int y = rect[1] + rand() % (rect[3] - rect[1] + 1);
return {x, y}; // Return the random point as a 2D vector.
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(rects);
* vector<int> param_1 = obj->pick();
*/
``` | 0 | 0 | ['Binary Search', 'Prefix Sum', 'Randomized', 'C++'] | 0 |
random-point-in-non-overlapping-rectangles | 📌📌 WEIGHTED AREA APPROACH FOR RANDOM INDEX SELECTION📌📌 | Binary Search Solution✅✅ | weighted-area-approach-for-random-index-svjxr | IntuitionApproachComplexity
Time complexity: O(n * log n)
Space complexity: O(n)
Code | Sankar_Madhavan | NORMAL | 2025-01-07T16:01:32.475553+00:00 | 2025-01-07T16:01:32.475553+00:00 | 9 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(n * log n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
private:
vector<vector<int>> rects;
vector<int> areas;
int totalArea = 0;
public:
Solution(vector<vector<int>>& rects) {
this->rects = rects;
for (auto& rect : rects) {
int area = (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1);
totalArea += area;
areas.push_back(totalArea);
}
srand(time(0));
}
vector<int> pick() {
int randomArea = rand() % totalArea;
int randomIndex = lower_bound(areas.begin(), areas.end(), randomArea + 1) - areas.begin();
int xVal = rects[randomIndex][0] + (rand() % (rects[randomIndex][2] - rects[randomIndex][0] + 1));
int yVal = rects[randomIndex][1] + (rand() % (rects[randomIndex][3] - rects[randomIndex][1] + 1));
return {xVal, yVal};
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(rects);
* vector<int> param_1 = obj->pick();
*/
``` | 0 | 0 | ['Binary Search', 'C++'] | 0 |
the-k-strongest-values-in-an-array | C++/Java/Python Two Pointers + 3 Bonuses | cjavapython-two-pointers-3-bonuses-by-vo-swsn | My initial solution during the contest was to sort the array to figure out the median, and then sort the array again based on the abs(arr[i] - median) criteria. | votrubac | NORMAL | 2020-06-07T04:02:50.250536+00:00 | 2020-06-07T21:51:19.060753+00:00 | 8,497 | false | My initial solution during the contest was to sort the array to figure out the `median`, and then sort the array again based on the `abs(arr[i] - median)` criteria.\n\nThen I noticed that we have smallest and largest elements in the array in the result. That makes sense based on the problem definition. So, instead of sorting the array again, we can use the two pointers pattern to enumerate smallest and largest numbers, picking the largest `abs(a[i] - median)` each time.\n\nThe code above has one trick: we check that `a[i] > a[j]` first. This way, if `a[i] == a[j]`, we pick the element from the right side, which is largest because the array is sorted!\n\n> Update: check bonus sections below for O(n log k), O(n + k log n), and O(n) solutions.\n\n**C++**\n```cpp\nvector<int> getStrongest(vector<int>& arr, int k) {\n sort(begin(arr), end(arr));\n int i = 0, j = arr.size() - 1;\n int med = arr[(arr.size() - 1) / 2];\n while (--k >= 0)\n if (med - arr[i] > arr[j] - med)\n ++i; \n else\n --j;\n arr.erase(begin(arr) + i, begin(arr) + j + 1);\n return arr;\n}\n```\n**Java**\n```java\npublic int[] getStrongest(int[] arr, int k) {\n Arrays.sort(arr);\n int i = 0, j = arr.length - 1, p = 0;\n int median = arr[(arr.length - 1) / 2];\n int[] res = new int[k];\n while (p < k)\n if (median - arr[i] > arr[j] - median)\n res[p++] = arr[i++]; \n else\n res[p++] = arr[j--]; \n return res;\n}\n```\n**Python**\n```python\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n i, j = 0, len(arr) - 1\n median = arr[(len(arr) - 1) // 2]\n while len(arr) + i - j <= k:\n if median - arr[i] > arr[j] - median:\n i = i + 1\n else:\n j = j - 1\n return arr[:i] + arr[j + 1:]\n```\n**Complexity Analysis**\n- Time: O(n log n) for the sorting.\n- Memory: only what\'s needed for the sorting (implementation-specific), and output.\n\n#### Bonus 1: O(n log k)\nWe can find a median in O(n) average complexity by using quick select. Then, we insert all elements in a sorted set, limiting the set size to `k`. Even better, we can use a partial sort algorithm that will move `k` strongest values to the front of the array.\n\n```cpp\nvector<int> getStrongest(vector<int>& arr, int k) {\n nth_element(begin(arr), begin(arr) + (arr.size() - 1) / 2, end(arr));\n int m = arr[(arr.size() -1) / 2];\n partial_sort(begin(arr), begin(arr) + k, end(arr), [&](int a, int b) { \n return abs(a - m) == abs(b - m) ? a > b : abs(a - m) > abs(b - m); \n });\n arr.resize(k);\n return arr;\n}\n```\n#### Bonus 2: O(n + k log n)\nSimilar to the first bonus, but using a max heap. Why this is O(n + k log n):\n- `nth_element` is quick select, which is O(n);\n- `priority_queue` initialized with array is heapify, which is also O(n);\n- Pulling from priority queue is O(log n), and we do it `k` times.\n\n```cpp\nvector<int> getStrongest(vector<int>& arr, int k) {\n nth_element(begin(arr), begin(arr) + (arr.size() - 1) / 2, end(arr));\n int m = arr[(arr.size() -1) / 2];\n auto cmp = [&](int a, int b) { \n return abs(a - m) == abs(b - m) ? a < b : abs(a - m) < abs(b - m); \n };\n priority_queue<int, vector<int>, decltype(cmp)> pq(begin(arr), end(arr), cmp);\n vector<int> res;\n while (res.size() < k) {\n res.push_back(pq.top());\n pq.pop();\n }\n return res;\n}\n```\n#### Bonus 3: O(n)\nThe order in output does not need to be sorted. So, after we find our median, we can do another quick select to move k strongest elements to the beginning of the array.\n> Note: quickselect has O(n) average time complexity, and O(n ^ 2) worst time complexity. It can be improved to O(n) worst time complexity using the median of medians approach to find a pivot. In practice though, a simpler randomization version is faster than median of medians, as the latter requires an extra O(n) scan to find a pivot.\n\n```cpp\nvector<int> getStrongest(vector<int>& arr, int k) {\n nth_element(begin(arr), begin(arr) + (arr.size() - 1) / 2, end(arr));\n int m = arr[(arr.size() -1) / 2];\n nth_element(begin(arr), begin(arr) + k, end(arr), [&](int a, int b) { \n return abs(a - m) == abs(b - m) ? a > b : abs(a - m) > abs(b - m); \n });\n arr.resize(k);\n return arr;\n}\n``` | 155 | 1 | [] | 18 |
the-k-strongest-values-in-an-array | Why not right definition of median | why-not-right-definition-of-median-by-le-6ixm | median = A[(n - 1) / 2] ??\n\nNo, why did leetcode define median itself....\n\nmedian = (A[n/2] + A[(n-1)/2]) / 2\n\nPlease noted that that\'s universal definit | lee215 | NORMAL | 2020-06-07T04:04:43.132192+00:00 | 2020-06-07T04:05:35.189158+00:00 | 4,896 | false | `median = A[(n - 1) / 2]` ??\n\nNo, why did leetcode define median itself....\n\n`median = (A[n/2] + A[(n-1)/2]) / 2`\n\nPlease noted that that\'s universal definition of "median"\n\nTime `O(nlogn)`\nSpace `O(n)`\n\n**C++**\n```cpp\n vector<int> getStrongest(vector<int> A, int k) {\n sort(A.begin(), A.end());\n int n = A.size(), i = 0, j = n - 1, m = A[(n - 1) / 2];\n while (k--) {\n if (A[j] - m >= m - A[i])\n j--;\n else\n i++;\n }\n A.erase(A.begin() + i, A.begin() + j + 1);\n return A;\n }\n``` | 103 | 5 | [] | 17 |
the-k-strongest-values-in-an-array | Learn randomized algorithm today which solves this problem in O(n). | learn-randomized-algorithm-today-which-s-a7w9 | Two Approaches: O(nlogn) and O(n) - Sort and Randomized Algorithm\n\nThe problem is not complex to find the solution of but it can get complex in implementation | interviewrecipes | NORMAL | 2020-06-07T04:02:01.138702+00:00 | 2020-06-10T18:17:50.129802+00:00 | 3,083 | false | **Two Approaches: O(nlogn) and O(n) - Sort and Randomized Algorithm**\n\nThe problem is not complex to find the solution of but it can get complex in implementation. Basically you want to find the median of the array and then find k values that result in the maximum value for the requested operation.\n\n**A Straightforward way - Sorting**\nSort the array.\nGet the median i.e. ((n-1)/2)th element.\nCreate a new array where each element, new_arr[i] = abs(original_arr[i] -median)\nSort the new array.\nReturn the highest k values.\n\nThe tricky part is to handle the scenarios when values in new_array are the same. You then want to sort based the original array value. For this, you might have to write a custom comparison method depending on the programming language.\n\nIf you sort the entire array, then time complexity is O(nlogn).\nHence the time complexity of this solution is O(nlogn).\n\n```\nint median;\nstruct compare {\n bool operator()(const int &a, const int &b) {\n return (abs(a-median) > abs(b-median)) || (abs(a-median) == abs(b-median) && a>b);\n }\n} compare;\n\nclass Solution {\npublic: \n vector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(), arr.end()); // Sort first to find the median.\n median = arr[(arr.size()-1)/2]; // Find median.\n sort(arr.begin(), arr.end(), compare); // Sort again based on a specific way.\n return vector<int>(arr.begin(), arr.begin()+k); // Return the answer.\n }\n};\n```\n\n\n**B. Advanced way - Randomized Algorithms**\nYou don\u2019t have to sort the entire array. There are only 2 things of interest.\nThe median. So you want `((n-1)/2)`th number in the array. There is a randomized algorithm that can give the result in O(n) time. (Basically how quicksort sorts the array by choosing a pivot element).\nThe strongest k values. An important thing to note here is that the order of those values is not important. The question states that any order is fine. So the same randomized algorithm helps here too.\n\nTime complexity: O(n).\n\n\nIn C++, the method is nth_element for arranging first k-1 elements to be smaller than kth element & remaining elements at the end. Other languages must also have something similar.\nWhat is the way in your language? I would be curious to know, put that in comments.\n\n**Thanks**\nPlease upvote if you found this helpful.\n\n```\nint median;\nstruct compare {\n bool operator()(const int &a, const int &b) {\n return (abs(a-median) > abs(b-median)) || (abs(a-median) == abs(b-median) && a>b);\n }\n} compare;\n\nclass Solution {\npublic: \n vector<int> getStrongest(vector<int>& arr, int k) {\n nth_element(arr.begin(), arr.begin()+(arr.size()-1)/2, arr.end()); // Just find median element correctly.\n median = arr[(arr.size()-1)/2]; // Get median.\n nth_element(arr.begin(), arr.begin()+k, arr.end(), compare); // Sort just enough that k strongest are at the beginning.\n return vector<int>(arr.begin(), arr.begin()+k); // Return the answer.\n }\n};\n```\n\n\n**How Randomized Median Find Work**\n\n1. It choses an element as pivot.\n2. Shuffles the array so that all elements to the left of it are smaller than itself while the ones on the right are greater.\n3. If that element turns out to be at the index \'k\' that we pass as a parameter, the algorithm stops. At this time - we have the array with `k`-th element at correct place (the place had the array been sorted.) AND we have smaller elements on left side and larger on right. This is exactly what helps us here for solving this problem.\n4. If the element is not at `k` we decide which part (left or right) to go into to get to the kth element.\n\nAdditional Info on ref: https://en.wikipedia.org/wiki/Partial_sorting | 42 | 2 | [] | 8 |
the-k-strongest-values-in-an-array | [Python3] straightforward 2 lines with custom sort | python3-straightforward-2-lines-with-cus-yvgw | get median by sorting and getting the (n-1)/2 th element\n2. use lambda to do custom sort. since we need maximum, take negative of difference. if difference is | manparvesh | NORMAL | 2020-06-07T04:18:02.071240+00:00 | 2020-06-07T16:10:09.217635+00:00 | 1,518 | false | 1. get median by sorting and getting the `(n-1)/2` th element\n2. use lambda to do custom sort. since we need maximum, take negative of difference. if difference is equal, we just get the larger value element\n\n```\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n m = sorted(arr)[(len(arr) - 1) // 2]\n return sorted(arr, key = lambda x: (-abs(x - m), -x))[:k]\n```\n\nSuggestion by @Gausstotle that makes sorting even easier to understand:\n\n```\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n m = sorted(arr)[(len(arr) - 1) // 2]\n return sorted(arr, reverse=True, key = lambda x: (abs(x - m), x))[:k]\n```\n | 16 | 0 | ['Python3'] | 2 |
the-k-strongest-values-in-an-array | [C++] Simple solution using two pointers | c-simple-solution-using-two-pointers-by-0n6zu | \ncpp\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(), arr.end());\n int left = 0;\n | hayashi-ay | NORMAL | 2020-06-07T10:52:08.288875+00:00 | 2020-06-07T10:52:08.288910+00:00 | 1,343 | false | \n```cpp\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(), arr.end());\n int left = 0;\n int right = arr.size()-1;\n int midIndex = (arr.size() -1)/2;\n int mid = arr[midIndex];\n \n vector<int> answer(k);\n int counter = 0;\n while(counter<k){\n int leftValue = abs(arr[left]-mid);\n int rightValue = abs(arr[right]-mid);\n \n if(rightValue>=leftValue){\n answer[counter] = arr[right];\n right--;\n } else {\n answer[counter] = arr[left];\n left++;\n }\n counter++;\n }\n return answer;\n }\n};\n``` | 15 | 0 | ['C', 'C++'] | 1 |
the-k-strongest-values-in-an-array | Python3 solution beats 100% of submissions | python3-solution-beats-100-of-submission-7w9s | \nclass Solution:\n \n def getStrongest(self, arr: List[int], K: int) -> List[int]:\n arr.sort()\n length = len(arr)\n res = arr[(len | dark_wolf_jss | NORMAL | 2020-06-07T05:12:17.088064+00:00 | 2020-06-07T05:12:17.088104+00:00 | 594 | false | ```\nclass Solution:\n \n def getStrongest(self, arr: List[int], K: int) -> List[int]:\n arr.sort()\n length = len(arr)\n res = arr[(length-1)//2]\n i = 0\n j = length-1\n result = []\n while K>0:\n a = abs(arr[i]-res)\n b = abs(arr[j]-res)\n if a>b or (a==b and arr[i]>arr[j]):\n result.append(arr[i])\n i+=1\n else:\n result.append(arr[j])\n j-=1\n K-=1\n return result\n``` | 13 | 1 | [] | 0 |
the-k-strongest-values-in-an-array | Java O(nlogn) solution:Sorting done once | java-onlogn-solutionsorting-done-once-by-suqu | To do this question,we need to sort the array,after sorting we can find the median by using the formula given in question.\nA value arr[i] is said to be stronge | manasviiiii | NORMAL | 2021-05-04T10:22:14.345050+00:00 | 2021-05-04T10:22:14.345091+00:00 | 736 | false | To do this question,we need to sort the array,after sorting we can find the median by using the formula given in question.\nA 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.\nSince we need to find stronger values,we can see from the above expression that a value is strong if its distance from median is greater.For eg:the distance of median from itself is zero.\nFor example:\narr=[1,1,3,4,5], k = 2\nThe median here is 3, and our strongest 2 elements are going to be [1,5]. After sorting we can see that the elements at extreme ends have max distance from median.So we can simply check which of the elements at extreme end(start vs end) has a greater distance from median.\nAnd to account for |arr[i] - m| == |arr[j] - m|, as given in question that arr[i] is said to be stronger than arr[j] if arr[i] > arr[j],so we can just simply consider the last element as the array is sorted and it will definitely be greater than starting element.\n\nAs the sorting takes O(nlogn)) time and the while loop will run for O(k),the total time complexity is O(nlogn)\n\n\n```\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n Arrays.sort(arr); \n int median=arr[(arr.length-1)/2];\n int i=0;\n int j=arr.length-1;\n int res=0;\n int[] result=new int[k];\n while(res<k)\n {\n\t\t//while loop will stop after we hace chosen the k greatest elements.\n if(Math.abs(arr[i]-median)>Math.abs(arr[j]-median))\n {\n result[res]=arr[i];\n i++;\n res++;\n }\n else{\n result[res]=arr[j];\n j--;\n res++;\n }\n }\n return result;\n \n }\n}\n```\nHope this helps someone! | 10 | 0 | ['Java'] | 3 |
the-k-strongest-values-in-an-array | Python solution (2 lines) 100% faster runtime | python-solution-2-lines-100-faster-runti-hj77 | \n\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n med = sorted(arr[(len(arr)-1)//2])\n \xA0 \xA0 \xA0 \xA0return sorted(array, key=l | it_bilim | NORMAL | 2020-06-07T09:05:22.626380+00:00 | 2020-06-07T20:09:07.821706+00:00 | 941 | false | \n```\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n med = sorted(arr[(len(arr)-1)//2])\n \xA0 \xA0 \xA0 \xA0return sorted(array, key=lambda x:(abs(x-med),x))[-k:]\n``` | 8 | 0 | ['Sorting', 'Python', 'Python3'] | 2 |
the-k-strongest-values-in-an-array | Java Custom Sort [easy] | java-custom-sort-easy-by-jatinyadav96-cso4 | \n public static int[] getStrongest(int[] arr, int k) {\n Arrays.sort(arr);\n int med = arr[((arr.length - 1) / 2)];\n int[] kStrongest = new int[k];\ | jatinyadav96 | NORMAL | 2020-06-07T04:17:26.484092+00:00 | 2020-06-07T04:17:26.484147+00:00 | 1,231 | false | ```\n public static int[] getStrongest(int[] arr, int k) {\n Arrays.sort(arr);\n int med = arr[((arr.length - 1) / 2)];\n int[] kStrongest = new int[k];\n ArrayList<Integer> ns = new ArrayList<>();\n for (int f : arr) ns.add(f);// please comment if any better way to do this [copying int[] into ArrayList]\n ns.sort((i1, i2) -> {\n int diff = Math.abs(i2 - med) - Math.abs(i1 - med);\n if (diff == 0) {\n return i2 - i1;\n }\n return diff;\n });\n for (int i = 0; i < k; i++) {\n kStrongest[i] = ns.get(i);\n }\n return kStrongest;\n }\n``` | 8 | 2 | ['Sorting', 'Java'] | 8 |
the-k-strongest-values-in-an-array | [Java/Python 3] Two codes: Two Pointer and PriorityQueue w/ brief explanation and analysis. | javapython-3-two-codes-two-pointer-and-p-xqwo | First sort then \nMethod 1:\nUse Two Pointer: \n1. starts from the two ends of the sorted array, choose the stronger one and move the corresponding pointer;\n2. | rock | NORMAL | 2020-06-07T04:04:06.589144+00:00 | 2020-06-13T04:34:39.948628+00:00 | 871 | false | First sort then \n**Method 1:**\nUse Two Pointer: \n1. starts from the two ends of the sorted array, choose the stronger one and move the corresponding pointer;\n2. repeats the above till get k elements.\n\n```java\n public int[] getStrongest(int[] arr, int k) {\n int n = arr.length, i = 0, j = n - 1;\n Arrays.sort(arr);\n int median = arr[(n - 1) / 2];\n int[] ans = new int[k];\n while (k-- > 0) {\n if (median - arr[i] > arr[j] - median) {\n ans[k] = arr[i++];\n }else {\n ans[k] = arr[j--];\n }\n }\n return ans;\n }\n```\n```python\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n n = len(arr)\n median, i, j = arr[(n - 1) // 2], 0, n - 1 \n while k > 0:\n if median - arr[i] > arr[j] - median:\n i += 1\n else:\n j -= 1\n k -= 1\n return arr[: i] + arr[j + 1 :]\n```\n**Analysis:**\nSorting is the major part for time, which cost (n); returned array cost space O(k). Therefore,\nTime: O(nlogn), space: O(k) - including returned array.\n\n----\n\n**Method 2:**\ntraverse `arr`, use PriorityQueue to maintain the currently k strongest.\n```java\n public int[] getStrongest(int[] arr, int k) {\n int n = arr.length;\n Arrays.sort(arr);\n int median = arr[(n - 1) / 2];\n PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);\n for (int a : arr) {\n pq.offer(new int[]{Math.abs(a - median), a});\n if (pq.size() > k) {\n pq.poll();\n }\n }\n return pq.stream().mapToInt(a -> a[1]).toArray();\n }\n```\n```python\nfrom queue import PriorityQueue\n\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n median = sorted(arr)[(len(arr) - 1) // 2]\n pq = PriorityQueue()\n for i, a in enumerate(arr):\n pq.put((abs(a - median), a))\n if i >= k:\n pq.get()\n return [pq.get()[1] for _ in range(k)]\n```\n**Analysis:**\nSorting is the major part for time, which cost (n); PriorityQueue cost space O(k). Therefore,\nTime: O(nlogn), space: O(k). | 8 | 0 | [] | 5 |
the-k-strongest-values-in-an-array | Java solution | Two approaches | java-solution-two-approaches-by-sourin_b-kl2w | Please Upvote !!!\n##### 1. Using Priority Queue (Max Heap)\n\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n Arrays.sort(arr);\n | sourin_bruh | NORMAL | 2022-08-27T18:51:27.442765+00:00 | 2022-08-27T18:51:27.442804+00:00 | 849 | false | ### *Please Upvote !!!*\n##### 1. Using Priority Queue (Max Heap)\n```\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n Arrays.sort(arr);\n int m = arr[(arr.length - 1) / 2];\n PriorityQueue<Integer> pq = new PriorityQueue<>(\n (a, b) -> Math.abs(a - m) == Math.abs(b - m) ? b - a : Math.abs(b - m) - Math.abs(a - m)\n );\n\n for (int num : arr) {\n pq.offer(num);\n }\n\n int[] ans = new int[k];\n for (int i = 0; i < k; i++) {\n ans[i] = pq.poll();\n }\n\n return ans;\n }\n}\n\n// TC: O(n * logn) + O(n) => O(n * logn)\n// SC: O(n + k)\n```\n##### 2. Two Pointer approach (faster)\n```\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n Arrays.sort(arr);\n int m = arr[(arr.length - 1) / 2];\n int[] ans = new int[k];\n int left = 0, right = arr.length - 1;\n int index = 0;\n\n while (index < k) {\n if (m - arr[left] > arr[right] - m) {\n ans[index++] = arr[left++];\n } else {\n ans[index++] = arr[right--];\n }\n }\n\n return ans;\n }\n}\n\n// TC: O(n * logn) + O(k) => O(n * logn)\n// SC: O(k)\n``` | 6 | 0 | ['Two Pointers', 'Heap (Priority Queue)', 'Java'] | 2 |
the-k-strongest-values-in-an-array | [C++] Why time limit on sort method during contest, and got accepted on re-submission? | c-why-time-limit-on-sort-method-during-c-61g9 | No need for explanation, straightforward solution.\n71 / 71 test cases passed, but took too long. Resubmission of same code got accepted.\nWhy it happened? Is i | mr_robot11 | NORMAL | 2020-06-07T04:11:17.575792+00:00 | 2020-06-07T04:11:17.575841+00:00 | 454 | false | No need for explanation, straightforward solution.\n71 / 71 test cases passed, but took too long. Resubmission of same code got accepted.\nWhy it happened? Is it normal or there is something wrong in my code.\n\n```\nbool comp(const pair<int,int> &a, const pair<int,int> &b)\n{\n if(a.first==b.first) return a.second>b.second;\n return a.first>b.first;\n}\n\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n int n=arr.size();\n sort(arr.begin(),arr.end());\n \n int med=arr[(n-1)/2];\n vector< pair<int,int> > ans;\n for(int i=0;i<n;i++) ans.push_back({ abs(arr[i]-med),arr[i] });\n \n sort(ans.begin(),ans.end(),comp);\n vector<int> rv;\n for(int i=0;i<k;i++) rv.push_back(ans[i].second);\n return rv;\n }\n}; | 6 | 1 | ['C', 'Sorting'] | 1 |
the-k-strongest-values-in-an-array | Java Simple Heap | java-simple-heap-by-hobiter-vdgn | Should be straightforward;\njust pay attention, the new defination of median makes this problem easier;\nTime:\nO(nlgN) to find the median;\nO(N), strictly O(lg | hobiter | NORMAL | 2020-06-07T04:02:10.276285+00:00 | 2020-06-07T20:37:18.741655+00:00 | 544 | false | Should be straightforward;\njust pay attention, the new defination of median makes this problem easier;\nTime:\nO(nlgN) to find the median;\nO(N), strictly O(lg3 * N) = O(N), to find result;\nSpace,\nO(k + ...) = O(k);\n```\n\tpublic int[] getStrongest(int[] arr, int k) {\n Arrays.sort(arr);\n int m = arr.length;\n int med = arr[(m - 1) / 2];\n PriorityQueue<Integer> pq = new PriorityQueue<>((b, a) -> Math.abs(b - med) == Math.abs(a - med) ? (b - a) : Math.abs(b - med) - Math.abs(a - med));\n for (int i : arr) {\n pq.offer(i);\n if (pq.size() > k) pq.poll();\n }\n int[] res = new int[k];\n for (int i = k - 1; i >= 0; i--) res[i] = pq.poll();\n return res;\n }\n``` | 5 | 0 | [] | 2 |
the-k-strongest-values-in-an-array | JavaScript Solution - Two Pointers Approach | javascript-solution-two-pointers-approac-x4zk | \nvar getStrongest = function(arr, k) {\n const n = arr.length;\n \n arr.sort((a, b) => a - b);\n \n let left = 0;\n let right = n - 1;\n \ | Deadication | NORMAL | 2021-08-16T18:02:38.647223+00:00 | 2021-08-16T18:02:38.647270+00:00 | 181 | false | ```\nvar getStrongest = function(arr, k) {\n const n = arr.length;\n \n arr.sort((a, b) => a - b);\n \n let left = 0;\n let right = n - 1;\n \n const idx = Math.floor((n - 1) / 2);\n const median = arr[idx];\n \n const res = [];\n \n while (k > 0) {\n const leftNum = arr[left];\n const rightNum = arr[right];\n \n const leftStr = Math.abs(leftNum - median);\n const rightStr = Math.abs(rightNum - median);\n \n if ((leftStr > rightStr) || (leftStr === rightStr && leftNum > rightNum)) {\n res.push(leftNum);\n left++;\n }\n else {\n res.push(rightNum);\n right--;\n }\n k--;\n }\n \n return res;\n};\n``` | 4 | 0 | ['Two Pointers', 'JavaScript'] | 0 |
the-k-strongest-values-in-an-array | Too Simple with C++ 2pointers | too-simple-with-c-2pointers-by-aryan29-epth | \nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n //In a sorted vector either 1st or last will be strongest\n | aryan29 | NORMAL | 2020-08-08T17:20:22.730987+00:00 | 2020-08-08T17:20:22.731039+00:00 | 211 | false | ```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n //In a sorted vector either 1st or last will be strongest\n //Seems like a simple 2pointer question\n int i=0,j=arr.size()-1;\n sort(arr.begin(),arr.end());\n int med=arr[(arr.size()-1)/2];\n vector<int>ans;\n for(int l=0;l<k;l++)\n {\n if(abs(arr[i]-med)>abs(arr[j]-med))\n ans.push_back(arr[i++]);\n else\n ans.push_back(arr[j--]);\n }\n return ans;\n }\n};\n``` | 4 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | 👉C++ MAX HEAP 👀!!! | c-max-heap-by-akshay_ar_2002-pg9b | Intuition\n Describe your first thoughts on how to solve this problem. \n- MAX HEAP + PAIR\n\n# Approach\n Describe your approach to solving the problem. \n- Th | akshay_AR_2002 | NORMAL | 2023-04-07T19:55:12.502867+00:00 | 2023-04-07T19:55:12.502906+00:00 | 222 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- MAX HEAP + PAIR\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- The first step is to sort the array arr in non-decreasing order. This is because we need to find the median of the array.\n\n- Once we have sorted the array, find the median by taking the middle element if the array has an odd number of elements, or the average of the two middle elements if the array has an even number of elements. Here, the median is calculated as arr[(n - 1) / 2] where n is the size of the array.\n\n- After finding the median then calculate the strength of each element in the array. The strength of an element is defined as the absolute difference between the element and the median. We create a list of tuples (value, strength) where value is the actual element in the array and strength is its strength.\n\n- Then push each tuple into a priority queue where the tuples are sorted based on the strength of the elements. The priority queue is implemented as a max heap, so the element with the highest strength will be at the top.\n\n- Then loop through the priority queue k times and pop the element with the highest strength. This element is added to a result vector.\n\n- Finally, return the result vector containing the k strongest elements.\n\n# Complexity\nTime complexity: O(n logn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- because of sorting the array and priority queue operations.\n\nSpace complexity: O(n) \n- because of priority queue & resultant vector.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector <int> getStrongest(vector<int>& arr, int k) \n {\n int n = arr.size();\n sort(arr.begin(), arr.end());\n int median = arr[(n - 1) / 2];\n priority_queue <pair<int, int>> pq;\n \n for(int i = 0; i < n; i++)\n pq.push({abs(arr[i] - median), arr[i]});\n \n vector <int> res;\n \n while(!pq.empty() && k)\n {\n int ele = pq.top().second;\n pq.pop();\n k--;\n \n res.push_back(ele);\n }\n \n return res;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
the-k-strongest-values-in-an-array | simple cpp solution | simple-cpp-solution-by-prithviraj26-ul4p | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | prithviraj26 | NORMAL | 2023-02-06T05:25:48.004265+00:00 | 2023-02-06T05:26:20.960943+00:00 | 526 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\no(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\no(n)\n# Code\n```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n vector<pair<int,int>>v;\n int sum=0,n=arr.size();\n sort(arr.begin(),arr.end());\n int median=arr[(n-1)/2];\n for(int i=0;i<arr.size();i++)\n {\n v.push_back({abs(arr[i]-median),arr[i]});\n }\n sort(v.begin(),v.end());\n reverse(v.begin(),v.end());\n vector<int>ans;\n for(int i=0;i<k;i++)\n {\n ans.push_back(v[i].second);\n }\n return ans;\n\n }\n};\n```\n\n\n\n | 3 | 0 | ['Array', 'C++'] | 0 |
the-k-strongest-values-in-an-array | Highly optimized & easiest C++ solution using two pointer | highly-optimized-easiest-c-solution-usin-d8h4 | \nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(),arr.end());\n int i = 0 , j = arr.size()-1;\n | NextThread | NORMAL | 2022-01-24T17:06:32.400014+00:00 | 2022-01-24T17:06:32.400059+00:00 | 219 | false | ```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(),arr.end());\n int i = 0 , j = arr.size()-1;\n int median = arr[(arr.size()-1)/2];\n while(--k >= 0){\n if(median - arr[i] > arr[j] - median)\n i++;\n else j--;\n }\n arr.erase(arr.begin()+i , arr.begin()+j+1);\n return arr;\n }\n};\n``` | 3 | 0 | ['C'] | 0 |
the-k-strongest-values-in-an-array | ✔ JAVA | 2 Solutions | 2-Pointer and Priority-Queue | java-2-solutions-2-pointer-and-priority-b24yg | 2-Pointer Approach\n\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n int[] result = new int[k];\n int n = arr.length, left | norman22194plus1 | NORMAL | 2021-11-25T13:54:26.560783+00:00 | 2021-11-25T13:54:26.560812+00:00 | 222 | false | **2-Pointer Approach**\n```\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n int[] result = new int[k];\n int n = arr.length, left = 0, right = n - 1, idx = 0;\n Arrays.sort(arr);\n int median = arr[(n - 1) / 2];\n while (left <= right) {\n int diff_l = Math.abs(arr[left] - median);\n int diff_r = Math.abs(arr[right] - median);\n \n if (diff_r > diff_l)\n result[idx++] = arr[right--];\n else if (diff_l > diff_r)\n result[idx++] = arr[left++];\n else if (arr[right] > arr[left])\n result[idx++] = arr[right--];\n else \n result[idx++] = arr[left++];\n if (idx == k)\n break;\n }\n return result;\n }\n}\n```\n**Priority-Queue Approach**\n```\nclass Pair {\n int diff;\n int ele;\n public Pair(int d, int e) {\n this.diff = d;\n this.ele = e;\n }\n}\nclass MyComparator implements Comparator<Pair> {\n public int compare (Pair p, Pair q) {\n if (p.diff == q.diff)\n return q.ele - p.ele;\n return q.diff - p.diff;\n }\n}\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n PriorityQueue<Pair> queue = new PriorityQueue(new MyComparator());\n Arrays.sort(arr);\n int median = arr[(arr.length - 1) / 2];\n for (int i = 0; i < arr.length; i++)\n queue.offer(new Pair(Math.abs(arr[i] - median), arr[i]));\n int[] result = new int[k];\n for (int i = 0; i < k; i++)\n result[i] = queue.poll().ele;\n return result;\n }\n}\n```\nPlease **upvote** :-) | 3 | 0 | ['Array', 'Java'] | 0 |
the-k-strongest-values-in-an-array | C++ STL but no sorting O(N) | c-stl-but-no-sorting-on-by-willwsxu-luoi | \n\n vector<int> getStrongest(vector<int>& arr, int k) {\n const int median = (arr.size()-1)/2;\n nth_element(begin(arr), begin(arr)+median, en | willwsxu | NORMAL | 2020-07-29T22:51:15.553065+00:00 | 2020-07-29T23:37:41.863464+00:00 | 263 | false | ```\n\n vector<int> getStrongest(vector<int>& arr, int k) {\n const int median = (arr.size()-1)/2;\n nth_element(begin(arr), begin(arr)+median, end(arr)); // find median, O(N)\n const int M = *(begin(arr)+median);\n // find strongest K elements\n nth_element(begin(arr), begin(arr)+k-1, end(arr), [M](const auto& I, const auto& J) {\n int strength1=abs(I-M);\n int strength2=abs(J-M);\n return strength1==strength2? I>J : strength1 > strength2; });\n arr.resize(k); // reuse as return value\n return arr;\n }\n``` | 3 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | 2 line Python | 2-line-python-by-auwdish-422b | Summary\nFirst sort to calc the median arr[(len(arr) - 1) // 2]\nThen sort by key abs(num - arr[(len(arr) - 1) // 2]) and num\nTake the last k elements\n\npytho | auwdish | NORMAL | 2020-06-12T19:43:58.443076+00:00 | 2020-06-12T19:43:58.443130+00:00 | 145 | false | **Summary**\nFirst sort to calc the median `arr[(len(arr) - 1) // 2]`\nThen sort by key `abs(num - arr[(len(arr) - 1) // 2])` and `num`\nTake the last k elements\n\n```python\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n return sorted(arr, key=lambda num: (abs(num - arr[(len(arr) - 1) // 2]), num))[-k:]\n``` | 3 | 0 | [] | 1 |
the-k-strongest-values-in-an-array | Py3 Easy Explained Sol | py3-easy-explained-sol-by-ycverma005-bkvh | \n# Idea- Strongest value are willing to realy on boundary either side, and then inward with decreasing intesity.\n# Steps to solve\n# Sort, get median, and ass | ycverma005 | NORMAL | 2020-06-11T10:35:20.412231+00:00 | 2020-06-11T10:35:20.412282+00:00 | 295 | false | ```\n# Idea- Strongest value are willing to realy on boundary either side, and then inward with decreasing intesity.\n# Steps to solve\n# Sort, get median, and assign lastPointer, startPointer\n# compare lastPointer\'s element with startPointer\'s element, then add accordingly\n# only iterate loop for k, because elements in start and last with range of k, have Strongest value\n\n# OR\n# Explaination(hindi lang.)- https://www.youtube.com/watch?v=mvbTN2I3HxY\n\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n lastPointer = -1\n startPointer = 0\n mInd = (len(arr)-1)//2\n m = arr[mInd]\n res = []\n for i in range(k):\n if abs(arr[lastPointer] - m) >= abs(arr[startPointer] - m):\n res.append(arr[lastPointer])\n lastPointer -= 1\n else:\n res.append(arr[startPointer])\n startPointer += 1\n return res\n\n``` | 3 | 0 | ['Sorting', 'Python', 'Python3'] | 0 |
the-k-strongest-values-in-an-array | Python 3 PriorityQueue solution | python-3-priorityqueue-solution-by-liian-co5l | Since I didn\'t see the PriorityQuene implementation in python I would like to provide my implementation for python guys.\n\n#### PriorityQuene\nTime: O(nlogn + | liianghuang | NORMAL | 2020-06-07T05:20:08.753626+00:00 | 2020-06-07T05:34:46.565232+00:00 | 125 | false | Since I didn\'t see the PriorityQuene implementation in python I would like to provide my implementation for python guys.\n\n#### PriorityQuene\nTime: O(nlogn + nlogk) where n is `len(arr)`\nSpace: O(k)\n```python\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n median = arr[(len(arr) - 1) // 2]\n res = []\n h = []\n \n for a in arr:\n heapq.heappush(h, (abs(a-median), a))\n if len(h) > k:\n heapq.heappop(h)\n \n for _ in range(k):\n res.append(heapq.heappop(h)[1])\n \n return res\n```\n\nOther solutions: \nSorted the second part: `O(nlogn + nlogn)`\nTwo pointer: `O(nlogn + n)`\n\nPlease let me know if there is any other better solution!\n\n\n\n\n\n | 3 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | C++ | beats 100% in memory and time | O(n Log n) | sorting | c-beats-100-in-memory-and-time-on-log-n-3mwll | No mater which algo we perform on this question, we need to sort (in O(n Log n)) our array first.\nThe basic idea is after we sort our array, then we will check | yashsaxena9 | NORMAL | 2020-06-07T04:32:30.546256+00:00 | 2020-06-07T04:33:34.841098+00:00 | 274 | false | **No mater which algo we perform on this question, we need to sort (in O(n Log n)) our array first.**\nThe basic idea is after we sort our array, then we will check values from beginning and last for the condition mentioned in question (abs(arr[j] - median) > abs(arr[i] - median)) to find strong elements.\nWe will increment or decrement the index according to requirement from the side where we find last strong component.\n```\nvector<int> getStrongest(vector<int>& arr, int k) {\n\tsort(arr.begin(), arr.end());\n\tint m = arr.size() - 1 >> 1;\n\tvector<int> ans;\n\tint i = 0, j = arr.size() - 1;\n\twhile(k > 0) {\n\t\tint val1 = abs(arr[j] - arr[m]), val2 = abs(arr[i] - arr[m]);\n\t\tif(val2 > val1) {\n\t\t\tans.push_back(arr[i]);\n\t\t\ti++;\n\t\t}\n\t\telse {\n\t\t\tans.push_back(arr[j]);\n\t\t\tj--;\n\t\t}\n\t\tk--;\n\t}\n\treturn ans;\n}\n``` | 3 | 0 | ['C', 'Sorting', 'C++'] | 0 |
the-k-strongest-values-in-an-array | JAVA TWO POINTERS VERY EASY TO UNDERSTAND | java-two-pointers-very-easy-to-understan-l374 | \nclass Solution {\n public int[] getStrongest(int[] nums, int k) {\n int[] res = new int[k];\n Arrays.sort(nums);\n int size = nums.len | jianhuilin1124 | NORMAL | 2020-06-07T04:12:52.678690+00:00 | 2020-06-07T04:12:52.678754+00:00 | 346 | false | ```\nclass Solution {\n public int[] getStrongest(int[] nums, int k) {\n int[] res = new int[k];\n Arrays.sort(nums);\n int size = nums.length;\n int m = (size - 1) / 2;\n int median = nums[m];\n int index = 0;\n int left = 0, right = size - 1;\n while (left <= right){\n if ((nums[right] - median) >= (median - nums[left]))\n res[index++] = nums[right--];\n else\n res[index++] = nums[left++];\n if (index == k)\n break;\n }\n return res;\n }\n}\n``` | 3 | 0 | ['Java'] | 1 |
the-k-strongest-values-in-an-array | Clean Python 3, generator with deque | clean-python-3-generator-with-deque-by-l-q3wn | Time: O(sort), it can reach O(N) if we adopt counting sort\nSpace: O(N) for output\nThanks grokus for his suggestion.\n\nimport collections\nclass Solution:\n | lenchen1112 | NORMAL | 2020-06-07T04:03:52.031235+00:00 | 2020-06-07T04:28:03.270124+00:00 | 272 | false | Time: `O(sort)`, it can reach O(N) if we adopt counting sort\nSpace: `O(N)` for output\nThanks [grokus](https://leetcode.com/grokus/) for his suggestion.\n```\nimport collections\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n def gen(A):\n dq = collections.deque(A)\n n = len(dq)\n m = dq[(n - 1) // 2]\n for _ in range(k):\n front, tail = m - dq[0], dq[-1] - m\n if front > tail:\n yield dq.popleft()\n else:\n yield dq.pop()\n return list(gen(sorted(arr)))\n``` | 3 | 0 | [] | 1 |
the-k-strongest-values-in-an-array | C# - Simple Sorting | c-simple-sorting-by-christris-z5fv | csharp\npublic int[] GetStrongest(int[] arr, int k) \n{\n\tArray.Sort(arr);\n\tint m = arr[(arr.Length - 1)/ 2];\n\n\tvar result = arr.OrderByDescending(x => Ma | christris | NORMAL | 2020-06-07T04:02:26.245636+00:00 | 2020-06-07T04:02:26.245690+00:00 | 124 | false | ```csharp\npublic int[] GetStrongest(int[] arr, int k) \n{\n\tArray.Sort(arr);\n\tint m = arr[(arr.Length - 1)/ 2];\n\n\tvar result = arr.OrderByDescending(x => Math.Abs(x - m)).ThenByDescending(x => x).Take(k).ToArray();\n\treturn result;\n}\n``` | 3 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | SIMPLE TWO-POINTER C++ SOLUTION | simple-two-pointer-c-solution-by-jeffrin-rzvr | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Jeffrin2005 | NORMAL | 2024-07-22T12:05:51.722673+00:00 | 2024-07-22T12:05:51.722692+00:00 | 169 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:o(k)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:o(k)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(), arr.end());\n int n = arr.size();\n int median = arr[(n - 1) / 2];\n int left = 0;\n int right = n - 1;\n vector<int>result;\n for(int i=0; i<k; i++){// we only need k elements \n if (abs(arr[right] - median) >= abs(arr[left] - median)) {// if both are equal we need to select the higher one ,if greater select right as defualt\n // right will be always higher (bcoz we already sorted)\n result.push_back(arr[right]);\n right--;\n }else{\n result.push_back(arr[left]);\n left++;\n }\n }\n \n return result;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
the-k-strongest-values-in-an-array | BEST C++ solution || Beginner-friendly approach || Beats 90% !! | best-c-solution-beginner-friendly-approa-xl8h | Code\n\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n vector<int> ans;\n sort(arr.begin(), arr.end());\n | prathams29 | NORMAL | 2023-06-29T05:38:04.527248+00:00 | 2023-06-29T05:38:04.527274+00:00 | 244 | false | # Code\n```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n vector<int> ans;\n sort(arr.begin(), arr.end());\n int a = arr.size(), m = arr[(a-1)/2], i=0, j=a-1;\n while(i<=j){\n if(abs(arr[i]-m) > abs(arr[j]-m))\n ans.push_back(arr[i++]);\n else\n ans.push_back(arr[j--]);\n }\n return {ans.begin(), ans.begin()+k};\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
the-k-strongest-values-in-an-array | Easy python solution using two pointers | easy-python-solution-using-two-pointers-hnbsv | \n# Code\n\nclass Solution(object):\n def getStrongest(self, arr, k):\n """\n :type arr: List[int]\n :type k: int\n :rtype: List[ | Lalithkiran | NORMAL | 2023-03-30T09:42:40.695471+00:00 | 2023-03-30T09:42:40.695517+00:00 | 249 | false | \n# Code\n```\nclass Solution(object):\n def getStrongest(self, arr, k):\n """\n :type arr: List[int]\n :type k: int\n :rtype: List[int]\n """\n arr.sort()\n lo=0\n hi=len(arr)-1\n m=arr[hi//2]\n lst=[]\n for i in arr:\n lst.append(abs(m-i))\n l=[]\n while lo<=hi:\n if lst[lo]>lst[hi]:\n l.append(arr[lo])\n lo+=1\n else:\n l.append(arr[hi])\n hi-=1\n k-=1\n if not k:\n return l\n \n \n``` | 2 | 0 | ['Array', 'Two Pointers', 'Sorting', 'Python'] | 0 |
the-k-strongest-values-in-an-array | python3 two pointer | python3-two-pointer-by-seifsoliman-l9t4 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | seifsoliman | NORMAL | 2023-03-01T11:48:12.372000+00:00 | 2023-03-01T11:51:31.838016+00:00 | 295 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n O(NlogN)\n\n- Space complexity:\n O(N)\n# Code\n```\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n mid = arr[(len(arr)-1)//2]\n ans = []\n l ,r = 0, len(arr)-1\n while(l <= r):\n if abs(arr[l] - mid) > abs(arr[r]-mid) :\n ans.append(arr[l])\n l+=1\n else:\n ans.append(arr[r])\n r-=1\n return ans[:k]\n``` | 2 | 0 | ['Array', 'Two Pointers', 'Sorting', 'Python3'] | 0 |
the-k-strongest-values-in-an-array | C++✅✅ | Beginner Friendly Approach | Sorting + Vector of Pairs | | c-beginner-friendly-approach-sorting-vec-u9cj | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | mr_kamran | NORMAL | 2022-10-05T10:35:35.808562+00:00 | 2022-10-05T10:35:35.808600+00:00 | 676 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n\n sort(arr.begin(),arr.end());\n int mid = arr[(arr.size()-1)/2];\n\n vector<pair<int,int>>vp;\n\n for(auto it : arr)\n { int temp = abs(it-mid);\n vp.push_back(make_pair(temp,it));\n }\n \n sort(vp.begin(),vp.end(),greater<pair<int,int>>());\n \n vector<int>ans;\n\n for(int i=0;i<k;++i)\n {\n ans.push_back(vp[i].second);\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
the-k-strongest-values-in-an-array | C++ K strongest values in the array | c-k-strongest-values-in-the-array-by-gur-zvs9 | \nif like it upvote.......\u2661\n\n\nvector getStrongest(vector& arr, int k) {\n vectorans;\n sort(arr.begin(),arr.end());\n int mid=arr[( | Gurjeet07 | NORMAL | 2022-09-21T21:00:01.323838+00:00 | 2022-09-21T21:02:30.896126+00:00 | 286 | false | \n**if like it upvote.......\u2661**\n\n\nvector<int> getStrongest(vector<int>& arr, int k) {\n vector<int>ans;\n sort(arr.begin(),arr.end());\n int mid=arr[(arr.size()-1)/2];\n int s=0;\n int e=arr.size()-1;\n while(s<=e)\n {\n if(abs(arr[s]-mid)>abs(arr[e]-mid))\n {\n ans.push_back(arr[s]);\n s++;\n }\n else\n {\n ans.push_back(arr[e]);\n e--;\n }\n if(ans.size()==k)\n {\n break;\n }\n }\n return ans;\n } | 2 | 1 | ['Two Pointers', 'C', 'Sorting'] | 0 |
the-k-strongest-values-in-an-array | Two pointer implementation question(It took couple of minutes to figure out the logic 🤨) | two-pointer-implementation-questionit-to-pwx2 | \nclass Solution\n{\n public:\n vector<int> getStrongest(vector<int> &arr, int k)\n {\n vector<int> vec;\n sort(arr.begin | Tan_B | NORMAL | 2022-09-14T04:39:57.321752+00:00 | 2022-09-14T04:39:57.321796+00:00 | 176 | false | ```\nclass Solution\n{\n public:\n vector<int> getStrongest(vector<int> &arr, int k)\n {\n vector<int> vec;\n sort(arr.begin(), arr.end());\n int med = arr[(arr.size() - 1) / 2];\n int i = 0;//Take one pointer at starting\n int j = arr.size() - 1;//Take one pointer from end\n\t\t\t//Simple Logic - in a sorted array the median is the middle most value and the distance of points from the extremes of the array is maximum from the median(Try to think it as a number line ).\n\t\t\t//As we move toward the median from end points its distance starts decreasing(That\'s the meaning of median)\n while (vec.size() != k)\n {\n int di = abs(med - arr[i]);\n int dj = abs(med - arr[j]);\n if (di > dj)\n vec.push_back(arr[i++]);\n else if (dj > di)\n vec.push_back(arr[j--]);\n else\n {\n if (arr[i] > arr[j])\n vec.push_back(arr[i++]);\n else\n vec.push_back(arr[j--]);\n }\n }\n return vec;\n }\n};\n``` | 2 | 0 | ['Two Pointers'] | 1 |
the-k-strongest-values-in-an-array | 🔥 Javascript Solution - Clean Logic | javascript-solution-clean-logic-by-joeni-m5i8 | \nfunction getStrongest(A, k) {\n // get abs methods\n const { abs, floor } = Math\n \n // sort first\n A.sort((a, b) => a - b)\n \n // get | joenix | NORMAL | 2022-09-05T10:50:57.002924+00:00 | 2022-09-05T10:50:57.002965+00:00 | 260 | false | ```\nfunction getStrongest(A, k) {\n // get abs methods\n const { abs, floor } = Math\n \n // sort first\n A.sort((a, b) => a - b)\n \n // get middle\n const m = A[floor((A.length-1) / 2)]\n \n // soring by middle\n A.sort((a, b) => abs(a - m) - abs(b - m))\n \n // reverse\n A.reverse()\n \n // Strongest Values by k\n return A.slice(0, k)\n}\n``` | 2 | 0 | ['JavaScript'] | 0 |
the-k-strongest-values-in-an-array | Java || O(NlogN) || Single Sort || Two Pointer | java-onlogn-single-sort-two-pointer-by-s-phmj | Once the array is sorted, use the fact that smallest and largest element is going to have the largest absolute difference with the median.\n\n\nclass Solution { | Shrekpozer02 | NORMAL | 2022-01-31T14:44:36.197350+00:00 | 2022-01-31T14:44:36.197398+00:00 | 90 | false | Once the array is sorted, use the fact that smallest and largest element is going to have the largest absolute difference with the median.\n\n```\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n int n = arr.length;\n \n Arrays.sort(arr);\n \n int m = arr[(n-1)/2];\n \n int[] res = new int[k];\n \n int st = 0;\n int ed = n-1;\n int i = 0;\n \n while(st <= ed && i < k){\n int a = Math.abs(arr[st] - m);\n int b = Math.abs(arr[ed] - m);\n \n if(a > b){\n res[i] = arr[st];\n st++;\n } else if(b > a){\n res[i] = arr[ed];\n ed--;\n } else {\n if(arr[st] > arr[ed]){\n res[i] = arr[st];\n st++;\n } else {\n res[i] = arr[ed];\n ed--;\n }\n }\n \n i++;\n }\n \n return res;\n }\n}\n``` | 2 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | C++ | Sorting using lambda function | With comments | c-sorting-using-lambda-function-with-com-fnma | \n\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(),arr.end()); //sort to find the median\n | prnvgautam15 | NORMAL | 2021-07-06T16:03:11.450482+00:00 | 2021-07-06T16:04:49.290182+00:00 | 170 | false | \n```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(),arr.end()); //sort to find the median\n int n=arr.size();\n int med=arr[(n-1)/2]; //median\n \n sort(arr.begin(),arr.end(),[med](int &a,int &b){ //sorting using lambda function\n if(abs(a-med)==abs(b-med))\n return a>b;\n return abs(a-med)>abs(b-med); \n });\n \n return vector<int>(arr.begin(),arr.begin()+k); //return vector slice of size k\n }\n};\n```\n##### Please upvote if you like my solution.\n*Feel free to share your opinion* | 2 | 0 | ['C', 'Sorting'] | 1 |
the-k-strongest-values-in-an-array | C++ | QuickSelect | Faster than 99.86% | c-quickselect-faster-than-9986-by-srijan-5mlv | Naive Approach:\n1. Sort the array in non-decreasing order.\n2. Choose median as (n-1)/2th element.\n3. Sort again based on a criteria given in question.\n\nMy | srijansankrit | NORMAL | 2020-10-14T14:23:58.417181+00:00 | 2020-10-14T14:24:57.287707+00:00 | 136 | false | Naive Approach:\n1. Sort the array in non-decreasing order.\n2. Choose median as (n-1)/2th element.\n3. Sort again based on a criteria given in question.\n\n**My Naive Approach Code:** (940 ms, faster than 39%)\n```\nclass Solution {\npublic:\n int median;\n vector<int> getStrongest(vector<int>& arr, int k) {\n \n\t\tcin.tie(0);\n\t\tios_base::sync_with_stdio(false);\n\t\t\n sort(arr.begin(), arr.end());\n int n = arr.size();\n \n median = arr[(n-1)/2];\n \n sort(arr.begin(), arr.end(), [this](int a, int b){\n if(abs(a - median) != abs(b - median)) return abs(a - median) > abs(b - median);\n return a > b;\n });\n \n arr.resize(k);\n return arr;\n }\n};\n```\n\nWhat are we missing?\nDo we really need to sort the full array?\nOr do we need to find the (n-1/)2th element for finding median, \nand the first k elements after the question criteria given.\n\nWe will use **quickselect** to acheive these tasks in O(n) time. (Worst case O(n^2)).\n\nQuickSelect is basically a partial sort in which we choose a pivot and then keep all smaller elements to the left, and bigger to the right.(We only need this in the question)\n\n\n1. For Finding the median\n\n\tChoose **Pivot** = (n-1)/2.\n\tQuickselect keeps smaller elements in left, bigger in right.\n\tSo arr[n-1/2] will be the median (as defined by question)\n\n2. For finding the kth strongest\n\t\n\tChoose **Pivot** = k.\n\tWe will use a custom comparator such that quickselect keeps greater elements to left and lower to right.\n\tFirst k elements will be the strongest.\n\t\n\t\n**My Quick Select Code:** (256ms, faster than 99.86%)\n\n```\nclass Solution {\npublic:\n int median;\n vector<int> getStrongest(vector<int>& arr, int k) {\n\t\n\t\tcin.tie(0);\n\t\tios_base::sync_with_stdio(false);\n\t\t\n int n = arr.size();\n \n\t\t// A STL method in C++ for quick select.\n\t\t// Pivot is the (n-1)/2 th element.\n nth_element(arr.begin(), arr.begin() + (n-1)/2, arr.end());\n \n median = arr[(n-1)/2];\n \n\t\t// choose pivot = k and custom comparator to do as the question asks.\n nth_element(arr.begin(),arr.begin() + k, arr.end(), [this](int a, int b){\n if(abs(a - median) != abs(b - median)) return abs(a - median) > abs(b - median);\n return a > b;\n });\n \n\t\t// return the first k entries of output array.\n\t\t// Since the order of the answer does not matter, we can simply return the final answer.\n vector<int> ans;\n for(int i=0;i<k;i++) ans.push_back(arr[i]);\n return ans;\n }\n};\n```\n\nThanks and Happy Leetcoding!\n\n | 2 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | [C++] O(n) shortest quickselect solution | c-on-shortest-quickselect-solution-by-al-he5d | Average time complexity : O(n)\nWorst time complexity : O(n^2)\n\n\nint getMedian(vector<int> arr)\n{\n\tnth_element(arr.begin(), next(arr.begin(), \n\t\t(arr.s | aleksey12345 | NORMAL | 2020-06-20T11:31:18.231050+00:00 | 2020-06-20T11:31:18.231076+00:00 | 160 | false | Average time complexity : O(n)\nWorst time complexity : O(n^2)\n\n```\nint getMedian(vector<int> arr)\n{\n\tnth_element(arr.begin(), next(arr.begin(), \n\t\t(arr.size() - 1)/ 2), arr.end());\n\n\treturn arr[(arr.size() - 1)/ 2];\n}\n\nvector<int> getStrongest(vector<int>& arr, int k) \n{\n\tauto median = getMedian(arr);\n\n\tnth_element(arr.begin(), next(arr.begin(), k), arr.end(), \n\t\t[median](auto n1, auto n2)\n\t\t\t{ return abs(median - n1) == abs(median - n2) ?\n\t\t\t\tn1 > n2 : abs(median - n1) > abs(median - n2); });\n\n\treturn vector<int>(arr.begin(), next(arr.begin(), k));\n}\n``` | 2 | 0 | [] | 1 |
the-k-strongest-values-in-an-array | Java Solution | java-solution-by-bhaveshan-1nw8 | \nclass Solution {\n \n public int[] getStrongest(int[] arr, int k) {\n \n int i = 0, j = arr.length - 1, l = 0;\n if (j == -1) retur | bhaveshan | NORMAL | 2020-06-16T13:23:51.405513+00:00 | 2020-06-16T13:23:51.405557+00:00 | 93 | false | ```\nclass Solution {\n \n public int[] getStrongest(int[] arr, int k) {\n \n int i = 0, j = arr.length - 1, l = 0;\n if (j == -1) return new int[0];\n Arrays.sort(arr);\n int median = arr[j / 2];\n int[] res = new int[k];\n while (l < k){\n if (median - arr[i] > arr[j] - median)\n res[l++] = arr[i++];\n else\n res[l++] = arr[j--];\n }\n return res;\n }\n}\n``` | 2 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | scala functional programming (anyone knows why scala is so slow on leetcode?) | scala-functional-programming-anyone-know-z80t | object Solution {\n def getStrongest(arr: Array[Int], k: Int): Array[Int] = {\n val sortArr = arr.sorted\n val len = arr.size\n val med | ls1229 | NORMAL | 2020-06-10T15:09:57.389412+00:00 | 2020-06-10T15:09:57.389449+00:00 | 57 | false | ```object Solution {\n def getStrongest(arr: Array[Int], k: Int): Array[Int] = {\n val sortArr = arr.sorted\n val len = arr.size\n val med = sortArr((len-1)/2)\n def helper(acc:Array[Int], k:Int, l:Int, r:Int):Array[Int] = \n if (k==0) acc\n else if(med-sortArr(l)>sortArr(r)-med) helper(acc:+sortArr(l), k-1, l+1, r)\n else helper(acc:+sortArr(r), k-1, l, r-1)\n helper(Array(), k, 0, len-1)\n \n \n }\n}\n``` | 2 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | Best Video Explanation in Hindi | Two Pointer Approach | best-video-explanation-in-hindi-two-poin-w5p8 | Link to the video - https://www.youtube.com/watch?v=mvbTN2I3HxY\n\nI found the best video explanation for the problem on CodingBeast youtube channel. I guess th | CodingBeastOfficial | NORMAL | 2020-06-08T22:41:57.765949+00:00 | 2020-06-11T16:53:06.824036+00:00 | 62 | false | Link to the video - https://www.youtube.com/watch?v=mvbTN2I3HxY\n\nI found the best video explanation for the problem on CodingBeast youtube channel. I guess the target audience are Indians as the language spoken in the video is Hindi. | 2 | 0 | [] | 1 |
the-k-strongest-values-in-an-array | Java stream&sorting solution | java-streamsorting-solution-by-msmych-d1cx | java\nimport static java.lang.Math.*;\nimport static java.util.Arrays.*;\nimport static java.util.Comparator.*;\n\nclass Solution {\n public int[] getStronge | msmych | NORMAL | 2020-06-08T10:25:47.159350+00:00 | 2020-06-08T10:25:47.159383+00:00 | 182 | false | ```java\nimport static java.lang.Math.*;\nimport static java.util.Arrays.*;\nimport static java.util.Comparator.*;\n\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n sort(arr);\n var median = arr[(arr.length - 1) / 2];\n return stream(arr)\n .boxed() // need to box/unbox as `sorted()` is not overloaded for `IntStream`\n .sorted(comparingInt((Integer n) -> abs(n - median)).thenComparingInt(n -> n).reversed())\n .mapToInt(n -> n)\n .limit(k)\n .toArray();\n }\n}\n``` | 2 | 0 | ['Sorting', 'Java'] | 0 |
the-k-strongest-values-in-an-array | Python Sort using Lambda 100% Faster | python-sort-using-lambda-100-faster-by-t-7qpd | \nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n n = len(arr)\n m = arr[(n-1)//2] # Comp | tad_ko | NORMAL | 2020-06-07T05:10:48.815402+00:00 | 2020-06-07T05:11:04.630422+00:00 | 103 | false | ```\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n n = len(arr)\n m = arr[(n-1)//2] # Compute median\n arr.sort(key=lambda x:(-abs(x-m),-x)) \n return arr[:k]\n``` | 2 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | Javascript Sorting solution | javascript-sorting-solution-by-seriously-jv6s | \nvar getStrongest = function(arr, k) {\n arr.sort(function(a,b){return a-b});\n\t//find median\n var med = arr[Math.floor((arr.length-1)/2)];\n\t//sort u | seriously_ridhi | NORMAL | 2020-06-07T05:00:54.977503+00:00 | 2020-06-07T05:00:54.977539+00:00 | 97 | false | ```\nvar getStrongest = function(arr, k) {\n arr.sort(function(a,b){return a-b});\n\t//find median\n var med = arr[Math.floor((arr.length-1)/2)];\n\t//sort using median\n arr.sort(function(a,b){return Math.abs(a-med) - Math.abs(b-med)});\n\t//reverse the array and slice for K strongest values\n arr.reverse();\n return arr.slice(0,k)\n};\n``` | 2 | 0 | [] | 1 |
the-k-strongest-values-in-an-array | [Python] 2-pointers solution beats 90% | python-2-pointers-solution-beats-90-by-l-stld | python\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n N = len(arr)\n median = arr[(N-1)/ | luolingwei | NORMAL | 2020-06-07T04:28:14.520343+00:00 | 2020-06-07T04:28:42.456881+00:00 | 102 | false | ```python\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n N = len(arr)\n median = arr[(N-1)//2]\n i,j = 0,N-1\n res = []\n while i<=j and len(res)<k:\n if abs(arr[i]-median)>abs(arr[j]-median):\n res.append(arr[i])\n i+=1\n else:\n res.append(arr[j])\n j-=1\n return res\n``` | 2 | 0 | [] | 1 |
the-k-strongest-values-in-an-array | Python, using sorted, Custom Sort | python-using-sorted-custom-sort-by-akshi-bh9d | \n # Sort the array to find the median\n arr.sort()\n med = arr[(len(arr)-1 )//2 ]\n \n # Now sort the array in Descending or | akshit0699 | NORMAL | 2020-06-07T04:20:17.573319+00:00 | 2020-06-07T04:20:53.737983+00:00 | 190 | false | ```\n # Sort the array to find the median\n arr.sort()\n med = arr[(len(arr)-1 )//2 ]\n \n # Now sort the array in Descending order of values abs(num - med)\n # If two values are same, use the face value(num)\n\t\t# Choose only the first k values.\n return sorted(arr, key = lambda num: (abs(num-med), num), reverse = True)[:k]\n \n``` | 2 | 0 | ['Python'] | 1 |
the-k-strongest-values-in-an-array | Custom lambda sort O(N) amortized update | custom-lambda-sort-on-amortized-update-b-r0ej | \nint n = arr.size();\nnth_element(begin(arr), begin(arr) + (n-1)/2, end(arr));\nint m = arr[(n-1)/2];\nsort(begin(arr), begin(arr) + k, end(arr), [&m] (const a | gh05t | NORMAL | 2020-06-07T04:03:01.069715+00:00 | 2020-06-10T01:22:32.554205+00:00 | 266 | false | ```\nint n = arr.size();\nnth_element(begin(arr), begin(arr) + (n-1)/2, end(arr));\nint m = arr[(n-1)/2];\nsort(begin(arr), begin(arr) + k, end(arr), [&m] (const auto &i, const auto &j) {\n if(abs(m - i) != abs(m - j))\n return abs(m - i) > abs(m - j);\n else\n return i > j;\n});\nreturn {begin(arr), begin(arr) + k};\n```\n\nUpdate:\n```nth_element(begin(arr), begin(arr) + k, end(arr), [&m] (const auto &i, const auto &j)```\n\nYou don\'t have to sort the range in order the only requirement is to have all the elements present, *order doesn\'t matter*, so nth_element twice is the best approach, in the contest I used sort for the second operation but I just realized the condition is **not necessary**, nth_element accepts the same binary predicate. | 2 | 0 | ['C'] | 0 |
the-k-strongest-values-in-an-array | [C++] Custom sort | c-custom-sort-by-zhanghuimeng-pzmq | Sort an array by the absolute difference of each element from the median.\n\n# Explanation\n\nUse a custom sort. The first key is |a[i] - median|, and the secon | zhanghuimeng | NORMAL | 2020-06-07T04:02:18.542371+00:00 | 2020-06-07T04:02:18.542415+00:00 | 103 | false | Sort an array by the absolute difference of each element from the median.\n\n# Explanation\n\nUse a custom sort. The first key is `|a[i] - median|`, and the second key is `a[i]`. The biggest `k` elements are the strongest ones.\n\nThe time complexity is `O(n*log(n))`.\n\n# C++ Solution\n\n```cpp\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n int n = arr.size();\n sort(arr.begin(), arr.end());\n int median = arr[(n + 1) / 2 - 1];\n \n vector<pair<int, int>> a;\n for (int i = 0; i < n; i++)\n a.emplace_back(abs(arr[i] - median), arr[i]);\n sort(a.begin(), a.end());\n \n vector<int> ans;\n for (int i = 0; i < k; i++)\n ans.push_back(a[n - i - 1].second);\n \n return ans;\n }\n};\n``` | 2 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | [Java] Sort + Two Pointers | java-sort-two-pointers-by-manrajsingh007-uxem | ```\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n int n = arr.length;\n Arrays.sort(arr);\n int mid = (n - 1) / 2; | manrajsingh007 | NORMAL | 2020-06-07T04:01:12.037985+00:00 | 2020-06-07T04:01:12.038038+00:00 | 225 | false | ```\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n int n = arr.length;\n Arrays.sort(arr);\n int mid = (n - 1) / 2;\n int left = 0, right = n - 1, count = 0;\n int[] ans = new int[k];\n int it = 0;\n while(count < k && left <= right) {\n count++;\n int x = Math.abs(arr[mid] - arr[left]), y = Math.abs(arr[mid] - arr[right]);\n if(x > y) ans[it++] = arr[left++];\n else ans[it++] = arr[right--];\n }\n return ans;\n }\n} | 2 | 1 | [] | 1 |
the-k-strongest-values-in-an-array | Java Solution | java-solution-by-dsuryaprakash89-vmj8 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | dsuryaprakash89 | NORMAL | 2024-11-27T07:05:20.240202+00:00 | 2024-11-27T07:05:20.240224+00:00 | 56 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N log N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```java []\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n //find the median\n Arrays.sort(arr);\n int median = (arr.length-1)/2;\n //intialise a max heap so that it stores the maximum absolute difference element \n //if difference is same it should store max element at top followed by min element\n PriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->{\n int diffA= Math.abs(a[0]-arr[median]);\n int diffB= Math.abs(b[0]-arr[median]);\n if(diffA!=diffB){\n return Integer.compare(diffB,diffA);\n }else{\n return Integer.compare(b[0],a[0]);\n }\n });\n for(int i:arr){\n pq.add(new int[]{i});\n }\n int[] res = new int[k];\n int t=0;\n while(k!=0){\n int [] top=pq.poll();\n res[t]=top[0];\n t++;\n k--;\n }\n return res;\n }\n}\n``` | 1 | 0 | ['Array', 'Sorting', 'Heap (Priority Queue)', 'Java'] | 0 |
the-k-strongest-values-in-an-array | Shortest, Easiest & Well Explained || To the Point & Beginners Friendly Approach (❤️ ω ❤️) | shortest-easiest-well-explained-to-the-p-n8of | Welcome to My Coding Family\u30FE(\u2267 \u25BD \u2266)\u309D\nThis is my shortest, easiest & to the point approach. This solution mainly aims for purely beginn | Nitansh_Koshta | NORMAL | 2023-12-27T14:33:49.089870+00:00 | 2023-12-27T14:33:49.089895+00:00 | 3 | false | # Welcome to My Coding Family\u30FE(\u2267 \u25BD \u2266)\u309D\n*This is my shortest, easiest & to the point approach. This solution mainly aims for purely beginners so if you\'re new here then too you\'ll be very easily be able to understand my this code. If you like my code then make sure to UpVOTE me. Let\'s start^_~*\n\n# Approach:-\n\n1. First create a pair of vector of data type integer to store the numbers pairwise so that we can sort it later.\n2. Now, sort the given vector \'v\' in ascending/increasing order to get the median from vector \'v\'.\n3. Use v[(v.size()-1)/2] formula for getting the median & store it inside an integer \'m\'.\n4. Now iterate from the 0th till the end index of vector \'v\' & insert the pair of absolute value of ith element minus \'m\' of vector \'v\' & ith element of \'v\' i.e. {abs(v[i]-m),v[i]} inside our vector pair \'p\'.\n5. Now as we\'re done with vector \'v\' then clear vector \'v\' & sort the vector pair \'p\' in decending/decreasing order.\n6. Now at the end, just iterate from the 0th till \'k\' inside vector pair \'p\' and insert all the second element of p[i] inside vector \'v\'. Then return \'v\' as answer.\n\n**The code is given below for further understanding(p\u2267w\u2266q)**\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& v, int k) {\n vector<pair<int,int>>p;\n sort(v.begin(),v.end());\n int m=v[(v.size()-1)/2];\n for(auto i:v)p.push_back({abs(i-m),i});\n v.clear();\n sort(p.rbegin(),p.rend());\n for(int i=0;i<k;i++)v.push_back(p[i].second);\n return v;\n\n// if my code helped you then please UpVOTE me, an UpVOTE encourages me to bring some more exciting codes for my coding family. Thank You o((>\u03C9< ))o\n }\n};\n```\n\n\n | 1 | 0 | ['C++'] | 0 |
the-k-strongest-values-in-an-array | Simple Python Solution | simple-python-solution-by-djdjned-8cjj | Intuition\n Describe your first thoughts on how to solve this problem. \nThink of the median as a balancing point in the array. Elements on one side of the medi | djdjned | NORMAL | 2023-08-07T12:24:46.566991+00:00 | 2023-08-08T12:48:45.683192+00:00 | 29 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThink of the median as a balancing point in the array. Elements on one side of the median have maximum element than the other side. Stronger elements are those that are farther away from the median, causing an imbalance.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. arr.sort(): This sorts the input list arr in ascending order. Sorting the list allows for easier comparison and selection of the closest elements.\n\n2. median = arr[(len(arr) - 1) // 2]: This calculates the median of the sorted list arr. If the length of the list is odd, the median is the element at the middle index. If the length is even, it\'s the average of the two middle elements.\n3. Initialize ans, left, and right: ans will store the k closest elements, and left and right are pointers that help traverse the sorted list from both ends towards the middle.\n4. while left <= right:: This initiates a loop that continues as long as the pointers left and right haven\'t crossed each other.\n5. Inside the loop:\n\n- abs(arr[left] - median) calculates the absolute difference between the element at index left and the median.\n\n- abs(arr[right] - median) calculates the absolute difference between the element at index right and the median.\n- The if condition compares the absolute differences of the elements at the left and right positions. The element with the smaller absolute difference is considered closer to the median.\n- If the element at the left position is closer, it\'s appended to the ans list, and left is incremented.\n- If the element at the right position is closer, it\'s appended to the ans list, and right is decremented.\n- return ans[:k]: Finally, the function returns the first k elements from the ans list, which are the k closest elements to the median.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n log n)\nRuntime 858ms ,Beats 90.34% of users with Python3\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\nMemory 29.46mb , Beats 97.16% of users with Python3\n\n# Code\n```\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n median = arr[(len(arr) - 1) //2]\n ans = []\n left = 0 \n right = len(arr)-1\n while left<=right:\n if abs(arr[left] - median) > abs(arr[right] - median):\n ans.append(arr[left])\n left+=1\n else:\n ans.append(arr[right])\n right-=1\n return ans[:k]\n``` | 1 | 0 | ['Array', 'Two Pointers', 'Sorting', 'Python3'] | 0 |
the-k-strongest-values-in-an-array | c# : Easy Solution | c-easy-solution-by-rahul89798-esf9 | Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n\npublic class Solution {\n public int[] GetStrongest(int[] arr, int k) {\n | rahul89798 | NORMAL | 2023-06-04T07:54:11.723651+00:00 | 2023-06-04T07:54:11.723703+00:00 | 17 | false | # Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\npublic class Solution {\n public int[] GetStrongest(int[] arr, int k) {\n Array.Sort(arr);\n var ans = new int[k];\n var median = arr[(arr.Length - 1) / 2];\n\n Array.Sort(arr, (a, b) => {\n var temp1 = Math.Abs(a - median);\n var temp2 = Math.Abs(b - median);\n if(temp1 == temp2)\n return b.CompareTo(a);\n \n return temp2.CompareTo(temp1);\n });\n\n for(int i = 0; i < k; i++)\n ans[i] = arr[i];\n\n return ans;\n }\n}\n``` | 1 | 0 | ['Sorting', 'C#'] | 0 |
the-k-strongest-values-in-an-array | USING HEAP. | using-heap-by-heythereguys-fgca | Intuition\nWeight=abs(arr[i]-m), where m is median.\nIn this problem we need to return the vector ans . Giving the biggest elements having the biggest weight.\n | HeyThereGuys | NORMAL | 2023-05-31T10:03:46.830065+00:00 | 2023-05-31T10:03:46.830097+00:00 | 16 | false | # Intuition\nWeight=abs(arr[i]-m), where m is median.\nIn this problem we need to return the vector ans . Giving the biggest elements having the biggest weight.\nMeans if an element have a bigger weight u have to store that element. But if u have a clash with element having equal weights , bigger element wins. \n\n# Approach\n1. First find the median.\n2. Make a map for assigning elements according to their weights.\n3. Map is formed with <int, heap> to return the biggest element first.\n4. Also for accessing the bigger weight first , we used a priority_queue(heap), which returns weight in decreasing order. \n\n# Complexity\n- Time complexity:\nO(N*logN), N for traversing throught each element of the array.\nand logN used by heapify algorithm(Arranging elements in decreasing order in heap in this question).\n\n- Space complexity:\nO(N*M), where N is the different weights.\nand M are the size of the heap assigned to different weights.\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n //find median\n sort(arr.begin(),arr.end());\n int n=arr.size();\n int m=arr[(n-1)/2];\n\n //using heap to find k strongest elements\n priority_queue<int>heap;\n unordered_map<int,priority_queue<int>>mapping;\n for(int i=0;i<n;i++){\n int weight=abs(arr[i]-m);\n mapping[weight].push(arr[i]);\n if(mapping[weight].size()==1)heap.push(weight);\n }\n vector<int>ans;\n while(ans.size()<k){\n int w=heap.top();\n heap.pop();\n while(ans.size()<k && !mapping[w].empty()){\n int ele=mapping[w].top();\n mapping[w].pop();\n ans.push_back(ele);\n }\n }\n \n return ans;\n }\n};\n``` | 1 | 0 | ['Hash Table', 'Heap (Priority Queue)', 'C++'] | 1 |
the-k-strongest-values-in-an-array | C | c-by-tinachien-eyi6 | \nint cmp(const void* a, const void* b){\n return *(int*)a - *(int*)b;\n}\nint* getStrongest(int* arr, int arrSize, int k, int* returnSize){\n qsort(arr, | TinaChien | NORMAL | 2022-11-30T12:14:59.493185+00:00 | 2022-11-30T12:14:59.493228+00:00 | 84 | false | ```\nint cmp(const void* a, const void* b){\n return *(int*)a - *(int*)b;\n}\nint* getStrongest(int* arr, int arrSize, int k, int* returnSize){\n qsort(arr, arrSize, sizeof(int), cmp);\n int median = arr[(arrSize-1)/2];\n int* ans = malloc(k * sizeof(int));\n int left = 0, right = arrSize-1;\n for(int i = 0; i < k; i++){\n if((arr[right] - median) >= (median - arr[left])){\n ans[i] = arr[right];\n right--;\n }\n else{\n ans[i] = arr[left];\n left++;\n }\n }\n *returnSize = k;\n return ans;\n}\n\n``` | 1 | 0 | [] | 1 |
the-k-strongest-values-in-an-array | C++ Easy 2 Pointers | c-easy-2-pointers-by-decimalx-oi6q | C++ Simple and easy\n\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(), arr.end());\n int me | decimalx | NORMAL | 2022-07-18T02:01:45.521242+00:00 | 2022-07-18T02:01:45.521288+00:00 | 215 | false | C++ Simple and easy\n```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(), arr.end());\n int median = arr[(arr.size() - 1) / 2];\n vector<int> res;\n int left = 0, right = arr.size() - 1;\n while(left <= right && k--){\n int leftRes = abs(arr[left] - median);\n int rightRes = abs(arr[right] - median);\n \n if (leftRes > rightRes) {\n res.push_back(arr[left]);\n ++left;\n }\n else{\n res.push_back(arr[right]);\n --right;\n }\n }\n return res;\n }\n};\n``` | 1 | 0 | ['Two Pointers', 'C', 'Sorting'] | 0 |
the-k-strongest-values-in-an-array | C++ Two Pointer + Sorting | c-two-pointer-sorting-by-user7710z-hp0z | \nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(),arr.end());\n int n=arr.size();\n i | user7710z | NORMAL | 2022-06-10T12:17:05.916164+00:00 | 2022-06-10T12:17:05.916194+00:00 | 150 | false | ```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(),arr.end());\n int n=arr.size();\n int m=arr[(n-1)/2];\n vector<int>ans;\n int i=0,j=n-1;\n int sz=0;\n while(i<=j and sz<k){\n if(m-arr[i]>arr[j]-m){\n ans.push_back(arr[i]);\n i++;\n }else if(m-arr[i]<arr[j]-m){\n ans.push_back(arr[j]);\n j--;\n }else{\n if(arr[i]>arr[j]){\n ans.push_back(arr[i]);\n i++;\n }else{\n ans.push_back(arr[j]);\n j--;\n }\n }\n sz++;\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['Two Pointers', 'C', 'Sorting'] | 0 |
the-k-strongest-values-in-an-array | javascript easy understanding | javascript-easy-understanding-by-sherif-o9afs | \nvar getStrongest = function(arr, k) { \n\t// sort array so we can easily find median\n const sorted = arr.sort((a,b) => a-b)\n\t// get index of median\n | sherif-ffs | NORMAL | 2022-06-06T03:20:46.524178+00:00 | 2022-06-06T03:20:46.524226+00:00 | 88 | false | ```\nvar getStrongest = function(arr, k) { \n\t// sort array so we can easily find median\n const sorted = arr.sort((a,b) => a-b)\n\t// get index of median\n\tconst medianIndex = Math.floor(((sorted.length-1)/2))\n\t// get median\n const median = sorted[medianIndex]\n\n\t// custom sort function following the parameters given us in the description\n const compareFunction = (a, b) => {\n if (Math.abs(a-median) > Math.abs(b-median)) {\n return 1\n }\n else if (Math.abs(a-median) === Math.abs(b-median) && a > b) {\n return 1\n } else {\n return -1\n }\n }\n \n\t// sort array using our custom sort function\n const strongest = arr.sort(compareFunction).reverse().slice(0,k);\n \n return strongest;\n};\n``` | 1 | 0 | ['JavaScript'] | 0 |
the-k-strongest-values-in-an-array | easyyyy | easyyyy-by-aavii-gko8 | ```\nclass Solution {\npublic:\n vector getStrongest(vector& arr, int k) {\n int n = arr.size();\n sort(arr.begin(), arr.end());\n int m | aavii | NORMAL | 2022-06-01T12:39:52.570521+00:00 | 2022-06-01T12:40:13.738484+00:00 | 99 | false | ```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n int n = arr.size();\n sort(arr.begin(), arr.end());\n int med = arr[(n-1)/2];\n int left = 0, right = arr.size()-1;\n \n k = min(k,(int) arr.size());\n vector<int> res;\n while(left<=right && k)\n {\n if(abs(med-arr[left])<=abs(med-arr[right]))\n {\n while(left<right && arr[right]==arr[right-1]) \n {\n if(!k) return res;\n res.push_back(arr[right]);\n right--;\n k--;\n }\n if(k) \n {\n res.push_back(arr[right]);\n right--;\n k--;\n }\n }\n else\n {\n while(left<right && arr[left]==arr[left+1]) \n {\n if(!k) return res;\n res.push_back(arr[left]);\n left++;\n k--;\n }\n if(k)\n {\n res.push_back(arr[left]);\n left++;\n k--;\n }\n }\n }\n return res;\n }\n}; | 1 | 0 | ['Two Pointers', 'C'] | 0 |
the-k-strongest-values-in-an-array | Custom Sorting || PAIRS || EASY || CPP | custom-sorting-pairs-easy-cpp-by-peerona-hbe3 | \nclass Solution {\npublic:\n static bool comp(pair<int,int> &A,pair<int,int> &B){\n if(A.first>B.first) return true;\n else if(A.first==B.firs | PeeroNappper | NORMAL | 2022-05-03T09:24:45.986852+00:00 | 2022-05-03T09:24:45.986895+00:00 | 68 | false | ```\nclass Solution {\npublic:\n static bool comp(pair<int,int> &A,pair<int,int> &B){\n if(A.first>B.first) return true;\n else if(A.first==B.first) return A.second>B.second;\n return false;\n }\n vector<int> getStrongest(vector<int>& arr, int k) {\n vector<int> P=arr;\n sort(P.begin(),P.end());\n int m=(P[(P.size()-1)/2]); \n vector<pair<int,int>> Q;\n for(int i=0;i<arr.size();i++){\n Q.push_back({abs(arr[i]-m),arr[i]});\n }\n sort(Q.begin(),Q.end(),comp);\n P.clear();\n for(int i=0;i<Q.size() && i<k;i++){\n P.push_back(Q[i].second);\n }\n return P;\n }\n};\n``` | 1 | 0 | ['Sorting', 'C++'] | 0 |
the-k-strongest-values-in-an-array | C++ | Custom Sort | c-custom-sort-by-__struggler-4gk1 | \nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(),arr.end());\n int n=arr.size();\n i | __struggler__ | NORMAL | 2022-04-08T14:18:29.930310+00:00 | 2022-04-08T14:18:29.930351+00:00 | 38 | false | ```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(),arr.end());\n int n=arr.size();\n int m=arr[(n-1)/2];\n sort( arr.begin( ), arr.end( ), [m]( const auto& x1, const auto& x2 )\n{\n return abs(x1-m) == abs(x2-m) ? x1 > x2 : abs(x1-m) > abs(x2-m);\n});\n vector<int> res(arr.begin(),arr.begin()+k);\n return res;\n }\n};\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | C++ Solution -Using Priority Queue | c-solution-using-priority-queue-by-sakth-m9ot | ```\nclass Solution {\npublic:\n struct compare{\n bool operator()(pair p1,pair p2){\n if (p1.first==p2.first){\n return p1. | sakthi37 | NORMAL | 2021-08-17T12:09:06.829549+00:00 | 2021-08-17T12:09:06.829596+00:00 | 69 | false | ```\nclass Solution {\npublic:\n struct compare{\n bool operator()(pair<int,int> p1,pair<int,int> p2){\n if (p1.first==p2.first){\n return p1.second<p2.second;\n }\n else{\n return p1.first<p2.first;\n }\n }\n };\n vector<int> getStrongest(vector<int>& arr, int k) {\n priority_queue<pair<int,int>,vector<pair<int,int>>,compare> pq;\n vector<int> v1;\n sort(arr.begin(),arr.end());\n int median= arr.size()%2!=0 ? arr[(arr.size()/2)] :arr[arr.size()/2-1];\n for (int i=0;i<arr.size();i++){\n pq.push({abs(arr[i]-median),arr[i]});\n }\n while (!pq.empty() && k--){\n v1.push_back(pq.top().second);\n pq.pop();\n }\n return v1;\n }\n}; | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | [C++] : O(nlog(n)) : Sorting | c-onlogn-sorting-by-zanhd-himo | \n\tvector<int> getStrongest(vector<int>& a, int k) \n {\n int n = a.size();\n sort(a.begin(),a.end());\n int m = a[(n - 1) / 2];\n | zanhd | NORMAL | 2021-08-16T11:06:32.406171+00:00 | 2021-08-16T11:06:32.406209+00:00 | 65 | false | ```\n\tvector<int> getStrongest(vector<int>& a, int k) \n {\n int n = a.size();\n sort(a.begin(),a.end());\n int m = a[(n - 1) / 2];\n \n vector<pair<int,int>> b;\n for(auto x : a)\n b.push_back({abs(x - m),x});\n sort(b.begin(),b.end(),greater<pair<int,int>>());\n \n vector<int> ans;\n for(int i = 0; i < k; i++)\n ans.push_back(b[i].second);\n return ans;\n }\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | C++ || Two Pointer Approach | c-two-pointer-approach-by-agautam992-oysd | \nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) \n {\n sort(arr.begin(),arr.end());\n int m = arr[(arr.size( | agautam992 | NORMAL | 2021-06-16T10:33:08.580724+00:00 | 2021-06-16T10:33:08.580767+00:00 | 121 | false | ```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) \n {\n sort(arr.begin(),arr.end());\n int m = arr[(arr.size()-1)/2];\n int i=0,j=arr.size()-1;\n vector<int >res;\n for(;i<=j;)\n {\n if(abs(arr[j]-m)>abs(arr[i]-m))\n {\n res.push_back(arr[j]);\n j--;\n }\n else if(abs(arr[j]-m)==abs(arr[i]-m))\n {\n if(arr[j]>arr[i])\n {\n res.push_back(arr[j]);\n j--;\n }\n else\n {\n res.push_back(arr[i]);\n i++; \n }\n }\n else\n {\n res.push_back(arr[i]);\n i++;\n }\n if(res.size()==k)\n {\n break;\n }\n }\n return res;\n }\n};\n``` | 1 | 0 | ['C', 'C++'] | 0 |
the-k-strongest-values-in-an-array | Easy to understand Java Solution. Two pointer approach. | easy-to-understand-java-solution-two-poi-7ki2 | \nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n \n int first=0;\n\t\tint last=arr.length-1;\n\t\t\n\t\tint retStrongest[]= | Dynamic_Suvam | NORMAL | 2021-06-06T19:45:51.477014+00:00 | 2021-06-06T19:45:51.477040+00:00 | 55 | false | ```\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n \n int first=0;\n\t\tint last=arr.length-1;\n\t\t\n\t\tint retStrongest[]=new int[k];\n\t\tint index=0;\n\t\t\n\t\tArrays.sort(arr);\n\t\t\n\t int median=arr[(arr.length-1)/2];\n\t \n\t \n\t \n\t for(int i=1;i<=k;i++)\n\t {\n\t\t if(Math.abs(arr[first]-median) > Math.abs(arr[last]-median) )\n\t\t {\n\t\t\t retStrongest[index]=arr[first];\n\t\t\t first++;\n\t\t\t index++;\n\t\t }\n\t\t \n\t\t else if(Math.abs(arr[first]-median) < Math.abs(arr[last]-median) )\n\t\t {\n\t\t\t retStrongest[index]=arr[last];\n\t\t\t last--;\n\t\t\t index++;\n\t\t }\n\t\t \n\t\t else if (Math.abs(arr[first]-median) == Math.abs(arr[last]-median) )\n\t\t {\n\t\t\t if(arr[first]>arr[last])\n\t\t\t {\n\t\t\t\t retStrongest[index]=arr[first];\n\t\t\t\t first++;\n\t\t\t\t index++;\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t\t retStrongest[index]=arr[last];\n\t\t\t\t last--;\n\t\t\t\t index++;\n\t\t\t }\n\t\t }\n\t\t \n\t\t \n\t\t \n\t }\n\t \n\t \n\t\t\n\t\treturn retStrongest;\n \n }\n}\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | c++ solution || easy || explained in comments | c-solution-easy-explained-in-comments-by-71ix | \nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n\t//the key logic is geting as farthest element as possible from median\n | avyakt | NORMAL | 2021-05-23T19:55:14.480244+00:00 | 2021-05-23T19:55:14.480271+00:00 | 79 | false | ```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n\t//the key logic is geting as farthest element as possible from median\n int n = arr.size();\n sort(arr.begin(), arr.end());\n int median = arr[(n-1)/2];\n vector<int> ans;\n int i = 0, j = n-1;\n while(k != 0)\n {\n if(abs(arr[i] - median) > abs(arr[j] - median))\n {\n ans.push_back(arr[i]);\n k--;\n i++;\n }\n else if(abs(arr[i] - median) <= abs(arr[j] - median))\n {\n ans.push_back(arr[j]);\n k--;\n j--;\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | C++ using nth_element | c-using-nth_element-by-chirags_30-i0bo | \nclass Solution {\npublic:\n int findMedian(vector<int> a, int n) \n { \n \n if (n % 2 == 0) \n { \n nth_element( a | chirags_30 | NORMAL | 2021-05-14T17:59:02.975123+00:00 | 2021-05-14T17:59:02.975149+00:00 | 72 | false | ```\nclass Solution {\npublic:\n int findMedian(vector<int> a, int n) \n { \n \n if (n % 2 == 0) \n { \n nth_element( a.begin() , a.begin() + (n-1)/2 , a.end() );\n \n return ( a[(n - 1) / 2] ); \n }\n else\n { \n // Applying nth_element on n/2\n nth_element( a.begin() , a.begin() + n/2 ,a.end() );\n\n return a[n / 2]; \n }\n \n} \n vector<int> getStrongest(vector<int>& arr, int k) {\n int m=findMedian(arr,arr.size());\n\n vector<pair<int, int>>V;\n for(int i:arr)\n { \n V.push_back(make_pair(i,abs(i-m)));\n \n }\n sort(V.begin(),V.end(),[](pair<int,int> a,pair<int,int> b){\n if(a.second==b.second) return a.first > b.first;\n else return a.second>b.second;\n });\n \n \n vector<int>V1;\n for(auto it : V)\n { \n V1.push_back(it.first);\n k--;\n if(k==0) break;\n }\n return V1;\n }\n};\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | using STL | using-stl-by-ranjan_1997-4zho | \nclass Solution {\npublic:\n int median = 0;\n \n vector<int> getStrongest(vector<int>& arr, int k) {\n int n = arr.size();\n sort(arr.beg | ranjan_1997 | NORMAL | 2021-05-14T17:58:35.550898+00:00 | 2021-05-14T17:58:35.550944+00:00 | 52 | false | ```\nclass Solution {\npublic:\n int median = 0;\n \n vector<int> getStrongest(vector<int>& arr, int k) {\n int n = arr.size();\n sort(arr.begin(),arr.end());\n median = arr[(n-1)/2];\n vector<pair<int,int>>pq;\n for(int i = 0;i<arr.size();i++)\n {\n pq.push_back(make_pair(arr[i],abs(arr[i]-median)));\n }\n sort(pq.begin(),pq.end(),[](pair<int,int> a,pair<int,int> b){\n if(a.second==b.second) return a.first > b.first;\n else return a.second>b.second;\n });\n vector<int>result;\n for(auto i:pq)\n {\n if(k == 0)\n break;\n result.push_back(i.first);\n k--;\n }\n return result;\n }\n};\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | Python 2 pointers | python-2-pointers-by-rehasantiago-i5ie | \nclass Solution(object):\n def getStrongest(self, arr, k):\n arr.sort()\n m = (len(arr)-1)/2\n i=0\n j=len(arr)-1\n res = | rehasantiago | NORMAL | 2021-04-11T11:53:09.681734+00:00 | 2021-04-11T11:53:09.681764+00:00 | 104 | false | ```\nclass Solution(object):\n def getStrongest(self, arr, k):\n arr.sort()\n m = (len(arr)-1)/2\n i=0\n j=len(arr)-1\n res = []\n while(k>0):\n if(abs(arr[m]-arr[i])>abs(arr[m]-arr[j])):\n res.append(arr[i])\n i+=1\n k-=1\n elif(abs(arr[m]-arr[i])<=abs(arr[m]-arr[j])):\n res.append(arr[j])\n j-=1\n k-=1\n return res\n \n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | Python 5-line solution using sort with comments | python-5-line-solution-using-sort-with-c-bux6 | class Solution:\n\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort(reverse = True) # sort the arr in descending order, this w | flyingspa | NORMAL | 2021-03-23T11:56:36.557731+00:00 | 2021-03-23T11:56:36.557770+00:00 | 153 | false | class Solution:\n\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort(reverse = True) # sort the arr in descending order, this will put the larger number at first if they have same distance to the median\n m_index = len(arr) - (len(arr)-1)//2 - 1 # median index in reversely sorted arr\n m = arr[m_index]\n arr.sort(key = lambda x: abs(x-m), reverse = True) # sorted the arr again by absolute distance \n return arr[:k] | 1 | 0 | ['Sorting', 'Python'] | 0 |
the-k-strongest-values-in-an-array | Java solution - easy to understand | java-solution-easy-to-understand-by-akir-wgfy | \nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n Arrays.sort(arr);\n int n = arr.length;\n int median = arr[(n - 1) | akiramonster | NORMAL | 2021-03-04T03:55:39.644815+00:00 | 2021-03-04T03:55:39.644883+00:00 | 104 | false | ```\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n Arrays.sort(arr);\n int n = arr.length;\n int median = arr[(n - 1) / 2];\n\n int[] res = new int[k];\n int i = 0, l = 0, r = n - 1;\n while (i < k) {\n int left = Math.abs(arr[l] - median);\n int right = Math.abs(arr[r] - median);\n if (left <= right) {\n res[i++] = arr[r--];\n } else {\n res[i++] = arr[l++];\n }\n }\n return res;\n }\n}\n```\nTime: O(nlogn)\nSpace: O(1) | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | C++ solution beats 95% speed | c-solution-beats-95-speed-by-pbabbar-3s7t | \nvector<int> getStrongest(vector<int>& arr, int k) {\n if(arr.size()<2) return arr;\n sort(arr.begin(),arr.end());\n int med=arr[(arr.size | pbabbar | NORMAL | 2021-02-26T16:24:11.805202+00:00 | 2021-02-26T16:24:11.805243+00:00 | 103 | false | ```\nvector<int> getStrongest(vector<int>& arr, int k) {\n if(arr.size()<2) return arr;\n sort(arr.begin(),arr.end());\n int med=arr[(arr.size()-1)/2];\n int left=0,right=arr.size()-1;\n vector<int> answer;\n while(k>0){\n int val_l=abs(arr[left]-med);\n int val_r=abs(arr[right]-med);\n if(val_l>val_r){\n answer.push_back(arr[left]);\n ++left;\n }\n else{\n answer.push_back(arr[right]);\n --right;\n }\n --k;\n }\n return answer;\n }\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | python - 2 lines | python-2-lines-by-mateosz-76rv | \nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n m = sorted(arr)[(len(arr)-1)//2]\n return sorted(arr, key=la | mateosz | NORMAL | 2020-12-12T12:14:50.772017+00:00 | 2020-12-12T12:14:50.772045+00:00 | 87 | false | ```\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n m = sorted(arr)[(len(arr)-1)//2]\n return sorted(arr, key=lambda x: (abs(x-m), x))[-k:]\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | Python with multiple IF ELSE | Faster than 72% | python-with-multiple-if-else-faster-than-xnsy | \nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n\n if len(arr) == 1: return arr\n\n resul | annnguyen | NORMAL | 2020-10-25T10:35:41.222904+00:00 | 2020-10-25T10:35:41.222935+00:00 | 69 | false | ```\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n\n if len(arr) == 1: return arr\n\n result_ = []\n num = 0\n i = 0\n j = len(arr) - 1\n m = arr[int((len(arr)-1)/2)]\n new_arr = [abs(x - m) for x in arr]\n\n while i < len(arr) and j > 0 and num < k :\n if new_arr[i] > new_arr[j]:\n result_.append(arr[i])\n i += 1\n elif new_arr[i] < new_arr[j]:\n result_.append(arr[j])\n j -= 1\n else:\n if arr[i] > arr[j]:\n result_.append(arr[i])\n i += 1\n else:\n result_.append(arr[j])\n j -= 1\n num = int(len(result_))\n return result_\n\t``` | 1 | 0 | [] | 1 |
the-k-strongest-values-in-an-array | python O(nlogn), sort | python-onlogn-sort-by-landsurveyork-iy4a | \nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n n = len(arr)\n m = (n - 1) // 2\n sort_arr = sorted(a | landsurveyork | NORMAL | 2020-10-25T03:03:41.138712+00:00 | 2020-10-25T03:03:41.138744+00:00 | 149 | false | ```\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n n = len(arr)\n m = (n - 1) // 2\n sort_arr = sorted(arr)\n med = sort_arr[m]\n \n A = {}\n for x in arr:\n dist = abs(x - med)\n if dist in A:\n A[dist].append(x)\n else:\n A[dist] = [x]\n \n res = []\n count = 0 \n for dist in sorted(A.keys(), reverse = True):\n val = sorted(A[dist], reverse=True)\n for x in val:\n if count < k:\n res.append(x)\n count += 1\n return res\n \n \n\n\n``` | 1 | 0 | ['Python'] | 0 |
the-k-strongest-values-in-an-array | Java - better than 92%, Clean solution | java-better-than-92-clean-solution-by-do-cb5l | \npublic int[] getStrongest(int[] arr, int k) {\n int n = arr.length;\n Arrays.sort(arr);\n int median = arr[((n - 1) / 2)];\n \n | dorelb72 | NORMAL | 2020-09-21T16:23:41.573717+00:00 | 2020-09-21T16:23:41.573752+00:00 | 370 | false | ```\npublic int[] getStrongest(int[] arr, int k) {\n int n = arr.length;\n Arrays.sort(arr);\n int median = arr[((n - 1) / 2)];\n \n int[] output = new int[k];\n int index = 0;\n int l = 0, r = n - 1;\n \n while (index < k) {\n int dist1 = Math.abs(arr[l] - median);\n int dist2 = Math.abs(arr[r] - median);\n \n if (dist1 > dist2) \n output[index++] = arr[l++];\n else\n output[index++] = arr[r--];\n }\n \n return output;\n }\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | Simple Python Solution | simple-python-solution-by-whissely-x80s | \nclass Solution:\n # Time: O(n*log(n))\n # Space: O(n)\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n med | whissely | NORMAL | 2020-09-15T04:55:40.338575+00:00 | 2020-09-15T04:55:40.338631+00:00 | 170 | false | ```\nclass Solution:\n # Time: O(n*log(n))\n # Space: O(n)\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n median = arr[(len(arr) - 1)//2]\n res, i, j = [], 0, len(arr) - 1\n while i <= j and k:\n if abs(arr[i] - median) > abs(arr[j] - median):\n res.append(arr[i])\n i += 1\n else:\n res.append(arr[j])\n j -= 1 \n k -= 1\n return res\n``` | 1 | 0 | ['Sorting', 'Python'] | 0 |
the-k-strongest-values-in-an-array | python3 2 pointers | python3-2-pointers-by-harshalkpd93-xiqo | ```\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n n = len(arr)\n m = arr[(n-1)//2]\n | harshalkpd93 | NORMAL | 2020-09-06T01:35:48.961970+00:00 | 2020-09-06T01:35:48.962029+00:00 | 53 | false | ```\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n n = len(arr)\n m = arr[(n-1)//2]\n strong = []\n # for i in range(len(arr)):\n i,j = 0, len(arr)-1\n while i<=j:\n if abs(arr[i]-m) <= abs(arr[j]-m):\n strong.append(arr[j])\n j -= 1\n else:\n strong.append(arr[i])\n i += 1\n return(strong[:k]) | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | C++ Simple Sort Solution | c-simple-sort-solution-by-rom111-qyzs | \nclass Solution {\npublic:\n static int m;\n static bool compare(int a,int b){\n if(abs(a-m)>abs(b-m)){\n return true;\n }else i | rom111 | NORMAL | 2020-09-01T12:18:24.324864+00:00 | 2020-09-01T12:18:24.324916+00:00 | 127 | false | ```\nclass Solution {\npublic:\n static int m;\n static bool compare(int a,int b){\n if(abs(a-m)>abs(b-m)){\n return true;\n }else if(abs(a-m)==abs(b-m)){\n if(a>b){\n return true;\n }\n }\n return 0;\n }\n vector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(),arr.end());\n int n=arr.size();\n m=arr[(n-1)/2];\n sort(arr.begin(),arr.end(),compare);\n vector<int>ans;\n for(int i=0;i<k;i++){\n ans.push_back(arr[i]);\n }\n return ans;\n }\n};\nint Solution :: m;\n``` | 1 | 0 | [] | 1 |
the-k-strongest-values-in-an-array | [C++] simple sort function using comparator | c-simple-sort-function-using-comparator-ravyg | c++\nint m;\nbool comp(int a,int b){\n int a1=abs(a-m),a2=abs(b-m);\n if(a1>a2)return true;\n else if(a2>a1)return false;\n return a>b;\n}\nclass So | suhailakhtar039 | NORMAL | 2020-09-01T07:56:16.313717+00:00 | 2020-09-01T07:56:16.313766+00:00 | 134 | false | ```c++\nint m;\nbool comp(int a,int b){\n int a1=abs(a-m),a2=abs(b-m);\n if(a1>a2)return true;\n else if(a2>a1)return false;\n return a>b;\n}\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(),arr.end());\n int n=arr.size();\n m=arr[(n-1)/2];\n sort(arr.begin(),arr.end(),comp);\n return vector<int>(arr.begin(),arr.begin()+k);\n }\n};\n``` | 1 | 0 | ['C', 'Sorting', 'C++'] | 0 |
the-k-strongest-values-in-an-array | O(Nlog(N)) JAVA solution! | onlogn-java-solution-by-lcq_dev-vbi6 | \nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n Arrays.sort(arr);\n int[] res = new int[k];\n int[] nums = | lcq_dev | NORMAL | 2020-07-25T21:36:09.540873+00:00 | 2020-07-25T21:36:09.540907+00:00 | 120 | false | ```\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n Arrays.sort(arr);\n int[] res = new int[k];\n int[] nums = arr;\n int mid_index = (nums.length-1)/2;\n int median = arr[mid_index];\n \n int i = 0;\n int j = nums.length-1;\n \n\n int count = 0;\n while(i<=j){\n int left = nums[i];\n int right = nums[j];\n \n if(Math.abs((long)left-median)>Math.abs((long)right-median)){\n count++;\n res[count-1] = left;\n i++;\n }else{\n count++;\n res[count-1] = right;\n j--;\n }\n if(count == k){\n break;\n }\n }\n \n \n \n return res;\n }\n}\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | Java TreeMap | java-treemap-by-mayankbansal-gnjy | ```\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n int[] c=new int[arr.length];\n for(int i=0;i<arr.length;i++){\n | mayankbansal | NORMAL | 2020-07-20T06:05:59.777612+00:00 | 2020-07-20T06:05:59.777663+00:00 | 73 | false | ```\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n int[] c=new int[arr.length];\n for(int i=0;i<arr.length;i++){\n c[i]=arr[i];\n }\n Arrays.sort(arr);\n int med=arr[(arr.length-1)/2];\n TreeMap<Integer,ArrayList<Integer>> map=new TreeMap<>(); \n for(int i=0;i<arr.length;i++){\n if(!map.containsKey(Math.abs(c[i]-med))){\n map.put(Math.abs(c[i]-med),new ArrayList<>());\n }\n map.get(Math.abs(c[i]-med)).add(c[i]);\n }\n // System.out.println(map);\n int[] a=new int[k];\n int i=0;\n while(k>0){\n int d=map.lastKey(); \n Collections.sort(map.get(d));\n // System.out.println(d);\n for(int p=map.get(d).size()-1;p>=0&&k>0;p--){\n a[i]=map.get(d).get(p);\n i++;\n k--;\n }\n map.remove(d);\n }\n return a;\n }\n} | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | Python3 93.52% (1052 ms)/100.00% (27.4 MB) | python3-9352-1052-ms10000-274-mb-by-numi-egf2 | \nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n median = arr[len(arr) // 2] if len(arr) % 2 els | numiek_p | NORMAL | 2020-06-23T12:28:07.469043+00:00 | 2020-06-23T12:28:07.469091+00:00 | 99 | false | ```\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n median = arr[len(arr) // 2] if len(arr) % 2 else arr[len(arr) // 2 - 1]\n left = 0\n right = len(arr) - 1\n ret = []\n \n \n while (len(ret) != k):\n left_value = abs(arr[left] - median)\n right_value = abs(arr[right] - median)\n \n \n if (right_value >= left_value):\n ret.append(arr[right])\n right -= 1\n else:\n ret.append(arr[left])\n left += 1\n \n return ret \n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | two pointers | two-pointers-by-fengyindiehun-z6rp | \nvector<int> getStrongest(vector<int>& arr, int k) {\n vector<int> ans;\n int n = arr.size();\n sort(arr.begin(), arr.end());\n int m_idx = (n - 1) | fengyindiehun | NORMAL | 2020-06-23T10:50:27.591151+00:00 | 2020-06-23T10:50:27.591196+00:00 | 67 | false | ```\nvector<int> getStrongest(vector<int>& arr, int k) {\n vector<int> ans;\n int n = arr.size();\n sort(arr.begin(), arr.end());\n int m_idx = (n - 1) >> 1;\n int m = arr[m_idx];\n int i = 0;\n int j = n-1;\n while (k--) {\n if (m - arr[i] < arr[j] - m) {\n ans.push_back(arr[j]);\n --j;\n } else if (m - arr[i] > arr[j] - m) {\n ans.push_back(arr[i]);\n ++i;\n } else {\n ans.push_back(arr[j]);\n --j;\n }\n }\n return ans;\n}\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | C++ O(N) solution 99% with explanation | c-on-solution-99-with-explanation-by-guc-2sbd | Because we need kth greatest elements, in no particular order, we can simply use selection algorithms (such as quickselect, implemented as nth_element) to solve | guccigang | NORMAL | 2020-06-13T01:18:25.497034+00:00 | 2020-06-13T01:19:18.568503+00:00 | 180 | false | Because we need `k`th greatest elements, in no particular order, we can simply use selection algorithms (such as quickselect, implemented as `nth_element`) to solve the problem in linear time. We first calculate the median using a selection algorithm which is `O(N)`. Then, we apply the selection algorithm again to find the element at `k`, using the given criteria as comparison. As a side effect of this selection algorithm, all numbers will be sorted according to the criteria, such that those with indices less than `k` will have greater "power". This is again `O(N)`. Then, we can simply take the array from `0` to `k` to get the solution, which is also `O(N)`. Thus, the overall run-time of this algorithm is `O(N)`. \n\n```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n int size{(int)arr.size()}, m;\n nth_element(arr.begin(), arr.begin()+((size-1)>>1), arr.end());\n m = arr[(size-1)>>1];\n nth_element(arr.begin(), arr.begin()+k, arr.end(), [&](const auto& a, const auto& b){return abs(a-m) == abs(b-m) ? a > b : abs(a-m) > abs(b-m);});\n return std::vector<int>(arr.begin(), arr.begin()+k);\n }\n};\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | Python3, simple solution O(nlogn) for sorting + O(k) for finding the result | python3-simple-solution-onlogn-for-sorti-iidp | \ndef getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr = sorted(arr)\n medianIndex = (len(arr) - 1) // 2\n median = arr[media | sraghav2 | NORMAL | 2020-06-10T09:22:18.680681+00:00 | 2020-06-10T09:22:18.680709+00:00 | 63 | false | ```\ndef getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr = sorted(arr)\n medianIndex = (len(arr) - 1) // 2\n median = arr[medianIndex]\n \n result = []\n backPointer = -1\n frontPointer = 0\n for i in range(k):\n if(abs(arr[backPointer] - median) >= abs(arr[frontPointer] - median)):\n result.append(arr[backPointer])\n backPointer -= 1\n elif(abs(arr[backPointer] - median) < abs(arr[frontPointer] - median)):\n result.append(arr[frontPointer])\n frontPointer += 1\n \n return result\n``` | 1 | 0 | [] | 1 |
the-k-strongest-values-in-an-array | c++ solution using custom sorting. | c-solution-using-custom-sorting-by-rajuj-s73c | \nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n \n int len = arr.size();\n sort(arr.begin(), arr.end | rajujnvgupta | NORMAL | 2020-06-09T12:48:46.583635+00:00 | 2020-06-09T12:49:13.810333+00:00 | 88 | false | ```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n \n int len = arr.size();\n sort(arr.begin(), arr.end()); // sort to get median\n int idx = (len-1)/2;\n int median = arr[idx];\n \n auto cmp = [&](int a, int b){ // lambda function\n if(abs(a-median) == abs(b-median)){\n return a > b;\n }else{\n return abs(a-median) > abs(b-median);\n }\n };\n \n sort(arr.begin(), arr.end(), cmp);\n return {arr.begin(), arr.begin()+k}; //list of the strongest k\n }\n};\n``` | 1 | 1 | ['C', 'Sorting'] | 0 |
the-k-strongest-values-in-an-array | How random quickselect should be implemented and why | how-random-quickselect-should-be-impleme-fi3i | Lots of folks without the benefit of nth_element from STL may be wondering how one could implement random quickselect by hand. Random quickselect is very easy t | algomelon | NORMAL | 2020-06-09T02:38:16.783372+00:00 | 2020-06-09T02:53:55.735246+00:00 | 186 | false | Lots of folks without the benefit of nth_element from STL may be wondering how one could implement random quickselect by hand. Random quickselect is very easy to implement once you understand the subtleties but it can behave badly on some inputs. (There is a far more complicated worst-case linear-time selection algorithm but it\'s difficult to implement correctly in an interview in my humble opinion). In any case I\'ve documented my thought process here and explained my understanding of the subtleties with random quickselect, due to the differences of the partitioning algorithm one may choose, (Lomuto or Hoare partitioning); since the go-to partitioning scheme, Lomuto partititoning, will TLE on large array with all same numbers.\n\n```\nclass Solution(object):\n def getStrongest(self, arr, k):\n """\n :type arr: List[int]\n :type k: int\n :rtype: List[int]\n """\n def lomuto_partitioning(first, last):\n # Pivot will be some randomly element selected in the range [first, last]\n # and placed to the end of the array\n p = random.randint(first, last)\n pivot = arr[p]\n arr[last], arr[p] = arr[p], arr[last]\n \n # Now we will go through elements in the range [first, last - 1] and place\n # all those greater than pivot to the right of i, and those less or equal to pivot\n # to indexes <= i.\n \n # Invariant: all elements whose indexes are <= i should be on the left of the pivot\n i = first - 1\n for j in xrange(first, last):\n if arr[j] > pivot:\n # keep marching j forward until we find an element <= pivot\n continue\n # Found one, now a[j] <= pivot so it should be at an index <= i. So make room\n # for it by advancing i and then placing it there\n i += 1\n arr[i], arr[j] = arr[j], arr[i]\n arr[i+1], arr[last] = arr[last], arr[i+1]\n return i+1\n \n def hoare_partitioning(A, first, last, less_than):\n p = random.randint(first, last)\n pivot = A[p]\n A[first], A[p] = A[p], A[first]\n i, j = first - 1, last + 1\n while True:\n i += 1\n while less_than(A[i], pivot):\n i += 1\n j -= 1\n while less_than(pivot, A[j]):\n j -= 1\n if i >= j:\n # Invariant: all elements in [first, j] are <= all elements in [j + 1, last]\n return j\n A[i], A[j] = A[j], A[i]\n \n def quickselect(A, first, last, i, less_than):\n if first == last:\n return first\n # lomuto partitioning will not do well against input with the same numbers.\n # (It has O(N^2) behavior in that case)\n #p = lomuto_partitioning(first, last)\n # Whereas hoare partitioning will always split non-trivially regardless of the input\n p = hoare_partitioning(A, first, last, less_than)\n # Though be aware since hoare partitioning only guarantees that elements in \n # [first, p] <= [p + 1, last], we cannot follow the standard random-select algorithm \n # where we do:\n \'\'\'\n if first + i == p:\n # The element at index first + i is not guaranteed to be the max element amongst\n\t\t\t\t # those in the range [first, p]\n # return p\n \'\'\'\n # Instead all we can say is if first + i is at or below index p, we can discard\n # the right, [p + 1, last], partition\n if first + i <= p:\n return quickselect(A, first, p, i, less_than)\n # Otherwise we can discard the left, [first, p], partition\n return quickselect(A, p + 1, last, i - (p - first + 1), less_than)\n \n n = len(arr)\n # Use quickselect to find the index of the median. This will have\n # expected runtime of O(n)\n median_idx = quickselect(arr, 0, n - 1, (n - 1) / 2, lambda x, y: x < y)\n median = arr[median_idx]\n \n # Use quickselect again to find the index of the k-th (since quickselect() as we\'ve\n # implemented is 0-indexed, it\'s k-1 th) strongest value. Again it would run\n # in O(n) time\n arr_with_strength = [None] * len(arr)\n for i in xrange(n):\n arr_with_strength[i] = (abs(arr[i] - median), arr[i])\n less_than_comparator = lambda x, y: x[0] > y[0] or x[0] == y[0] and x[1] > y[1]\n p = quickselect(arr_with_strength, 0, n - 1, k-1, less_than_comparator)\n # Due to how quickselect partitions elements like quicksort, all the elements in the \n\t\t# partition [0, p] should be <= all elements in partition [p + 1, n - 1] where\n\t\t# the ordering defined by the less_than_comparator. (Again this is an invariant \n # property of Hoare partioning)\n result = []\n for i in range(0, p + 1):\n result.append(arr_with_strength[i][1])\n \n # Total runtime is O(n) + O(n) + k => O(n), k is some small constant\n return result\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | Java Solution - Quick Select | java-solution-quick-select-by-mycafebabe-ipmk | \nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n int n = arr.length;\n int median = findKthLargest(arr, 0, n - 1, n / 2 + | mycafebabe | NORMAL | 2020-06-08T06:53:58.448113+00:00 | 2020-06-08T06:53:58.448162+00:00 | 100 | false | ```\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n int n = arr.length;\n int median = findKthLargest(arr, 0, n - 1, n / 2 + 1);\n int idx = helper(arr, 0, n - 1, k, median);\n int[] ans = new int[k];\n for (int i = 0; i < k; i++) {\n ans[i] = arr[i];\n }\n return ans;\n }\n \n public int findKthLargest(int[] arr, int start, int end, int k) {\n if (start >= end) {\n return arr[end];\n }\n int left = start;\n int right = end;\n int pivot = arr[end];\n while (left <= right) {\n while (left <= right && arr[left] > pivot) {\n left++;\n }\n while (left <= right && arr[right] < pivot) {\n right--;\n }\n if (left <= right) {\n int temp = arr[left];\n arr[left] = arr[right];\n arr[right] = temp;\n left++;\n right--;\n }\n }\n if (start + (k - 1) <= right) {\n return findKthLargest(arr, start, right, k);\n } else if (start + (k - 1) >= left) {\n return findKthLargest(arr, left, end, k - (left - start));\n }\n return arr[right + 1];\n }\n \n public int helper(int[] arr, int start, int end, int k, int median) {\n if (start >= end) {\n return end;\n }\n int left = start; \n int right = end;\n int pivot = getStrength(arr[end], median);\n while (left <= right) {\n while (left <= right && isStronger(getStrength(arr[left], median), pivot, arr[left], arr[end])) {\n left++;\n }\n while (left <= right && isWeaker(getStrength(arr[right], median), pivot, arr[right], arr[end])) {\n right--;\n }\n if (left <= right) {\n int temp = arr[left];\n arr[left] = arr[right];\n arr[right] = temp;\n left++;\n right--;\n }\n }\n if (start + (k - 1) <= right) {\n return helper(arr, start, right, k, median);\n } else if (start + (k - 1) >= left) {\n return helper(arr, left, end, k - (left - start), median);\n } else {\n return right + 1;\n }\n }\n \n public int getStrength(int n, int median) {\n return Math.abs(n - median);\n }\n \n public boolean isStronger(int s1, int s2, int num, int end) {\n return s1 == s2 ? num > end : s1 > s2;\n }\n \n public boolean isWeaker(int s1, int s2, int num, int end) {\n return s1 == s2 ? num < end : s1 < s2;\n }\n}\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | C++ [Easy] | c-easy-by-pal_96-47j1 | \nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n if(arr.size() == 1) return arr;\n sort(arr.begin(), arr.end | pal_96 | NORMAL | 2020-06-08T02:56:01.175788+00:00 | 2020-06-08T02:56:01.175825+00:00 | 38 | false | ```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n if(arr.size() == 1) return arr;\n sort(arr.begin(), arr.end());\n vector<int> ans;\n int len = arr.size();\n int medPos = (len-1)/2;\n int med = arr[medPos];\n vector< pair<int, int>> m;\n for(int i = 0; i < len; i++)\n m.push_back(make_pair(abs(arr[i] - med), arr[i]));\n sort(m.begin(), m.end(), [](const pair<int,int> &a, const pair<int,int> &b) {\n if(a.first == b.first)\n return a.second > b.second;\n return (a.first > b.first);\n });\n int i = 0;\n for(auto it = m.begin(); i < k; it++, i++)\n ans.push_back(it->second);\n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | Short Python Time O(nlogn) | short-python-time-onlogn-by-yuchen_peng-pzp8 | \nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n if k == 0 or not arr:\n return []\n \n n = | yuchen_peng | NORMAL | 2020-06-07T15:05:06.859840+00:00 | 2020-06-07T15:05:06.859889+00:00 | 47 | false | ```\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n if k == 0 or not arr:\n return []\n \n n = len(arr)\n arr.sort()\n median = arr[(n - 1) // 2]\n \n abs_arr = sorted(arr, key=lambda x: (abs(x - median), x), reverse=True)\n \n return abs_arr[:k]\n \n``` | 1 | 0 | [] | 2 |
the-k-strongest-values-in-an-array | C++ code : using a MULTIMAP. | c-code-using-a-multimap-by-xxdil-ya1m | \nclass Solution {\npublic: \n vector<int> getStrongest(vector<int>& arr, int k) \n {\n sort(arr.begin(), arr.end());\n int n = arr.size( | xxdil | NORMAL | 2020-06-07T08:48:54.306746+00:00 | 2020-07-14T11:32:39.749225+00:00 | 50 | false | ```\nclass Solution {\npublic: \n vector<int> getStrongest(vector<int>& arr, int k) \n {\n sort(arr.begin(), arr.end());\n int n = arr.size();\n int m = (n - 1) / 2;\n \n multimap<int, int> M;\n int c=0;\n for(int i : arr)\n {\n M.insert({abs(i-arr[m]), c});\n c++;\n }\n \n vector<int> ans;\n for (auto i = M.rbegin(); i != M.rend(); ++i)\n {\n if(k == 0) break;\n ans.push_back(arr[i->second]);\n k--;\n }\n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | Swift Two Pointers | swift-two-pointers-by-achoas-0qqp | \nclass Solution { \n func getStrongest(_ arr: [Int], _ k: Int) -> [Int] {\n let sorted = arr.sorted()\n let mIndex = (arr.count - 1) / 2\n | achoas | NORMAL | 2020-06-07T08:48:10.358030+00:00 | 2020-06-07T08:48:41.749876+00:00 | 70 | false | ```\nclass Solution { \n func getStrongest(_ arr: [Int], _ k: Int) -> [Int] {\n let sorted = arr.sorted()\n let mIndex = (arr.count - 1) / 2\n let m = sorted[mIndex]\n var p1 = 0\n var p2 = arr.count - 1\n \n var rest = [Int]()\n while rest.count < k {\n let p1Val = abs(sorted[p1] - m)\n let p2Val = abs(sorted[p2] - m)\n if p1Val > p2Val {\n rest.append(sorted[p1])\n p1 += 1\n } else {\n rest.append(sorted[p2])\n p2 -= 1\n }\n }\n return rest\n }\n}\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | lazy java solution | lazy-java-solution-by-trustno1-qo34 | ```\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n Arrays.sort(arr);\n int n = arr.length, mid = arr[(n - 1) / 2];\n | trustno1 | NORMAL | 2020-06-07T07:46:39.698062+00:00 | 2020-06-07T07:46:39.698101+00:00 | 91 | false | ```\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n Arrays.sort(arr);\n int n = arr.length, mid = arr[(n - 1) / 2];\n int[][] tmp = new int[n][2];\n for(int i = 0; i < n; i++)\n tmp[i] = new int[]{Math.abs(arr[i] - mid), i};\n Arrays.sort(tmp, (a, b) -> b[0] == a[0] ? arr[b[1]] - arr[a[1]] : b[0] - a[0]);\n\n int[] res = new int[k];\n for(int i = 0; i < k; i++)\n res[i] = arr[tmp[i][1]];\n return res;\n }\n} | 1 | 0 | [] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.