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
largest-local-values-in-a-matrix
Simpler || Faster || Fully Explained || Beats 100 % C#
simpler-faster-fully-explained-beats-100-c4o1
Intuition\n Describe your first thoughts on how to solve this problem. \nSimply use for loops to iterate over the matrix, with limit as n-2 for outer loops and
priyasmb24
NORMAL
2024-05-12T04:04:38.695780+00:00
2024-05-12T04:06:57.594830+00:00
1,064
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSimply use for loops to iterate over the matrix, with limit as n-2 for outer loops and i+3, j+3 for inner loops\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInput: grid = [[9,9,8,1],\n [5,6,2,6],\n [8,2,6,4],\n [6,2,2,2]]\n\n(i) i) i = 0, j = 0;\n res[0] =new int[n-2] = new int[2] = [,]\n\n (aa) ii =0, jj = 0 , ii & jj < 3\n res[0][0] = Math.Max(0,9) = 9\n (ab) ii = 0, jj = 1 , ii & jj <3\n res[0][0] = Math.Max(9,9) = 9\n (ac) ii = 0, jj = 2 , ii & jj <3\n res[0][0] = Math.Max(9,8) = 9\n \n (ba) ii =1, jj = 0 , ii & jj < 3\n res[0][0] = Math.Max(9,5) = 9\n (bb) ii = 1, jj = 1 , ii & jj <3\n res[0][0] = Math.Max(9,6) = 9\n (bc) ii = 1, jj = 2 , ii & jj <3\n res[0][0] = Math.Max(9,2) = 9\n\n (ca) ii =2, jj = 0 , ii & jj < 3\n res[0][0] = Math.Max(9,8) = 9\n (cb) ii = 2, jj = 1 , ii & jj <3\n res[0][0] = Math.Max(9,2) = 9\n (cc) ii = 2, jj = 2 , ii & jj <3\n res[0][0] = Math.Max(9,6) = 9 \n\nFinally res[0][0] = 9\n\nNext\n (i) ii) i = 0, j = 1\n\n (aa) ii = 0, jj = 1 , ii <3 & jj < 4\n res[0][1] = Math.Max(0,9) = 9\n (ab) ii = 0, jj = 2 , ii<3 & jj <4\n res[0][1] = Math.Max(9,8) = 9\n (ac) ii = 0, jj = 3 , ii<3 & jj <4\n res[0][1] = Math.Max(9,1) = 9\n \n (ba) ii = 1, jj = 1 , ii <3 & jj < 4\n res[0][1] = Math.Max(9,6) = 9\n (bb) ii = 1, jj = 2 , ii<3 & jj <4\n res[0][1] = Math.Max(9,2) = 9\n (bc) ii = 1, jj = 3 , ii<3 & jj <4\n res[0][1] = Math.Max(9,6) = 9\n \n (ca) ii = 2, jj = 1 , ii <3 & jj < 4\n res[0][1] = Math.Max(9,2) = 9\n (cb) ii = 2, jj = 2 , ii<3 & jj <4\n res[0][1] = Math.Max(9,6) = 9\n (cc) ii = 2, jj = 3 , ii<3 & jj <4\n res[0][1] = Math.Max(9,4) = 9\n \n\nFinally res[0][1] = 9\n\nsimilary for other values of res array will also be calculated.\n\n \n\nOutput: [[9,9],[8,6]]\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C# []\npublic class Solution {\n public int[][] LargestLocal(int[][] grid) {\n int n = grid.Length;\n var res = new int[n-2][];\n for(int i = 0; i<n-2;i++){\n res[i] = new int[n-2];\n for(int j = 0; j<n-2; j++){\n for(int ii = i; ii<i+3;ii++){\n for(int jj = j; jj<j+3;jj++){\n res[i][j] = Math.Max(res[i][j],grid[ii][jj]);\n }\n }\n }\n }\n return res;\n }\n}\n```\n```Java []\npublic class Solution {\n public int[][] largestLocal(int[][] grid) {\n int n = grid.length;\n int[][] res = new int[n - 2][];\n\n for (int i = 0; i < n - 2; i++) {\n res[i] = new int[n - 2];\n for (int j = 0; j < n - 2; j++) {\n for (int ii = i; ii < i + 3; ii++) {\n for (int jj = j; jj < j + 3; jj++) {\n res[i][j] = Math.max(res[i][j], grid[ii][jj]);\n }\n }\n }\n }\n return res;\n }\n}\n```\n```Python []\nclass Solution(object):\n def largestLocal(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: List[List[int]]\n """\n n = len(grid)\n res = [[0] * (n - 2) for _ in range(n - 2)]\n\n for i in range(n - 2):\n for j in range(n - 2):\n max_val = float(\'-inf\')\n for ii in range(i, i + 3):\n for jj in range(j, j + 3):\n max_val = max(max_val, grid[ii][jj])\n res[i][j] = max_val\n\n return res\n\n```
2
0
['Array', 'Matrix', 'Python', 'Java', 'C#']
0
largest-local-values-in-a-matrix
Easy C++ Constant Space Solution | Beats 100 πŸ’―βœ… | Max Pooling
easy-c-constant-space-solution-beats-100-mhh7
Intuition\n Describe your first thoughts on how to solve this problem. \n- We start by traversing each cell in the grid.\n- For each cell, we consider its surro
shobhitkushwaha1406
NORMAL
2024-05-12T02:45:36.817928+00:00
2024-05-12T02:45:36.817954+00:00
258
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- We start by traversing each cell in the grid.\n- For each cell, we consider its surrounding cells (including diagonals) to find the maximum value.\n- Updating each cell\'s value in-place ensures that we maintain the largest local value for each cell.\n- Finally, we return the modified grid containing the largest local values for each cell.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Iterate through each cell of the grid.\n2. For each cell, iterate through its neighboring cells (up, down, left, right, and diagonals).\n3. Update the current cell\'s value to the maximum value among itself and its neighbors.\n4. Repeat steps 1-3 for all cells in the grid.\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n vector<vector<int>> largestLocal(vector<vector<int>>& grid) {\n const int n=grid.size();\n for(int i=1; i<n-1; i++){ \n for(int j=1; j<n-1; j++){\n for(int r=i-1; r<=i+1; r++)\n for( int c=j-1; c<=j+1; c++)\n grid[i-1][j-1]=max(grid[i-1][j-1], grid[r][c]);\n }\n grid[i-1].resize(n-2);\n }\n grid.resize(n-2);\n return grid;\n }\n};\n```
2
0
['Array', 'Math', 'Matrix', 'C++']
2
largest-local-values-in-a-matrix
Fastest execution || beats 100% users with JAVA || C++ || PYTHON3 || TYPESCRIPT
fastest-execution-beats-100-users-with-j-lm2o
Approach\nIterate Through Grid\n\n# Complexity\n- Time complexity: O(n^2)\n\n- Space complexity: O(n^2)\n\n# Explanation\n1. Method Signature:\n\n- We start wit
SanketSawant18
NORMAL
2024-05-12T00:19:05.956845+00:00
2024-05-12T00:19:05.956883+00:00
595
false
# Approach\nIterate Through Grid\n\n# Complexity\n- Time complexity: O(n^2)\n\n- Space complexity: O(n^2)\n\n# Explanation\n1. **Method Signature:**\n\n- We start with the Solution class containing the largestLocal method. The method takes a 2D integer array grid as input and returns a 2D integer array as the result.\n\n2. **Initialization:**\n\n- We initialize variables n to store the size of the input grid and result as a 2D array to store the resulting matrix.\n\n3. **Iterating Over Submatrices:**\n\n- We use two nested loops to iterate through the input grid, considering each cell as the top-left corner of a 3x3 submatrix. Since we are generating a matrix of size (n - 2) x (n - 2), we iterate up to n - 2.\n\n4. **Finding Maximum Value:**\n\n- For each cell (i, j), we initialize maxVal to the minimum integer value. Then, we iterate over the corresponding 3x3 submatrix using nested loops.\n- Within the nested loops, we update maxVal to store the maximum value found in the submatrix using the Math.max method.\n\n5. **Storing Maximum Value:**\n\n- After finding the maximum value within the submatrix, we store it in the corresponding position of the result matrix at index (i, j).\n6. **Returning Result:**\n\n- After iterating through all cells, we have computed the maximum values for each contiguous 3x3 submatrix in the input grid. We return the result matrix containing these maximum values.\n\n---\n\n\n```java []\nimport java.util.*;\n\nclass Solution {\n public int[][] largestLocal(int[][] grid) {\n int n = grid.length;\n int[][] result = new int[n - 2][n - 2];\n \n for (int i = 0; i < n - 2; i++) {\n for (int j = 0; j < n - 2; j++) {\n int maxVal = Integer.MIN_VALUE;\n // Iterate over the 3x3 submatrix\n for (int r = i; r < i + 3; r++) {\n for (int c = j; c < j + 3; c++) {\n maxVal = Math.max(maxVal, grid[r][c]);\n }\n }\n result[i][j] = maxVal;\n }\n }\n \n return result;\n }\n}\n\n```\n```python3 []\nclass Solution:\n def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:\n length = len(grid)\n res =[]\n for i in range(length-2):\n temp=[]\n for j in range(length-2):\n maxi = max(grid[i][j],grid[i][j+1],grid[i][j+2],\n grid[i+1][j],grid[i+1][j+1],grid[i+1][j+2],\n grid[i+2][j],grid[i+2][j+1],grid[i+2][j+2])\n temp.append(maxi)\n res.append(temp)\n return res\n```\n```C++ []\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nclass Solution {\npublic:\n vector<vector<int>> largestLocal(vector<vector<int>>& grid) {\n int n = grid.size();\n vector<vector<int>> result(n - 2, vector<int>(n - 2));\n\n for (int i = 0; i < n - 2; i++) {\n for (int j = 0; j < n - 2; j++) {\n int maxVal = numeric_limits<int>::min();\n for (int r = i; r < i + 3; r++) {\n for (int c = j; c < j + 3; c++) {\n maxVal = max(maxVal, grid[r][c]);\n }\n }\n result[i][j] = maxVal;\n }\n }\n\n return result;\n }\n};\n\n```\n```Typescript []\nfunction largestLocal(grid: number[][]): number[][] {\n const n: number = grid.length;\n const result: number[][] = [];\n\n for (let i = 0; i < n - 2; i++) {\n result[i] = [];\n for (let j = 0; j < n - 2; j++) {\n let maxVal: number = Number.MIN_SAFE_INTEGER;\n for (let r = i; r < i + 3; r++) {\n for (let c = j; c < j + 3; c++) {\n maxVal = Math.max(maxVal, grid[r][c]);\n }\n }\n result[i].push(maxVal);\n }\n }\n\n return result;\n};\n```\n
2
0
['Array', 'Matrix', 'C++', 'Java', 'TypeScript', 'Python3']
1
largest-local-values-in-a-matrix
Fast and easy to understand solution - 2ms
fast-and-easy-to-understand-solution-2ms-tfj7
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. Calculates the size of the resulting box (excluding outer edges).\n2.
virhansda2302
NORMAL
2024-01-21T11:39:27.547888+00:00
2024-01-21T11:39:27.547952+00:00
287
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Calculates the size of the resulting box (excluding outer edges).\n2. Creates a new 2D array box to store the largest local values.\n3. Iterates through each cell of the box array:\n * Calls maxValue to find the largest value within a 3x3 sub-grid around the current cell.\n * Stores the returned maximum value in the corresponding cell of box.\n4. Returns the box array containing the largest local values.\n\n\n# Complexity\n- Time complexity:O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[][] largestLocal(int[][] grid) {\n int size = grid.length-2;\n int[][] box = new int[size][size];\n\n for(int r=0; r<size; r++){\n for(int c=0;c<size; c++){\n box[r][c]= maxValue(grid,r,c);\n }\n }\n return box;\n }\n\n public int maxValue(int[][] grid, int i, int j){\n\n int max = 0;\n for(int row=i; row<i+3; row++){\n for(int col=j;col<j+3; col++){\n max = Math.max(grid[row][col], max); \n }\n }\n return max;\n }\n}\n```
2
0
['Array', 'Math', 'Matrix', 'Java']
1
largest-local-values-in-a-matrix
The Only C Solution
the-only-c-solution-by-nitianvineet-4vi3
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
nitianvineet
NORMAL
2023-05-08T18:11:02.715498+00:00
2023-05-08T18:11:02.715534+00:00
85
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```\n/**\n * Return an array of arrays of size *returnSize.\n * The sizes of the arrays are returned as *returnColumnSizes array.\n * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().\n */\nint** largestLocal(int** grid, int gridSize, int* gridColSize, int* returnSize, int** returnColumnSizes){\n int row=0,col=0,*p=0,tot=0,gret=0,ind=0,maxc=3,maxr=3,loop=0,**ans=0,loc=0;\n tot=(gridSize-2)*(*gridColSize-2);\n p=(int*)calloc(tot,sizeof(int));\n for(int i=0;i<tot+loop;i++){\n if((gridSize-row)>=3 && (*gridColSize-col)>=3){\n for(int k=row;k<maxr;k++){\n for(int j=col;j<maxc;j++){\n if(grid[k][j]>gret){\n gret=grid[k][j];\n }\n }\n }\n col++;\n maxc++;\n p[loc]=gret;\n loc++;\n gret=0;\n }\n else{\n loop++;\n row++;\n maxr++;\n col=0;\n maxc=3;\n }\n\n }\n\n ans=(int**)calloc((gridSize-2),sizeof(int*));\n (*returnColumnSizes)=(int*)calloc((gridSize-2),sizeof(int));\nloc=0;\n for(int i=0;i<(gridSize-2);i++){\n ans[i]=(int*)calloc((*gridColSize-2),sizeof(int*));\n returnColumnSizes[0][i]=(*gridColSize-2);\n for(int j=0;j<(*gridColSize-2);j++){\n ans[i][j]=p[loc];\n loc++; \n }\n }\n*returnSize=(gridSize-2);\nfree(p);\nreturn ans;\n}\n```
2
0
['C']
1
largest-local-values-in-a-matrix
FASTEST way with JAVA, 2ms(beasts 99.5%)
fastest-way-with-java-2msbeasts-995-by-a-35ke
\n\n# Code\n\nclass Solution {\n public int[][] largestLocal(int[][] grid) {\n int n = grid.length;\n int[][] ret = new int[n-2][n-2];\n
amin_aziz
NORMAL
2023-04-12T08:06:40.776512+00:00
2023-04-12T08:06:40.776561+00:00
1,217
false
\n\n# Code\n```\nclass Solution {\n public int[][] largestLocal(int[][] grid) {\n int n = grid.length;\n int[][] ret = new int[n-2][n-2];\n for(int a = 0; a < n-2; a++){\n int[] first = grid[a];\n int[] second = grid[a+1];\n int[] third = grid[a+2];\n for(int b = 0; b < n-2; b++){\n int max = 0;\n for(int c = b; c < b+3; c++){\n max = Math.max(max, first[c]);\n }\n for(int d = b; d < b+3; d++){\n max = Math.max(max, second[d]);\n }\n for(int e = b; e < b+3; e++){\n max = Math.max(max, third[e]); \n }\n ret[a][b] = max;\n }\n }\n return ret;\n }\n}\n```
2
0
['Java']
1
largest-local-values-in-a-matrix
Beats 87% | C++
beats-87-c-by-pathakjuhi-yev5
Please upvote <3\n\n\nclass Solution {\npublic:\n vector<vector<int>> largestLocal(vector<vector<int>>& grid) {\n int n=grid.size();\n vector<v
pathakjuhi
NORMAL
2023-03-13T10:22:16.838894+00:00
2023-03-13T10:22:16.838929+00:00
246
false
Please upvote <3\n\n```\nclass Solution {\npublic:\n vector<vector<int>> largestLocal(vector<vector<int>>& grid) {\n int n=grid.size();\n vector<vector<int>>res(n-2,vector<int>(n-2,0));\n for(int i=0;i<n-2;i+=1){\n for(int j=0;j<n-2;j+=1){\n int x=0;\n for(int k=i;k<i+3;k+=1){\n for(int l=j;l<j+3;l+=1)\n x=max(x,grid[k][l]);\n res[i][j]=x;\n }\n }\n }\n return res;\n }\n};\n```
2
0
[]
0
largest-local-values-in-a-matrix
JAVA | 2 ms
java-2-ms-by-firdavs06-389p
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
Firdavs06
NORMAL
2023-02-27T07:51:45.874565+00:00
2023-02-27T07:51:45.874615+00:00
915
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 {\n public int[][] largestLocal(int[][] grid) {\n int len = grid.length;\n int max;\n int[][] m = new int[len-2][len-2];\n for(int i = 0; i < len - 2; i++){\n for(int j = 0; j < len - 2; j++){\n max = 0;\n for(int x = i; x < i + 3; x++){\n for(int y = j; y < j + 3; y++){\n if(grid[x][y] > max){\n max = grid[x][y];\n }\n }\n }\n m[i][j] = max;\n }\n }\n return m;\n }\n}\n```
2
0
['Java']
2
largest-local-values-in-a-matrix
πŸ“Œ c++ solution βœ”
c-solution-by-1911uttam-69mr
\nclass Solution {\npublic:\n int find(int i,int j,vector<vector<int>>& grid){\n int ans= 0;\n \n for(int ii=0;ii<3;ii++)\n f
1911Uttam
NORMAL
2023-02-13T06:14:31.409511+00:00
2023-02-13T06:14:31.409557+00:00
790
false
```\nclass Solution {\npublic:\n int find(int i,int j,vector<vector<int>>& grid){\n int ans= 0;\n \n for(int ii=0;ii<3;ii++)\n for(int jj=0;jj<3;jj++)\n ans= max(ans, grid[i+ii][j+jj]);\n \n return ans;\n }\n//----------------------------------------------------------------------\n vector<vector<int>> largestLocal(vector<vector<int>>& grid) {\n int ln= grid.size();\n vector<vector<int>> ans(ln-2,vector<int>(ln-2));\n \n for(int i=0;(i+3)<= ln;i++)\n for(int j=0;(j+3)<= ln;j++)\n ans[i][j]= find(i,j,grid);\n \n return ans;\n }\n};\n```
2
0
['C', 'C++']
0
largest-local-values-in-a-matrix
Python two loops (max_pooling)
python-two-loops-max_pooling-by-inversio-x5d2
Intuition\n Describe your first thoughts on how to solve this problem. \nThis is more like max_pooling in deep learning.\n\n# Approach\n Describe your approach
inversion39
NORMAL
2022-12-27T03:36:27.029297+00:00
2022-12-27T03:36:27.029347+00:00
535
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is more like `max_pooling` in deep learning.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. output shape would be `mxm`, where `m=n-3+1`\n2. loop through the `grid` matrix, get max value for each `3x3` block.\n\n# Complexity\n- Time complexity: `O(n^2)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(m^2)` where `m=n-2`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python\nclass Solution:\n def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:\n n, m = len(grid), len(grid) - 3 + 1\n res = [[0] * m for _ in range(m)]\n for r in range(n - 2):\n for c in range(n - 2):\n mat = [row[c:c+3] for row in grid[r:r+3]]\n res[r][c] = max([max(row) for row in mat])\n return res\n```\n\n**Please upvote if you found this post helpful.**
2
0
['Python3']
1
largest-local-values-in-a-matrix
PYTHON3 BEST
python3-best-by-gurugubelli_anil-z0bt
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
Gurugubelli_Anil
NORMAL
2022-11-17T16:36:09.592037+00:00
2022-11-17T16:36:09.592078+00:00
1,157
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:\n def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:\n n = len(grid)\n ans = [[0]*(n-2) for _ in range(n-2)]\n for i in range(n-2): \n for j in range(n-2): \n ans[i][j] = max(grid[ii][jj] for ii in range(i, i+3) for jj in range(j, j+3))\n return ans\n \n```
2
0
['Python3']
1
largest-local-values-in-a-matrix
C++ solution | 2 simple ways
c-solution-2-simple-ways-by-_kitish-szf3
Method -> 1\n\nclass Solution {\nprivate:\n int giveMax(vector<vector<int>>& v,int i,int j){\n return max({v[i][j],v[i+1][j],v[i+2][j],v[i][j+1],v[i+1
_kitish
NORMAL
2022-10-29T15:40:13.499202+00:00
2022-10-29T15:40:13.499250+00:00
555
false
**Method -> 1**\n```\nclass Solution {\nprivate:\n int giveMax(vector<vector<int>>& v,int i,int j){\n return max({v[i][j],v[i+1][j],v[i+2][j],v[i][j+1],v[i+1][j+1],v[i+2][j+1],v[i][j+2],v[i+1][j+2],v[i+2][j+2]});\n }\npublic:\n vector<vector<int>> largestLocal(vector<vector<int>>& grid) {\n int n = grid.size();\n vector<vector<int>> ans(n-2,vector<int>(n-2));\n for(int i=0; i<n-2; ++i){\n for(int j=0; j<n-2; ++j){\n ans[i][j] = giveMax(grid,i,j);\n }\n }\n return ans;\n }\n};\n```\n**Method -> 2**\n```\nclass Solution {\nprivate:\n vector<pair<int,int>> movements {{0,0},{0,1},{0,2},{1,0},{1,1},{1,2},{2,0},{2,1},{2,2}};\n int giveMax(vector<vector<int>>& v,int i,int j){\n int mx = INT_MIN;\n for(auto [x,y]: movements)\n mx = max(mx,v[x+i][y+j]);\n return mx;\n }\npublic:\n vector<vector<int>> largestLocal(vector<vector<int>>& grid) {\n int n = grid.size();\n vector<vector<int>> ans(n-2,vector<int>(n-2));\n for(int i=0; i<n-2; ++i){\n for(int j=0; j<n-2; ++j){\n ans[i][j] = giveMax(grid,i,j);\n }\n }\n return ans;\n }\n};\n```
2
0
[]
1
largest-local-values-in-a-matrix
Solution in JAVA
solution-in-java-by-coderkuldeep7733-8p8x
class Solution {\n \n \n public static int large(int i,int j,int arr[][]){\n int l=0;\n for(int row=i;row<i+3;row++){\n for(in
coderkuldeep7733
NORMAL
2022-10-21T13:45:48.005800+00:00
2022-10-21T13:45:48.005825+00:00
14
false
class Solution {\n \n \n public static int large(int i,int j,int arr[][]){\n int l=0;\n for(int row=i;row<i+3;row++){\n for(int col=j;col<j+3;col++){\n if(arr[row][col] > l)\n l =arr[row][col];\n }\n }\n return l;\n }\n \n \n public int[][] largestLocal(int[][] grid) {\n \n int arr[][]=new int[grid.length-2][grid.length-2];\n \n for(int mrow=0;mrow<grid.length-2;mrow++)\n {\n for(int mcol=0;mcol<grid.length-2;mcol++){\n arr[mrow][mcol]=large(mrow,mcol,grid);\n } \n } \n \n return arr;\n }\n }\n\t
2
0
[]
0
largest-local-values-in-a-matrix
Easy
easy-by-sunakshi132-vw8j
\nclass Solution:\n def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:\n l=len(grid)-2\n ans=[]\n for i in range(l):\n
sunakshi132
NORMAL
2022-10-12T15:42:30.118692+00:00
2022-10-12T15:42:30.118736+00:00
515
false
```\nclass Solution:\n def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:\n l=len(grid)-2\n ans=[]\n for i in range(l):\n ans.append([0]*l)\n for i in range(l):\n for j in range(l):\n ans[i][j] = max(grid[i][j],grid[i][j+1],grid[i][j+2],\n grid[i+1][j],grid[i+1][j+1],grid[i+1][j+2],\n grid[i+2][j],grid[i+2][j+1],grid[i+2][j+2])\n return ans\n```
2
0
['Python']
1
largest-local-values-in-a-matrix
c++ solution easy 😍
c-solution-easy-by-rohan_bhingare-y5ln
class Solution {\npublic:\n int findMax(vector>& grid , int i ,int j)\n {\n int maxi=INT_MIN;\n for(int x=i ; x<i+3 ; x++){\n for
Rohan_Bhingare
NORMAL
2022-09-26T12:50:27.113020+00:00
2022-09-26T12:50:27.113067+00:00
969
false
class Solution {\npublic:\n int findMax(vector<vector<int>>& grid , int i ,int j)\n {\n int maxi=INT_MIN;\n for(int x=i ; x<i+3 ; x++){\n for(int y=j ; y<j+3 ; y++)\n maxi=max(maxi , grid[x][y]);\n }\n return maxi;\n }\n \n \n \n \n vector<vector<int>> largestLocal(vector<vector<int>>& grid) {\n int n=grid.size();\n \n vector<vector<int>> v(n-2 , vector<int> (n-2));\n for(int i=0 ; i<n-2 ; i++)\n {\n for(int j=0 ; j<n-2 ; j++)\n v[i][j] = findMax(grid , i , j);\n \n }\n \n return v;\n }\n};
2
0
['C']
1
largest-local-values-in-a-matrix
c++ solution | Easy understanding | BruteForce
c-solution-easy-understanding-bruteforce-ieo9
\nclass Solution {\npublic:\n vector<vector<int>> largestLocal(vector<vector<int>>& grid) \n {\n vector<vector<int>>ans(grid.size()-2,vector<int>(g
akshat0610
NORMAL
2022-09-25T17:30:03.679474+00:00
2022-09-25T17:30:03.679515+00:00
358
false
```\nclass Solution {\npublic:\n vector<vector<int>> largestLocal(vector<vector<int>>& grid) \n {\n vector<vector<int>>ans(grid.size()-2,vector<int>(grid.size()-2));\n\n for(int i=0;i<(grid.size()-2);i++)\n {\n for(int j=0;j<(grid.size()-2);j++)\n {\n int ele=getmax(grid,i,j);\t\n ans[i][j]=ele;\n }\t\n } \n return ans; \n }\n int getmax(vector<vector<int>>&grid,int row,int col)\n {\n int temp=INT_MIN;\n for(int i=row;i<row+3;i++)\n {\n for(int j=col;j<col+3;j++)\n {\n temp=max(temp,grid[i][j]);\t\n }\n }\n return temp;\n }\n};\n```
2
0
['C', 'C++']
1
largest-local-values-in-a-matrix
TypeScript solution: easy and short
typescript-solution-easy-and-short-by-ni-anal
\nfunction largestLocal(grid: number[][]): number[][] {\n let result: number[][] = new Array(grid.length - 2).fill(0).map(x => []);\n for (let i = 0; i <
Nina_Torgunakova
NORMAL
2022-09-18T04:34:04.341687+00:00
2022-09-18T04:34:04.341723+00:00
178
false
```\nfunction largestLocal(grid: number[][]): number[][] {\n let result: number[][] = new Array(grid.length - 2).fill(0).map(x => []);\n for (let i = 0; i < grid.length - 2; i++) {\n for (let k = 0; k < grid.length - 2; k++) {\n result[i][k] = Math.max(...grid.slice(i, i + 3).map(row => row.slice(k, k + 3)).flat());\n }\n }\n return result;\n};\n\n```
2
0
['TypeScript']
0
largest-local-values-in-a-matrix
βœ… [Rust] 0 ms, functional-style efficient sliding windows (with detailed comments)
rust-0-ms-functional-style-efficient-sli-ijr5
This solution employs a functional-style approach with sliding windows to first compute maximum values for triples across rows, then across columns. It demonstr
stanislav-iablokov
NORMAL
2022-09-10T23:10:16.788493+00:00
2022-10-23T12:58:17.391662+00:00
142
false
This [solution](https://leetcode.com/submissions/detail/796636578/) employs a functional-style approach with sliding windows to first compute maximum values for triples across rows, then across columns. It demonstrated **0 ms runtime (100%)** and used **2.2 MB memory (66.34%)**. Detailed comments are provided.\n\n**IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n```\nuse std::cmp::max;\n\nimpl Solution \n{\n pub fn largest_local(grid: Vec<Vec<i32>>) -> Vec<Vec<i32>> \n {\n // [1] first, we compute maximum values across\n // 3-windows in each row\n let max_rows: Vec<Vec<i32>> = \n grid\n .iter()\n .map(|v| \n v.windows(3)\n .map(|w| *w.iter().max().unwrap())\n .collect()\n ).collect();\n\n // [2] second, we compute maximum values across\n // 3-windows in each column;\n max_rows\n .windows(3)\n .map(|w: &[Vec<i32>]| \n // [3] to scan columns in a 3-row slice, we zip 3 iterators...\n w[0].iter()\n .zip(w[1].iter())\n .zip(w[2].iter())\n // [4] ...and compute maximum across each column\n .map(|((a,b),c)| max(max(*a,*b),*c))\n .collect()\n ).collect()\n } \n}\n```
2
0
['Rust']
0
largest-local-values-in-a-matrix
c++ || easy
c-easy-by-niraj_1-gw2n
\nclass Solution {\npublic:\n int solve(int r,int c,vector<vector<int>>& grid){\n int maxi=0;\n for(int i=-1;i<=1;i++){\n for(int j=
niraj_1
NORMAL
2022-08-31T08:10:22.410624+00:00
2022-08-31T08:10:22.410656+00:00
235
false
```\nclass Solution {\npublic:\n int solve(int r,int c,vector<vector<int>>& grid){\n int maxi=0;\n for(int i=-1;i<=1;i++){\n for(int j=-1;j<=1;j++){\n int row=r+i,col=c+j;\n maxi=max(grid[row][col],maxi);\n }\n }\n return maxi;\n }\n vector<vector<int>> largestLocal(vector<vector<int>>& grid) {\n int n=grid.size();\n vector<vector<int>> ans(n-2,vector<int>(n-2,0));\n for(int i=0;i<n-2;i++){\n for(int j=0;j<n-2;j++){\n ans[i][j]=solve(i+1,j+1,grid);\n }\n }\n return ans;\n }\n};\n```
2
0
['C']
1
largest-local-values-in-a-matrix
C++ Easy and simple solution
c-easy-and-simple-solution-by-ayushluthr-zsk6
Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F\n\nin
ayushluthra62
NORMAL
2022-08-17T17:45:26.561426+00:00
2022-08-17T17:45:26.561476+00:00
169
false
***Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F***\n```\nint getMax(vector<vector<int>>&grid, int i,int j){\n int maxi=INT_MIN;\n for(int x=i;x<i+3;x++){\n for(int y=j;y<j+3;y++){\n maxi=max(grid[x][y],maxi);\n }\n }\n return maxi;\n }\n \n vector<vector<int>> largestLocal(vector<vector<int>>& grid) {\n int n=grid.size();\n int m=n-2;\n vector<vector<int>>ans(n-2,vector<int>(n-2));\n for(int i=0;i<n-2;i++){\n \n for(int j=0;j<n-2;j++){\n ans[i][j]=getMax(grid,i,j);\n }\n }\n return ans;\n }\n```\n***Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F***
2
0
['C', 'C++']
0
sort-by
🍞🍞🍞 1 LINE | Full thorough explanation | βœ… bread
1-line-full-thorough-explanation-bread-b-wt75
Approach\nFor an array arr, if we call arr.sort(), it will automatically sort the array. However, JavaScript won\'t automatically sort correctly, since how we w
TheGElCOgecko
NORMAL
2023-06-11T07:30:01.135864+00:00
2023-08-13T00:35:18.229414+00:00
9,416
false
# Approach\nFor an array ```arr```, if we call ```arr.sort()```, it will automatically sort the array. However, JavaScript won\'t automatically sort correctly, since how we want the array to be sorted is not solely based on the value of each element, but rather the result of each element being inputted into a function. However, we can create a custom sort, where the parameter is the function we use to sort.\n\nWe create a custom sort in this format:\n```\narr.sort((a, b) => [expression])\n```\nThe ```sort``` function will constantly swap values based on our custom sort function. If the function\'s return value is negative, ```a``` should go to the *left* of ```b```. If the return value is positive, ```a``` should go to the *right* of ```b```. The custom sort function we want is simple and is as follows:\n```\n(a, b) => fn(a) - fn(b)\n```\nIf ```fn(a)``` is less than ```fn(b)```, then the function will return a negative value and ```a``` will go before ```b```. If ```fn(a)``` is greater than ```fn(b)```, the function will return a positive value, and ```a``` will go after ```b```.\n\n# Code\n```\nvar sortBy = function(arr, fn) {\n return arr.sort((a, b) => fn(a) - fn(b));\n};\n```\nUPVOTE if this was helpful \uD83C\uDF5E\uD83C\uDF5E\uD83C\uDF5E
104
0
['Array', 'Sorting', 'JavaScript']
4
sort-by
🀯 More than you ever wanted to know about this topic
more-than-you-ever-wanted-to-know-about-uax49
2724. Sort By\n\nView this Write-up on GitHub\n\n## Summary\n\nThere are two built-in functions we could use, either Array.prototype.sort or Array.prototype.toS
VehicleOfPuzzle
NORMAL
2024-09-05T06:20:51.112595+00:00
2024-09-05T06:20:51.112631+00:00
3,053
false
# 2724. Sort By\n\n[View this Write-up on GitHub](https://github.com/code-chronicles-code/leetcode-curriculum/blob/main/workspaces/javascript-leetcode-month/problems/2724-sort-by/solution.md)\n\n## Summary\n\nThere are two built-in functions we could use, either [`Array.prototype.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) or [`Array.prototype.toSorted`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted). The latter is better if we don\'t want to modify the input, although we could also use the former after first copying the input.\n\nIf `fn` (the function that computes the "sort key") is expensive, we can make sure it\'s invoked at most once per element of the input. Some options are:\n\n- map the input into records or tuples of the sort key and the original element, sort, then map back\n- memoize `fn`, using either a library function like [Lodash](https://lodash.com/)\'s [`memoize`](https://lodash.com/docs/#memoize) (which is available in the LeetCode environment) or our own cache\n\nIf we wish to treat this problem as an algorithmic problem rather than an API knowledge problem, we can also get accepted by implementing our own sorting algorithm.\n\n## Background\n\n### Sorting in JavaScript\n\nLike most modern programming languages, JavaScript comes with a built-in function for sorting, the `.sort` method of array objects. Although nowadays JavaScript is being used for all kinds of applications, it seems that its early API design expected that programmers would need to sort strings more often than numbers. If the desired comparison method is not specified, `.sort` will do a _string_ comparison on the array elements, leading to hilarious results. For example:\n\n```javascript []\nconst arr = [5, 12, 37, 3];\narr.sort();\nconsole.log(arr); // prints [ 12, 3, 37, 5 ]\n```\n\nIt\'s therefore essential to specify a custom comparator that\'s appropriate for the kind of elements you want to sort.\n\n---\n\n###### \u2753 **What would the array `[{digit: 3}, {digit: 1}, {digit: 4}]` become after we invoke `.sort` on it with no arguments?** Try it in your browser\'s JavaScript console! The answer is at the bottom of this doc.\n\n---\n\nA custom comparator in JavaScript is very similar to a [`Comparator`](<https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Comparator.html#compare(T,T)>) in Java. It\'s a function object that takes in two array elements and is expected to return a number, based on the following contract:\n\n- **a negative number** means the first element passed in is "smaller", i.e. should be ordered before the second one\n- **a positive number** means the first element passed in is "bigger", i.e. should be ordered after the second one\n- **zero** means the two elements are equal according to the sort criteria\n\nA lot of people read about this contract and then write code like this:\n\n```javascript []\nfunction numericCompare(a, b) {\n if (a < b) {\n return -1;\n }\n\n if (a > b) {\n return 1;\n }\n\n return 0;\n}\n\nconst arr = [5, 12, 37, 3];\narr.sort(numericCompare);\nconsole.log(arr); // prints [ 3, 5, 12, 37 ], yay!\n```\n\nFor some reason "a negative number" becomes -1 in their code and "a positive number" becomes 1. There\'s nothing in the contract requiring -1 and 1, we could just as well return -2 and 2, or any other numbers. The contract only cares about the _sign_ of the result, not its magnitude. That\'s why I recommend writing the `numericCompare` function more concisely:\n\n```javascript []\nfunction numericCompare(a, b) {\n return a - b;\n}\n```\n\nLet\'s quickly confirm that it respects the contract: if a < b, then a - b will be a negative number; if a > b, then a - b will be a positive number; and if a = b, then a - b = 0. It works!\n\nUsing this principle, writing a custom comparator becomes simple enough to inline most of the time, usually using an arrow function expression:\n\n```javascript []\nconst arr = [5, 12, 37, 3];\narr.sort((a, b) => a - b);\nconsole.log(arr); // prints [ 3, 5, 12, 37 ], yay!\n```\n\nSorting objects by some numeric property can also use the subtraction idiom, for example let\'s sort some strings by their length:\n\n```javascript []\nconst arr = ["Alice", "Bob", "Charlie"];\narr.sort((a, b) => a.length - b.length);\nconsole.log(arr); // prints [ "Bob", "Alice", "Charlie" ]\n```\n\nAnd to reverse the sort order, invert the sign of the comparator by inverting the subtraction:\n\n```javascript []\nconst arr = [5, 12, 37, 3];\narr.sort((a, b) => b - a);\nconsole.log(arr); // prints [ 37, 12, 5, 3 ]\n```\n\n---\n\n###### \u2753 Can you think of a concise way to break ties in a custom comparator? **How would we sort an array of _x_ and _y_ coordinates first by _x_ in increasing order, breaking ties by _y_ in decreasing order?** An answer is included at the bottom of this doc.\n\n---\n\n### Regarding API Design\n\nSome APIs return a new value. Some APIs mutate their argument. [`Array.prototype.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) unfortunately does both -- it mutates the array it\'s invoked on, but it also returns it. This makes it convenient to chain `.sort` with other array methods, but unfortunately it also results in code like this:\n\n```javascript []\nconst arr = [3, 1, 4];\nconst sortedArr = arr.sort((a, b) => a - b);\n```\n\nCan you spot the potential confusion? The code reads as if the developer expected `.sort` to return a sorted copy of `arr`, but in fact `arr` and `sortedArr` both refer to exactly the same object! That\'s because `.sort` mutated `arr` in-place, and then additionally returned it! Misconceptions like this could lead to bugs, if the developer thought that `arr` still contains the data in its non-sorted state.\n\n---\n\n###### \uD83D\uDCA1 If you\'re using TypeScript, default to annotating array data that you don\'t intend to mutate as `readonly`. You\'ll get a type error if you accidentally invoke a mutating method on such an array, like `.push`, `.pop`, or `.sort`.\n\n---\n\nFor a `.sort` API that mutates in-place, I would prefer that it didn\'t return anything. It could be less convenient in some cases, but it\'s less likely to be misused. Python got this right: the [`sorted`](https://docs.python.org/3/library/functions.html#sorted) function returns a new, sorted list, whereas the [`.sort`](https://docs.python.org/3/library/stdtypes.html#list.sort) method of list objects mutates in-place and doesn\'t return anything. I\'ll therefore often choose to deliberately not use the return value of JavaScript\'s `.sort`, unless it\'s especially convenient. (Today\'s problem might be one of those cases wherein being able to sort and return in one statement does feel very nice.)\n\n---\n\n###### \uD83D\uDCA1 When you design APIs, I hope you\'ll pick to either return new data, or mutate the input, but not both. Be clear on how you\'d like your API to be used!\n\n---\n\nNote that for cases when you don\'t want to mutate the original array, the latest JavaScript spec includes a [`.toSorted`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted) method that returns a sorted copy.\n\n[`Array.prototype.reverse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) suffers from the same flaw of both modifying the array it\'s invoked on and also returning it. You can use the recently added [`.toReversed`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toReversed) to get a reversed copy of an array.\n\n## Solutions\n\nLet\'s write some!\n\n### Using `Array.prototype.sort`\n\nIf we don\'t mind mutating the input, we can write a single expression, using the subtraction idiom for the custom comparator function:\n\n[View Submission](https://leetcode.com/problems/sort-by/submissions/1378429436/)\n\n```javascript []\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nconst sortBy = (arr, fn) => arr.sort((a, b) => fn(a) - fn(b));\n```\n\nFor TypeScript, I opted to use generics and get rid of the `JSONValue` junk from LeetCode\'s default template. We don\'t have to limit ourselves to JSON, we can handle anything as long as our input array and `fn` are in sync!\n\n[View Submission](https://leetcode.com/problems/sort-by/submissions/1378760710/)\n\n```typescript []\nconst sortBy = <T>(arr: T[], fn: (value: T) => number): T[] =>\n arr.sort((a, b) => fn(a) - fn(b));\n```\n\nSince the problem is asking us to _return_ a sorted array, by the principle of either mutating or returning but not both, I think we should favor not modifying the input, and marking it `readonly` in TypeScript. We can still use `.sort` if we first make a copy of the input, for example using [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax):\n\n[View Submission](https://leetcode.com/problems/sort-by/submissions/1378760479/)\n\n```typescript []\nconst sortBy = <T>(arr: readonly T[], fn: (value: T) => number): T[] =>\n [...arr].sort((a, b) => fn(a) - fn(b));\n```\n\n### Using `Array.prototype.toSorted`\n\nThe code will look very similar to the code using `.sort`:\n\n[View Submission](https://leetcode.com/problems/sort-by/submissions/1378760265/)\n\n```javascript []\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nconst sortBy = (arr, fn) => arr.toSorted((a, b) => fn(a) - fn(b));\n```\n\nCuriously, although LeetCode\'s JavaScript environment supports the `.toSorted` method, at the time of this writing, LeetCode\'s TypeScript config isn\'t aware that this method exists. So we have to inform TypeScript that it does, by declaring it!\n\n[View Submission](https://leetcode.com/problems/sort-by/submissions/1378759820/)\n\n```typescript []\ndeclare global {\n interface Array<T> {\n toSorted(this: T[], compareFn: (a: T, b: T) => number): T[];\n }\n\n interface ReadonlyArray<T> {\n toSorted(this: readonly T[], compareFn: (a: T, b: T) => number): T[];\n }\n}\n\nconst sortBy = <T>(arr: readonly T[], fn: (value: T) => number): T[] =>\n arr.toSorted((a, b) => fn(a) - fn(b));\n```\n\nNote that `ReadonlyArray` and `Array` are distinct interfaces. That\'s one way TypeScript can prevent mutation of arrays: a `ReadonlyArray` is simply missing the definitions of mutating methods! Since `.toSorted` is a non-mutating method, it exists on both interfaces.\n\n### Minimizing Calls to `fn`\n\nIf the function we use to compute the "sort key", `fn`, is especially expensive, it might be a good idea to limit how much we invoke it. The best we can theoretically do is _O(N)_ invocations, where _N_ is the size of the array. If there are lots of duplicated elements we can account for that as well, but in general any better than once per element is impossible. (How can we sort correctly without computing where each element should go?)\n\nFrom a time complexity perspective, this isn\'t that exciting, since a good `.sort` should have a time complexity of _O(N log N)_, so we\'re talking about reducing the number of invocations of `fn` by a factor of _O(log N)_. We\'d need a rather large _N_ for _O(log N)_ to be meaningful. But practically speaking, it might make a difference, and any constant factors might also come into play. You\'ll have to measure it for your use case!\n\nFor now, let\'s assume that it\'s a good idea to minimize calls to `fn` and see some ways to do it. One option is to transform the input so that `fn` has already been computed, once and only once, for each element. The sorting step can then be done using simple look-ups. We\'ll just have to re-map the data before returning it.\n\nThe code below uses a JavaScript object (a record) to group each element with its sort key. The braces in `({ element }) => element` are a [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).\n\n[View Submission](https://leetcode.com/problems/sort-by/submissions/1378759536/)\n\n```typescript []\nconst sortBy = <T>(arr: readonly T[], fn: (value: T) => number): T[] =>\n arr\n .map((element) => ({ element, sortKey: fn(element) }))\n .sort((a, b) => a.sortKey - b.sortKey)\n .map(({ element }) => element);\n```\n\n---\n\n###### \u2753 **How come TypeScript allowed us to use `.sort` in the above solution when the input is marked `readonly`?** The answer is at the bottom of this doc.\n\n---\n\nInstead of records, we could have used tuples. JavaScript doesn\'t have an explicit tuple data type, but arrays are often used as tuples. An explicit [tuple type annotation](https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types) helps TypeScript distinguish it from some other kind of array, and the square brackets in `([element]) => element` are once again a [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).\n\n[View Submission on LeetCode](https://leetcode.com/problems/sort-by/submissions/1378759168/)\n\n```typescript []\nconst sortBy = <T>(arr: readonly T[], fn: (value: T) => number): T[] =>\n arr\n .map((element): [T, number] => [element, fn(element)])\n .sort((a, b) => a[1] - b[1])\n .map(([element]) => element);\n```\n\nInstead of explicit pre-computing via `.map`, we can give `fn` a caching wrapper. Memoization is incredibly common in JavaScript code, and on LeetCode we have access to a [`memoize`](https://lodash.com/docs/#memoize) helper through [Lodash](https://lodash.com/). (In the future we\'ll also implement our own, in problems like [2623. Memoize](https://leetcode.com/problems/memoize/).)\n\n[View Submission](https://leetcode.com/problems/sort-by/submissions/1378433879/)\n\n```javascript []\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nfunction sortBy(arr, fn) {\n const memoizedFn = _.memoize(fn);\n return arr.toSorted((a, b) => memoizedFn(a) - memoizedFn(b));\n}\n```\n\nWe can also implement our own bespoke caching wrapper, using a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map). It\'s important to go with a `Map` instead of a plain JavaScript object as a map, because we don\'t know what type of data the input array might hold. JavaScript objects are adequate maps primarily when working with string keys. For arbitrary keys, we can\'t assume unique stringifications.\n\n[View Submission](https://leetcode.com/problems/sort-by/submissions/1378432975/)\n\n```typescript []\nfunction sortBy<T>(arr: readonly T[], fn: (value: T) => number): T[] {\n const cache = new Map<T, number>();\n const getSortKey = (value: T): number => {\n let res = cache.get(value);\n if (res == null) {\n res = fn(value);\n cache.set(value, res);\n }\n return res;\n };\n\n return [...arr].sort((a, b) => getSortKey(a) - getSortKey(b));\n}\n```\n\n### Implementing a Sort Algorithm\n\nAlthough I think the intent of the problem was to teach us about how to `.sort` with a custom comparator, we can also choose to treat it as an algorithmic problem and implement our own sort. For example, here\'s a (not particularly optimized) [merge sort](https://en.wikipedia.org/wiki/Merge_sort):\n\n[View Submission](https://leetcode.com/problems/sort-by/submissions/1378430770/)\n\n```typescript []\nfunction sortBy<T>(arr: readonly T[], fn: (value: T) => number): T[] {\n const n = arr.length;\n if (n <= 1) {\n return [...arr];\n }\n\n const middleIndex = Math.floor(n / 2);\n const firstHalf = sortBy(arr.slice(0, middleIndex), fn);\n const secondHalf = sortBy(arr.slice(middleIndex), fn);\n\n const res: T[] = [];\n\n let firstHalfCursor = 0;\n let secondHalfCursor = 0;\n while (\n firstHalfCursor < firstHalf.length &&\n secondHalfCursor < secondHalf.length\n ) {\n res.push(\n fn(firstHalf[firstHalfCursor]) <= fn(secondHalf[secondHalfCursor])\n ? firstHalf[firstHalfCursor++]\n : secondHalf[secondHalfCursor++],\n );\n }\n res.push(\n ...firstHalf.slice(firstHalfCursor),\n ...secondHalf.slice(secondHalfCursor),\n );\n\n return res;\n}\n```\n\n### Absolutely Refusing to Specify a Custom Comparator\n\nI couldn\'t resist also including a fun hack as a bonus solution. Since the problem clearly wants us to `.sort` with a custom comparator function, could we somehow get default `.sort` to do the right thing? It turns out we can...\n\n[View Submission](https://leetcode.com/problems/sort-by/submissions/1379421195/)\n\n```typescript []\nconst sortBy = <T>(arr: T[], fn: (value: T) => number): T[] =>\n arr\n .map((element) => `${1.1e10 + fn(element)} ${JSON.stringify(element)}`)\n .sort()\n .map((sortKeyAndElement) =>\n JSON.parse(sortKeyAndElement.replace(/^\\d+ /, "")),\n );\n```\n\n---\n\n###### \u2753 **How does this solution work?** Hint: It packs the original data and its sort key into a string, then decodes the original data after sorting. But how do we get strings that will naturally sort in the correct order? The answer is at the bottom of the doc.\n\n---\n\n## Answers to Bonus Questions\n\n1. **What would the array `[{digit: 3}, {digit: 1}, {digit: 4}]` become after a `.sort` with no arguments?**\n\n It\'s a bit of a trick question! It would remain unchanged. That\'s because unless we override it, an object in JavaScript gets stringified to `"[object Object]"`. So all three array elements will get stringified to the same thing and be considered equal as far as the comparison is concerned. Since `.sort` is expected to be a _stable_ sorting algorithm, "equal" elements maintain their relative order in the sorted result. So nothing moves.\n\n<!-- prettier-ignore-start -->\n2. **How would we sort an array of _x_ and _y_ coordinates first by _x_ in increasing order, breaking ties by _y_ in decreasing order?**\n\n We can take advantage of the fact that 0 is a falsy value in JavaScript:\n\n <!-- Prettier will try to remove some parentheses that I\'d like to keep for clarity. -->\n ```js\n const arr = [\n { x: 5, y: 2 },\n { x: 3, y: -1 },\n { x: 3, y: 0 },\n ];\n arr.sort((a, b) => (a.x - b.x) || (b.y - a.y));\n console.log(arr); // prints [ { x: 3, y: 0 }, { x: 3, y: -1 }, { x: 5, y: 2 } ]\n ```\n\n When the two _x_ coordinates are zero, the `||` will compute and return the _y_ comparison.\n\n<!-- prettier-ignore-end -->\n\n3. **Why did TypeScript seemingly allow us to use `.sort` in a solution with a `readonly` input?**\n\n We should look at the code carefully! The `.sort` is not invoked directly on the input, but chained after a `.map`:\n\n ```typescript []\n const sortBy = <T>(arr: readonly T[], fn: (value: T) => number): T[] =>\n arr\n .map((element) => ({ element, sortKey: fn(element) }))\n .sort((a, b) => a.sortKey - b.sortKey)\n .map(({ element }) => element);\n ```\n\n Whenever we `.map` (or `.filter`) we\'re creating a new array, and that array is no longer `readonly`. The input is not mutated by this code.\n\n4. **How can we get a solution that uses a default `.sort` to work?**\n\n Here\'s the code again for convenience:\n\n ```typescript []\n const sortBy = <T>(arr: T[], fn: (value: T) => number): T[] =>\n arr\n .map((element) => `${1.1e10 + fn(element)} ${JSON.stringify(element)}`)\n .sort()\n .map((sortKeyAndElement) =>\n JSON.parse(sortKeyAndElement.replace(/^\\d+ /, "")),\n );\n ```\n\n Since the default `.sort` works on strings, we need to replace our array with strings that will naturally be ordered based on the output of `fn`. The basic idea is to create strings that encode the output of `fn` and the data itself, separated with a space. Since LeetCode promised us JSON data, we can use `JSON.stringify` to encode and `JSON.parse` later recover the elements.\n\n But just concatenating via space is not enough! If `fn` returns 100 for some array element and 12 for another, building the strings naively would give us `"100 <some JSON>"` and `"12 <some JSON>"`, and the string with 100 will be ordered first! To address this, we add `1.1e10` to the result of `fn` -- this is another way of expressing the number 11,000,000,000. Then, in the 100 and 12 example, the strings will become `"11000000100 <some JSON>"` and `"11000000012 <some JSON>"` which will now sort correctly. The reason for `1.1e10` instead of just `1e10` is so we can handle negative outputs from `fn`. If `fn` returns -1, we\'ll get the string `"10999999999 <some JSON>"` which will also be ordered correctly!\n\n Overall, this assumes that `fn` will return an integer between -1,000,000,000 and 1,000,000,000 inclusive, which happened to work on all of LeetCode\'s test cases. If we needed to handle floating point values, or a greater range of numbers, we could have gone for a more elaborate hack.\n\n---\n\n###### Thanks for reading! If you enjoyed this write-up, feel free to up-vote it! \n\n# \uD83D\uDE4F
41
0
['TypeScript', 'JavaScript']
5
sort-by
Simple one line.
simple-one-line-by-cpcs-f5ge
\n# Code\n\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a, b) => fn(a)
cpcs
NORMAL
2023-06-07T06:20:16.649688+00:00
2023-06-07T06:20:16.649742+00:00
4,196
false
\n# Code\n```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a, b) => fn(a) - fn(b));\n};\n```
14
0
['JavaScript']
1
sort-by
using merge sort / quick sort
using-merge-sort-quick-sort-by-simonapiz-8au5
Merge Sort\n\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */// merge sort\nvar sortBy = function(arr, fn) {\n const n = arr.lengt
SimonaPiz
NORMAL
2023-06-29T08:53:48.502661+00:00
2023-06-29T08:53:48.502688+00:00
930
false
# Merge Sort\n```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */// merge sort\nvar sortBy = function(arr, fn) {\n const n = arr.length;\n // base case\n if (n == 1) return arr;\n\n // divide\n const mid = Math.floor(n/2);\n const arrLeft = arr.slice(0, mid); \n const arrRight = arr.slice(mid, n);\n\n // sort and merge \n return merge(sortBy(arrLeft, fn), sortBy(arrRight, fn), fn);\n};\n\n/**\n * @param {Array} left\n * @param {Array} right\n * @param {Function} fn\n * @return {Array}\n */// merge function\nfunction merge (left, right, fn) {\n const sortedArray = [];\n while (left.length > 0 && right.length > 0) {\n // sort and merge\n if (fn(left[0]) < fn(right[0])) {\n sortedArray.push(left[0]);\n left.shift();\n } else {\n sortedArray.push(right[0]);\n right.shift();\n }\n }\n\n return sortedArray.concat(left, right);\n}\n```\n# Quick Sort\n```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */// using quick sort\nvar sortBy = function(arr, fn) {\n // function quick sort\n const quickSort = (arr, leftBound = 0, rightBound = arr.length-1) => {\n if (leftBound < rightBound) {\n const pivotIdx = partition(arr, leftBound, rightBound);\n quickSort(arr, leftBound,pivotIdx-1);\n quickSort(arr, pivotIdx, rightBound);\n }\n return arr;\n }\n\n // function partition\n const partition = (arr, left, right) => {\n const pivot = fn(arr[Math.floor((right+left) /2)]);\n while (left <= right) {\n while (fn(arr[left]) < pivot) left++;\n while (fn(arr[right]) > pivot) right--;\n\n if (left <= right) {\n // swap\n const temp = arr[right];\n arr[right] = arr[left];\n arr[left] = temp;\n\n left++;\n right--;\n }\n }\n\n return left;\n }\n\n return quickSort(arr);\n}\n```
13
1
['Sorting', 'Merge Sort', 'JavaScript']
2
sort-by
πŸ—“οΈ Daily LeetCoding Challenge Day 24|| πŸ”₯ JS SOL
daily-leetcoding-challenge-day-24-js-sol-puzs
\n# Code\n\nvar sortBy = function(arr, fn) {\n return arr.sort((a, b) => fn(a) - fn(b));\n};\n
DoaaOsamaK
NORMAL
2024-06-14T19:09:49.316448+00:00
2024-06-14T19:09:49.316479+00:00
1,722
false
\n# Code\n```\nvar sortBy = function(arr, fn) {\n return arr.sort((a, b) => fn(a) - fn(b));\n};\n```
11
0
['JavaScript']
2
sort-by
Use quicksort instead of native sort function - surprise! it's faster
use-quicksort-instead-of-native-sort-fun-uk3z
Code\n\nfunction sortBy(arr: any[], fn: Function, left = 0, right = arr.length - 1): any[] {\n if (left >= right) {\n return;\n }\n\n const pivo
RedMonkez
NORMAL
2023-06-18T08:15:55.800871+00:00
2023-06-18T08:15:55.800888+00:00
1,019
false
# Code\n```\nfunction sortBy(arr: any[], fn: Function, left = 0, right = arr.length - 1): any[] {\n if (left >= right) {\n return;\n }\n\n const pivotIndex = partition(arr, fn, left, right);\n\n sortBy(arr, fn, left, pivotIndex - 1);\n sortBy(arr, fn, pivotIndex + 1, right);\n\n return arr;\n};\n\nfunction partition(arr: any[], fn: Function, left: number, right: number): number {\n const pivot = arr[right];\n let i = left - 1;\n\n for (var j = left; j < right; j++) {\n if (fn(arr[j]) <= fn(pivot)) {\n i++;\n swap(arr, i, j);\n }\n }\n\n swap(arr, i + 1, right);\n return i + 1;\n}\n\nfunction swap(arr: any[], i: number, j: number) {\n const temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n}\n\n```
5
0
['TypeScript']
2
sort-by
Very Easy Solution: 1 Line Of Code
very-easy-solution-1-line-of-code-by-nis-uc4c
Intuition\nThe sortBy function takes an array arr and a function fn as parameters. It is designed to sort the array in ascending order based on the values retur
nishantpriyadarshi60
NORMAL
2023-10-20T03:34:17.792866+00:00
2023-10-20T03:34:17.792897+00:00
1,280
false
# Intuition\nThe sortBy function takes an array arr and a function fn as parameters. It is designed to sort the array in ascending order based on the values returned by the function for each element. In other words, it allows you to sort an array based on a custom criterion defined by the function fn.\n\n# Approach:\nThe sortBy function uses the sort method on the input array arr. The sort method sorts the array in place based on the values of its elements.\n\nThe sorting is done using a custom comparison function that calculates the difference between the results of applying the function fn to two elements, a and b. The comparison function (a, b) => fn(a) - fn(b) is used for this purpose.\n\nBy subtracting the result of fn(b) from fn(a), we achieve ascending sorting order. If fn(a)is smaller thanfn(b), the result will be a negative number, indicating that a should come before b in the sorted array. If fn(a) is larger, the result will be positive, and a should come after b.\n\nThe array is sorted based on the calculated differences, so elements for which fn(a) is smaller will appear earlier in the sorted array, while elements for which fn(b) is smaller will appear later.\n\n# Complexity\n- Time complexity:\no(n*(log(n)))\n\n- Space complexity:\no(1)\n\n# Code\n```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a,b) => fn(a) - fn(b));\n};\n```
4
0
['JavaScript']
0
sort-by
Single line JS with explanation (90% run time)
single-line-js-with-explanation-90-run-t-5vvu
\n# Approach\n Describe your approach to solving the problem. \nUsing sort function in JS. \n\n# Solution\n Describe your approach to solving the problem. \nArr
user4495rR
NORMAL
2023-07-06T05:32:59.708011+00:00
2023-07-06T05:32:59.708031+00:00
843
false
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing sort function in JS. \n\n# Solution\n<!-- Describe your approach to solving the problem. -->\nArray.sort(compareFn) works in the following way:\ncompareFn = (a,b)=> {\n/* some logic that returns 0, 1 or -1 \n\n1. a and b are the two elements picked from arr for comparison (so a,b are always defined)\n2. if compareFn returns -1, array is sorted as [a,b]\n3. if compareFn returns +1, array is sorted as [b,a]\n4. if compareFn returns 0, order of a,b is left unchanged\n\n*/\n\n}\n\n\n# Code\n```\nfunction sortBy(arr: any[], fn: Function): any[] {\n return arr.sort((a,b)=>fn(a)-fn(b))\n};\n```
4
0
['TypeScript']
0
sort-by
Beats 87.63%πŸ₯³One Simple line with explanationπŸ˜‰βœ…
beats-8763one-simple-line-with-explanati-n6hw
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
ayaAshraf
NORMAL
2023-12-21T16:29:14.783516+00:00
2023-12-21T16:29:14.783553+00:00
375
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\nUsing Sort method we can sort numbers that return from function ascending\n- if negative number means a is smaller than b so it will not changed\n- if positive number it means a is bigger than b so it will be order to right \n- in case of zero that means a & b are equal so no need to change\n```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a, b) => fn(a) - fn(b));\n};\n```\n\n**Native Approch**\nhere we are comparing numbers and shifting the smallest one to left so at the end the array will be sorted\uD83D\uDE03\n```\n for(let i=0;i<arr.length;i++){\n for(let j=i+1;j<arr.length;j++){\n if(fn(arr[i])>fn(arr[j])){\n let temp = 0;\n temp = arr[j];\n arr[j] = arr[i];\n arr[i] = temp\n }\n }\n }\n return arr;\n```
3
0
['JavaScript']
0
sort-by
Easy Solution
easy-solution-by-mdgolamrabbani-l153
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
mdgolamrabbani
NORMAL
2023-09-06T17:02:22.189341+00:00
2023-09-06T17:02:22.189362+00:00
484
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```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a, b) => fn(a) - fn(b));\n};\n```
3
0
['JavaScript']
0
sort-by
Two solutions - Array.prototype.sort() with closure, and a Quicksort implementation.
two-solutions-arrayprototypesort-with-cl-9xtk
Intuition\nThe Javacript Array prototype offers a swap method that takes a comparison function, but it requires the function to take two inputs and then return
nigh_anxiety
NORMAL
2023-06-17T18:08:57.643819+00:00
2023-06-17T18:08:57.643838+00:00
1,571
false
# Intuition\nThe Javacript Array prototype offers a swap method that takes a comparison function, but it requires the function to take two inputs and then return -1 (a < b) , 0 (a == b) or 1 (a > b), so we can\'t just pass the provided `fn` variable into `Array.swap()`\n\n# Approach\nCreate a new swap function using `fn` in a closure, and then pass that to the prototype swap method.\n It would also be possible to just pass this as an anonymous function directly into arr.sort.\n\n# Complexity\n- Time and Space complexity:\n I couldn\'t find the documented complexity for `Array.Prototype.sort()`, but I assume its using some variation on the quicksort algorithm which would make it `O(n log n)` for time complexity and `O(log n)` for space complexity.\n\n\n# Code\n```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nconst sortBy = function(arr, fn) {\n function swap(a, b) {\n return (fn(a) < fn(b)) ? -1 : 1\n }\n\n return arr.sort(swap)\n};\n```\n\n# VERSION 2\n Here I decided to try implementing my own sort algorithm for practice. Bubble Sort is too slow for some of the required test cases and will time out, so here I implemented my own QuickSort. With several runs of this compared to the `Array.sort()` method above, the results were comparable. There was enough variablility in the test runs results that neither had a clear advantage, but I would give this version a slight time advantage, while version 1 seemed to have a slight memory advantage.\n\n\n```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nconst sortBy = function(arr, fn) {\n // We don\'t need to pass arr as a parameter to each function.\n function swap(i, j) {\n [arr[i], arr[j]] = [arr[j], arr[i]]\n }\n \n function partition(start, end) {\n const pivot = fn(arr[end]);\n let i = (start - 1); \n for (let j = start; j <= end - 1; j++) {\n if (fn(arr[j]) <= pivot) { \n swap(++i, j)\n } \n } \n swap(++i, end)\n return i; \n }\n\n function quick_sort(start, end) { \n if (start < end) {\n let pi = partition(start, end); \n quick_sort(start, pi - 1); \n quick_sort(pi + 1, end); \n } \n }\n\n quick_sort(0, arr.length-1);\n return arr\n};\n```\n\n\n
3
0
['JavaScript']
0
sort-by
Easy and simple solution | one line Solution
easy-and-simple-solution-one-line-soluti-6pml
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
Nitin_singh_000
NORMAL
2024-05-02T16:11:03.852800+00:00
2024-05-02T16:11:03.852833+00:00
806
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```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a,b)=> fn(a)-fn(b))\n};\n```
2
0
['JavaScript']
0
sort-by
βœ… βœ… Simple TypeScript Solution with explanation βœ… βœ…
simple-typescript-solution-with-explanat-j13g
\nWe have to return sorted array, so we simply use arrays method sort. But the values, that has to be sorted dependent on function "fn" from arguments. Because
arturKulish
NORMAL
2024-03-04T18:33:16.137720+00:00
2024-03-04T18:33:16.137750+00:00
765
false
\nWe have to return sorted array, so we simply use arrays method sort. But the values, that has to be sorted dependent on function "fn" from arguments. Because of that we have to run function inner and pass arguments "a" and "b". The functions return us values that we have to compare. So we do it and return result.\n\n# Code\n```\ntype JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };\ntype Fn = (value: JSONValue) => number\n\nfunction sortBy(arr: JSONValue[], fn: Fn): JSONValue[] {\n return arr.sort((a, b) => fn(a) - fn(b)); \n};\n```
2
0
['TypeScript']
0
sort-by
100 % Beats
100-beats-by-alokranjanjha10-nl6t
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
alokranjanjha10
NORMAL
2023-07-27T12:37:28.504700+00:00
2023-07-27T12:37:28.504720+00:00
1,151
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```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a, b) => fn(a) - fn(b)); \n};\n```
2
0
['JavaScript']
1
sort-by
1 line solution
1-line-solution-by-bikramghoshal6337-sc94
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
bikramghoshal6337
NORMAL
2023-07-26T17:12:25.878278+00:00
2023-07-26T17:12:25.878299+00:00
714
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```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a, b) => fn(a) - fn(b));\n};\n```
2
0
['JavaScript']
0
sort-by
Very easy and simple solution in JS :)
very-easy-and-simple-solution-in-js-by-a-7mel
\n# Code\n\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a,b) => fn(a) -
AzamatAbduvohidov
NORMAL
2023-07-13T12:51:39.214350+00:00
2023-07-13T12:51:39.214371+00:00
980
false
\n# Code\n```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a,b) => fn(a) - fn(b))\n};\n```
2
0
['JavaScript']
0
sort-by
JavaScript Solution
javascript-solution-by-motaharozzaman199-8icd
\n\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a,b)=>fn(a)-fn(b));\n
Motaharozzaman1996
NORMAL
2023-06-08T12:28:14.034009+00:00
2023-06-08T12:28:14.034049+00:00
2,207
false
\n```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a,b)=>fn(a)-fn(b));\n \n};\n```
2
0
['JavaScript']
0
sort-by
βœ… 🌟 JAVASCRIPT SOLUTION ||πŸ”₯ BEATS 100% PROOFπŸ”₯|| πŸ’‘ CONCISE CODE βœ… || πŸ§‘β€πŸ’» BEGINNER FRIENDLY
java-solution-beats-100-proof-concise-co-sfpt
Complexity Time complexity:O(nlogn) Space complexity:O(n) Code
Shyam_jee_
NORMAL
2025-03-27T17:59:29.832651+00:00
2025-03-28T19:39:44.609156+00:00
139
false
# Complexity - Time complexity:$$O(nlogn)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:$$O(n)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a, b)=>fn(a)-fn(b)); }; ```
1
0
['JavaScript']
0
sort-by
Quick sort implementation | beats 98%
quick-sort-implementation-beats-98-by-sh-cg5n
IntuitionWe need to sort an array based on a custom function fn. The function transforms each element, and we compare the transformed values to determine the or
sharqawycs
NORMAL
2025-03-04T09:07:37.387970+00:00
2025-03-04T09:07:37.387970+00:00
44
false
# Intuition We need to sort an array based on a custom function `fn`. The function transforms each element, and we compare the transformed values to determine the order. QuickSort is a good choice because it efficiently sorts in-place with an average time complexity of `O(n log n)`. # Approach 1. Copy the input array to avoid modifying the original. 2. Implement the QuickSort algorithm with a custom comparison using `fn()`. 3. Partition the array based on the transformed values. 4. Recursively sort the left and right subarrays. # Complexity ![image.png](https://assets.leetcode.com/users/images/a409e362-c2d1-45de-9f62-cb81f7d3b26d_1741079221.9126496.png) - Time complexity: - **Average case**: $$O(n \log n)$$ - **Worst case**: $$O(n^2)$$ (if the pivot selection is poor) - Space complexity: - **Worst case**: $$O(n)$$ (due to recursive function calls) # Code ```Javascript [] var sortBy = function (arr, fn) { let res = [...arr]; // Create a copy of the array quickSort(res, 0, res.length - 1); return res; // QuickSort with a custom comparison function function partition(myArr, low, high) { let pivot = myArr[high]; let i = low - 1; for (let j = low; j < high; j++) { if (fn(myArr[j]) < fn(pivot)) { i++; [myArr[i], myArr[j]] = [myArr[j], myArr[i]]; // Swap elements } } [myArr[i + 1], myArr[high]] = [myArr[high], myArr[i + 1]]; // Place pivot correctly return i + 1; } function quickSort(myArr, low, high) { if (low >= high) return; let pi = partition(myArr, low, high); quickSort(myArr, low, pi - 1); quickSort(myArr, pi + 1, high); } }; ```
1
0
['Sorting', 'Merge Sort', 'JavaScript']
0
sort-by
JavaScript
javascript-by-adchoudhary-e333
Code
adchoudhary
NORMAL
2025-03-01T07:42:06.193271+00:00
2025-03-01T07:42:06.193271+00:00
209
false
# Code ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a,b) => fn(a) - fn(b)) }; ```
1
0
['JavaScript']
0
sort-by
Comparator function || JS ||
comparator-function-js-by-ashish_ujjwal-26xg
Code
Ashish_Ujjwal
NORMAL
2025-02-22T07:35:02.694924+00:00
2025-02-22T07:35:02.694924+00:00
128
false
# Code ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a,b)=> fn(a)-fn(b)); }; // (a, b) => a-b; sort no. in ascending order // It should return a number where: // -> A negative value indicates thtat a should come before b. // -> A Positive value indicates thtat a should come after b. // -> Zero or Null indicates that a and b are considered equal. ```
1
0
['JavaScript']
0
sort-by
BEAT 70+% || EASY TO UNDERSTAND SOLUTION || JS
beat-70-easy-to-understand-solution-js-b-5sej
IntuitionApproachComplexity Time complexity: Space complexity: Code
Siddarth9911
NORMAL
2025-01-28T16:23:15.573467+00:00
2025-01-28T16:23:15.573467+00:00
244
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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a, b) => fn(a) - fn(b)); }; ```
1
0
['JavaScript']
0
sort-by
Easy Explanation
easy-explanation-by-pratyushpanda91-hlhy
Explanation:Built-in Sort:The sort() function in JavaScript allows sorting elements based on a comparison function. The comparison function (a, b) => fn(a) - fn
pratyushpanda91
NORMAL
2025-01-24T04:04:55.139829+00:00
2025-01-24T04:04:55.139829+00:00
175
false
# Explanation: ### Built-in Sort: The sort() function in JavaScript allows sorting elements based on a comparison function. The comparison function (a, b) => fn(a) - fn(b) computes the difference between the results of fn applied to a and b. ### Behavior: If fn(a) < fn(b), the function returns a negative value, indicating that a should come before b. If fn(a) > fn(b), the function returns a positive value, indicating that a should come after b. If fn(a) === fn(b), it returns 0, meaning their order is unchanged. # Code ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a, b) => fn(a) - fn(b)); }; ```
1
0
['JavaScript']
0
sort-by
Beats 96.11%β€Ό You also could do this!
sort-by-by-harryakbaram-zvxn
IntuitionWe can use the Array.sort and use the fn paramater to get the value that we want to compare.Approach This is ascending sort, so we expect element n is
harryakbaram
NORMAL
2024-12-19T06:45:11.920888+00:00
2024-12-19T06:54:42.091708+00:00
242
false
# Intuition We can use the Array.sort and use the `fn` paramater to get the value that we want to compare. # Approach - This is ascending sort, so we expect `element n` is lesser than `element n+1` by substract `element n` by `element n+1` in the body function of Array.sort. # Complexity - Time complexity: O(n) - Space complexity: O(1) # Code ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a, b) => fn(a) - fn(b)) }; ``` # Result ![Screenshot 2024-12-19 at 2.40.52β€―PM.png](https://assets.leetcode.com/users/images/72384dee-5c3f-43c9-92f4-ac3088f788c5_1734590472.3959045.png)
1
0
['JavaScript']
0
sort-by
99.75 Beats
9975-beats-by-nawaf-rayhan2-09gx
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
Nawaf-Rayhan2
NORMAL
2024-08-03T13:44:42.117395+00:00
2024-08-03T13:44:42.117426+00:00
9
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```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n const sort = arr.sort((a,b) => fn(a) - fn(b))\n return sort\n};\n```
1
0
['JavaScript']
1
sort-by
Beats 84.66% of users with JavaScript
beats-8466-of-users-with-javascript-by-r-lbaz
\n\n# Code\n\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a, b) => fn(a
rudrasaha305
NORMAL
2024-03-09T15:43:40.257227+00:00
2024-03-09T15:43:40.257249+00:00
518
false
\n\n# Code\n```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a, b) => fn(a) - fn(b));\n};\n\n```
1
0
['JavaScript']
1
sort-by
Production grade TS
production-grade-ts-by-stuymedova-s45s
Code\n\nconst sortBy = <I>(arr: I[], fn: (item: I) => number): I[] => {\n return arr.sort((a, b) => fn(a) - fn(b));\n};\n\n
stuymedova
NORMAL
2024-02-13T17:11:44.124374+00:00
2024-08-22T06:11:07.925439+00:00
18
false
# Code\n```\nconst sortBy = <I>(arr: I[], fn: (item: I) => number): I[] => {\n return arr.sort((a, b) => fn(a) - fn(b));\n};\n\n```
1
0
['TypeScript']
0
sort-by
2724. Sort By - Space complexity: O(1)
2724-sort-by-space-complexity-o1-by-ngan-utjb
Intuition\nThe problem involves sorting an array based on the values returned by a given function. The goal is to achieve ascending order according to the funct
nganthudoan2001
NORMAL
2024-01-09T08:02:42.340791+00:00
2024-01-09T08:02:42.340821+00:00
1,147
false
# Intuition\nThe problem involves sorting an array based on the values returned by a given function. The goal is to achieve ascending order according to the function outputs.\n\n# Approach\nThe approach directly uses the `sort()` method on the input array, providing a custom comparison function. This comparison function compares the values returned by the provided function (`fn`) for each element. The sorting is done in place, modifying the original array.\n\n# Complexity\n- Time complexity: O(n * log(n))\n - The `sort()` method has a time complexity of O(n * log(n)) in the worst case.\n- Space complexity: O(1)\n - The sorting is done in place, and no additional space is used other than the input array.\n\n# Code\n```javascript\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n arr.sort((a, b) => {\n return fn(a) - fn(b);\n });\n return arr;\n};\n```
1
0
['JavaScript']
1
sort-by
2724. Sort By - Just 01 line - Beats 95.81% of users with JavaScript (Runtime)
2724-sort-by-just-01-line-beats-9581-of-6m8hg
Intuition\nThe problem requires sorting an array based on the values returned by a given function. The sorting should be done in ascending order according to th
nganthudoan2001
NORMAL
2024-01-09T08:01:32.466713+00:00
2024-01-09T08:01:32.466755+00:00
403
false
# Intuition\nThe problem requires sorting an array based on the values returned by a given function. The sorting should be done in ascending order according to the function outputs.\n\n# Approach\nThe approach involves creating a shallow copy of the input array using `slice()`. This is done to avoid modifying the original array. The `sort()` method is then applied to the copied array, using a custom comparison function. The comparison function compares the values returned by the provided function (`fn`) for each element, ensuring the sorted order based on these values.\n\n# Complexity\n- Time complexity: O(n * log(n)) \n - The `slice()` operation takes O(n) time, and the subsequent `sort()` operation takes O(n * log(n)) time in the worst case.\n- Space complexity: O(n)\n - The shallow copy created using `slice()` requires O(n) space.\n\n# Code\n```javascript\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.slice().sort((a, b) => fn(a) - fn(b));\n};\n```
1
0
['JavaScript']
2
sort-by
1 Line solution (O(n log n))
1-line-solution-on-log-n-by-strix_wl-4api
Complexity\n- Time complexity: O(n log n).\n\n# Code\n\nvar sortBy = function(arr, fn) {\n return arr.sort((a, b) => fn(a) - fn(b))\n};\n
Strix_wl
NORMAL
2023-12-02T04:33:20.598760+00:00
2023-12-02T04:33:20.598788+00:00
402
false
# Complexity\n- Time complexity: O(n log n).\n\n# Code\n```\nvar sortBy = function(arr, fn) {\n return arr.sort((a, b) => fn(a) - fn(b))\n};\n```
1
0
['JavaScript']
0
sort-by
sort by - solution in Quick Sort
sort-by-solution-in-quick-sort-by-velayu-1cm8
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
Velayutham25
NORMAL
2023-11-14T17:24:24.199230+00:00
2023-11-14T17:24:24.199266+00:00
41
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```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function (arr, fn) {\n if (arr.length <= 1) {\n return arr;\n }\n\n let pivot = arr[0];\n let leftArr = [];\n let rightArr = [];\n\n for (let i = 1; i < arr.length; i++) {\n\n if(fn(arr[i]) < fn(pivot)) {\n leftArr.push(arr[i])\n } else {\n rightArr.push(arr[i]);\n }\n }\n\n return [...sortBy(leftArr, fn), pivot, ...sortBy(rightArr, fn)]\n};\n```
1
0
['JavaScript']
0
sort-by
Beats 98.06%of users with JavaScript
beats-9806of-users-with-javascript-by-po-618i
\n> ***var sortBy = function(arr, fn) {\n return arr.sort((a,b) => fn(a) > fn(b) ? 1 : -1);};***\n
PoetryOfCode
NORMAL
2023-11-11T04:05:10.494014+00:00
2023-11-11T04:05:10.494035+00:00
9
false
```\n> ***var sortBy = function(arr, fn) {\n return arr.sort((a,b) => fn(a) > fn(b) ? 1 : -1);};***\n```
1
0
['JavaScript']
0
sort-by
JavaScript Sort By
javascript-sort-by-by-samabdullaev-l045
Intuition\n Describe your first thoughts on how to solve this problem. \nWe need to return a sorted array, where the sorting is based on the output of a given f
samabdullaev
NORMAL
2023-11-09T15:47:46.737374+00:00
2023-11-09T15:47:46.737395+00:00
10
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to return a sorted array, where the sorting is based on the output of a given function, which exclusively returns numbers, ensuring the sorted array is in ascending order according to the function\'s output.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. These are comment delimiters for a multi-line comment to help explain and document code while preventing ignored text from executing. These comments are commonly used in formal documentation for better code understanding.\n\n ```\n /**\n * Multi-line comment\n */\n ```\n\n2. This is a special type of comment called a JSDoc comment that explains that the function should take parameters named `arr` and `fn`, which are expected to be an `Array` and a `Function`.\n\n ```\n @param {Array} arr\n @param {Function} fn\n ```\n\n3. This is a special type of comment called a JSDoc comment that explains what the code should return, which, in this case, is an `Array`. It helps developers and tools like code editors and documentation generators know what the function is supposed to produce.\n\n ```\n @return {Array}\n ```\n\n4. This is how we define a function named `sortBy` that takes an array `arr` and a function `fn` as its arguments.\n\n ```\n var sortBy = function(arr, fn) {\n // code to be executed\n };\n ```\n\n5. This function returns the array sorted in ascending order, where the sorting is determined by the output of the function `fn` applied to each element (`a` and `b`).\n\n ```\n return arr.sort((a, b) => fn(a) - fn(b));\n ```\n\n# Complexity\n- Time complexity: $O(n log n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n`n` is the length of the input array. This is because the function uses the `sort` method, which has a time complexity of $O(n log n)$ in the average case.\n\n- Space complexity: $O(1)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThis is because the function does not use any additional data structures that grow with the size of the input array.\n\n# Code\n```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a, b) => fn(a) - fn(b));\n};\n```
1
0
['JavaScript']
0
sort-by
Merge Sort
merge-sort-by-shivam-agrahari-t92c
Approach\nusing mergesort algorithm\n\n# Complexity\n- Time complexity: nlog(n)\n\n- Space complexity: nlog(n)\n\n# Code\n/**\n * @param {Array} arr #- The inpu
shivam-agrahari
NORMAL
2023-09-16T05:58:02.104613+00:00
2023-09-16T05:58:43.738992+00:00
106
false
# Approach\nusing mergesort algorithm\n\n# Complexity\n- Time complexity: nlog(n)\n\n- Space complexity: nlog(n)\n\n# Code\n```/**\n * @param {Array} arr #- The input array to be sorted.\n * @param {Function} fn #- A custom comparison function used for sorting.\n * @return {Array} #- A new array containing the sorted elements.\n */\nvar sortBy = function (arr, fn) {\n return mergesort(0, arr.length - 1, arr, fn); // Call the merge sort algorithm with initial parameters.\n};\n\nfunction mergesort(s, e, arr, fn) {\n if (s >= e) return; // If the array size is 0 or 1, it\'s already sorted, so return.\n let m = Math.floor((s + e) / 2); // Calculate the middle index.\n mergesort(s, m, arr, fn); // Recursively sort the left half.\n mergesort(m + 1, e, arr, fn); // Recursively sort the right half.\n merge(s, m, e, arr, fn); // Merge the two sorted halves.\n}\n\nfunction merge(s, m, e, arr, fn) {\n let arr1 = arr.slice(s, m + 1); // Create a copy of the left subarray.\n let arr2 = arr.slice(m + 1, e + 1); // Create a copy of the right subarray.\n let i = 0,\n j = 0,\n st = s;\n while (i < arr1.length && j < arr2.length) {\n if (fn(arr1[i]) < fn(arr2[j])) {\n arr[st] = arr1[i]; // Place the smaller element from arr1 into the result array.\n i++;\n } else {\n arr[st] = arr2[j]; // Place the smaller element from arr2 into the result array.\n j++;\n }\n st++;\n }\n while (i < arr1.length) {\n arr[st] = arr1[i]; // Copy any remaining elements from arr1.\n i++;\n st++;\n }\n while (j < arr2.length) {\n arr[st] = arr2[j]; // Copy any remaining elements from arr2.\n j++;\n st++;\n }\n}\n\n```
1
0
['Merge Sort', 'JavaScript']
0
sort-by
return arr.sort((a, b) => fn(a) - fn(b))
return-arrsorta-b-fna-fnb-by-pbelskiy-js3o
js\nvar sortBy = function(arr, fn) {\n return arr.sort((a, b) => fn(a) - fn(b));\n};\n
pbelskiy
NORMAL
2023-06-27T10:44:58.236615+00:00
2023-06-27T10:44:58.236647+00:00
230
false
```js\nvar sortBy = function(arr, fn) {\n return arr.sort((a, b) => fn(a) - fn(b));\n};\n```
1
0
[]
0
sort-by
Easy One Line Solution || JavaScript 🎁🎁
easy-one-line-solution-javascript-by-del-qo6b
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
deleted_user
NORMAL
2023-06-07T08:54:25.720655+00:00
2023-06-07T08:54:25.720687+00:00
2,163
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```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nconst sortBy = (arr, fn) => Array.from(arr).sort((a, b) => fn(a) > fn(b) ? 1 : -1);\n```
1
0
['JavaScript']
2
sort-by
Sort By
sort-by-by-naeem_abd-pu70
IntuitionApproachComplexity Time complexity: Space complexity: Code
Naeem_ABD
NORMAL
2025-04-10T11:45:04.690818+00:00
2025-04-10T11:45:04.690818+00:00
2
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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a,b) => fn(a) - fn(b)) }; ```
0
0
['JavaScript']
0
sort-by
2724. Sort By Solution
2724-sort-by-solution-by-runl4avdwj-vm0d
IntuitionThis problem is focused on custom sorting using higher-order functions. We are required to implement a utility function sortBy(arr, fn) that: Sorts an
runl4AVDwJ
NORMAL
2025-04-07T15:35:14.704836+00:00
2025-04-07T15:35:14.704836+00:00
3
false
# **Intuition** This problem is focused on **custom sorting using higher-order functions**. We are required to implement a utility function `sortBy(arr, fn)` that: - Sorts an array **based on a transformation** applied to each element using a callback function `fn`. - The goal is to allow **dynamic and flexible sorting** criteria, depending on the logic inside `fn`. Understanding this helps improve skills in **custom comparator functions**, which is a vital part of advanced array manipulations in JavaScript. --- # **Understanding `sort()` in JavaScript** βœ… **What is `Array.prototype.sort()`?** The `sort()` method sorts the elements of an array **in place** and returns the sorted array. It takes an **optional compare function** to determine the sort order. βœ… **Why use a custom comparator?** Custom comparator functions are essential when: - Sorting objects or values **based on derived criteria** - You need **ascending/descending** control - You want to **sort dynamically** based on external logic --- # **Approach** We explored **two main approaches** for implementing the `sortBy` function. --- # πŸ”Ή **Approach 1: Simple Arithmetic Comparator** ```js var sortBy = function(arr, fn) { return arr.sort((a, b) => fn(a) - fn(b)); }; ``` πŸ“Œ **Explanation:** - This approach is valid when `fn(a)` and `fn(b)` return **numeric values**. - Subtracting `fn(a) - fn(b)` directly gives: - Negative β†’ `a` comes before `b` - Positive β†’ `b` comes before `a` - Zero β†’ keep original order βœ… **Pros:** - Very concise and elegant - Ideal for numeric transformations ❗ **Note:** Not ideal if `fn()` returns strings or complex types. --- # πŸ”Ή **Approach 2: Boolean-Based Comparator** ```js var sortBy = function(arr, fn) { return arr.sort((a, b) => fn(a) > fn(b) ? 1 : -1); }; ``` πŸ“Œ **Explanation:** - Compares `fn(a)` and `fn(b)` using `>` operator - If `fn(a)` is greater β†’ returns `1` (a goes after b) - Otherwise β†’ returns `-1` (a goes before b) βœ… **Pros:** - Works well for **strings, booleans**, and other comparable values - Safer in some non-numeric cases ❗ **Note:** This does not handle **equality cases** explicitly. --- # **Complexity Analysis** - **Time Complexity:** - $$O(n \log n)$$ – Standard time for array sorting - **Space Complexity:** - $$O(1)$$ – In-place sorting, no extra space required --- # **Code Implementation** ```js /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a, b) => fn(a) > fn(b) ? 1 : -1); }; ``` --- # **Important Topics to Learn πŸ“š** - **Array.prototype.sort()**: How JavaScript sorts arrays under the hood - **Custom Comparator Functions**: Writing flexible sorting logic - **Higher-Order Functions**: Passing behavior through callbacks - **Stable Sorts**: Maintaining order when values are equal - **Arrow Functions**: Simplifying function syntax --- # πŸš€ **Support & Feedback** βœ… If you found this helpful, **drop an upvote & share your thoughts**! πŸ’¬ Let’s discuss alternate ways to solve this or make it more generic! πŸ‘‡ ---
0
0
['JavaScript']
0
sort-by
array.prototype.solution
arrayprototypesolution-by-gvictorlo-b4ac
IntuitionSince it was not limited to being able to use native js functions, thinking about doing the sorting "from scratch" seemed very complex, especially sinc
GVictorLO
NORMAL
2025-04-07T03:22:14.404608+00:00
2025-04-07T03:22:14.404608+00:00
3
false
# Intuition Since it was not limited to being able to use native js functions, thinking about doing the sorting "from scratch" seemed very complex, especially since the array could be made up of objects, numbers, strings, etc. So it was more intuitive to use the js sort method approach. # Approach solution using array.prototype.sort # Complexity - Time complexity: O(nlogn) - Space complexity: O(n) # Code ```typescript [] type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue }; type Fn = (value: JSONValue) => number function sortBy(arr: JSONValue[], fn: Fn): JSONValue[] { return arr.sort((a :JSONValue, b :JSONValue) => fn(a)-fn(b)) }; ```
0
0
['TypeScript']
0
sort-by
Sort By
sort-by-by-shalinipaidimuddala-8el2
IntuitionApproachComplexity Time complexity: Space complexity: Code
ShaliniPaidimuddala
NORMAL
2025-03-25T08:59:00.078911+00:00
2025-03-25T08:59:00.078911+00:00
2
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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ const sortBy = (arr, fn) => arr.toSorted((a, b) => fn(a) - fn(b)); ```
0
0
['JavaScript']
0
sort-by
2724. Sort By
2724-sort-by-by-h3thal-i6vi
IntuitionApproachComplexity Time complexity: Space complexity: Code
H3thal
NORMAL
2025-03-24T18:27:53.094341+00:00
2025-03-24T18:27:53.094341+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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = (arr, fn) => arr.sort((a, b) => fn(a) - fn(b)); ```
0
0
['JavaScript']
0
sort-by
Solution Sort By
solution-sort-by-by-aprydatko-239d
Code
aprydatko
NORMAL
2025-03-22T11:01:26.678132+00:00
2025-03-22T11:01:26.678132+00:00
2
false
# Code ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((first, second ) => fn(first) > fn(second) ? 1 : -1) }; ```
0
0
['JavaScript']
0
sort-by
Simple solution
simple-solution-by-itziks00-27cl
Code
itziks00
NORMAL
2025-03-20T18:56:14.603091+00:00
2025-03-20T18:56:14.603091+00:00
3
false
# Code ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { arr.sort(function(a, b){ return fn(a) - fn(b) }) return arr }; ```
0
0
['JavaScript']
0
sort-by
85 m/s runtime
85-ms-runtime-by-lhcee3-s3eu
IntuitionThe problem requires sorting an array based on the values returned by a given function fn. Since fn only returns unique numbers for different elements,
lhcee3
NORMAL
2025-03-20T09:57:09.904672+00:00
2025-03-20T09:57:09.904672+00:00
3
false
# Intuition The problem requires sorting an array based on the values returned by a given function fn. Since fn only returns unique numbers for different elements, we can use a simple sorting algorithm that compares these numerical outputs. JavaScript’s built-in .sort() method provides an efficient way to achieve this. # Approach Use .sort(): .sort((a, b) => fn(a) - fn(b)) ensures ascending order sorting. fn(a) and fn(b) return numerical values that dictate the order. Since the numbers are unique, no need to handle duplicates. Sorting Logic: If fn(a) < fn(b), the element a comes before b. If fn(a) > fn(b), the element b comes before a. This approach works for numbers, objects, or nested arrays, as long as fn extracts a valid numeric key. # Complexity Time Complexity: Sorting operation: The .sort() method in JavaScript uses Timsort, which has an average and worst-case complexity of O(n log n). Function calls: The function fn() is called for each element, adding an extra O(n) overhead. Overall complexity: O(n log n). Space Complexity: .sort() performs in-place sorting, meaning it does not require extra space beyond the input array. The function fn() may create temporary values but does not store extra copies of the array. Overall space complexity: O(1) (if sorting in place) or O(n) (if the sorting algorithm creates a copy internally). # Code ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a, b) => fn(a) - fn(b)); }; ```
0
0
['JavaScript']
0
sort-by
Sort Problem Solve
sort-problem-solve-by-ariyaneiasin02-qrw3
IntuitionApproachComplexity Time complexity: Space complexity: Code
ariyanEiasin02
NORMAL
2025-03-13T03:43:06.834024+00:00
2025-03-13T03:43:06.834024+00:00
5
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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a,b)=> fn(a) - fn(b)) }; ```
0
0
['JavaScript']
0
sort-by
Simple Solution 100%
simple-solution-100-by-soumya15-n7x6
IntuitionApproachComplexity Time complexity: Space complexity: Code
Soumya15
NORMAL
2025-03-10T04:24:25.609254+00:00
2025-03-10T04:24:25.609254+00:00
6
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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a,b) => fn(a) - fn(b)) }; ```
0
0
['JavaScript']
0
sort-by
1 Line of code.πŸ‘‰
1-line-of-code-by-tiy1orr5gx-ekam
IntuitionApproachComplexity Time complexity: Space complexity: Code
TiY1orr5Gx
NORMAL
2025-03-07T03:34:14.125358+00:00
2025-03-07T03:34:14.125358+00:00
3
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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a,b) =>fn(a) - fn(b)); }; ```
0
0
['JavaScript']
0
sort-by
Lets go sorting!
lets-go-sorting-by-ecabigting-nvqr
IntuitionApproachComplexity Time complexity: Space complexity: Code
ecabigting
NORMAL
2025-03-05T07:09:50.829135+00:00
2025-03-05T07:09:50.829135+00:00
4
false
# Intuition # 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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { const mapped = arr.map((element)=>[fn(element),element]) mapped.sort((a,b)=>a[0] - b[0]) const sortedArray = mapped.map((pair)=>pair[1]) return sortedArray }; ```
0
0
['JavaScript']
0
sort-by
Very simple with one line πŸ”₯πŸ”₯
very-simple-with-one-line-by-abdullah_ua-ithk
IntuitionApproachComplexity Time complexity: Space complexity: Code
Abdullah_UA
NORMAL
2025-03-05T06:21:16.678175+00:00
2025-03-05T06:21:16.678175+00:00
3
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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a,b)=>fn(a)-fn(b)) }; ```
0
0
['JavaScript']
0
sort-by
Efficient JavaScript solution
efficient-javascript-solution-by-jayanth-a8h3
IntuitionApproachComplexity Time complexity: Space complexity: Code
jayanth_br
NORMAL
2025-03-04T04:19:13.595836+00:00
2025-03-04T04:19:13.595836+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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { arr.sort((a, b) => fn(a) - fn(b)) return arr; }; ```
0
0
['JavaScript']
0
sort-by
Solution
solution-by-aradhanadevi_jadeja-khww
Code
Aradhanadevi_Jadeja
NORMAL
2025-02-28T11:23:49.195166+00:00
2025-02-28T11:23:49.195166+00:00
3
false
# Code ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a, b) => fn(a) - fn(b)); }; console.log(sortBy([5, 4, 1, 2, 3], x => x)); console.log(sortBy([{x: 1}, {x: 0}, {x: -1}], d => d.x)); console.log(sortBy([[3, 4], [5, 2], [10, 1]], x => x[1])); ```
0
0
['JavaScript']
0
sort-by
Sort By - 30 Days of JavaScript
sort-by-30-days-of-javascript-by-aleksan-7k63
IntuitionApproachComplexity Time complexity: Space complexity: Code
AleksanderP
NORMAL
2025-02-24T09:49:22.925792+00:00
2025-02-24T09:49:22.925792+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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort(function(a, b) { return fn(a) - fn(b); }); }; ```
0
0
['JavaScript']
0
sort-by
Best & Simple solution ever | 97 ms - Beats 99.94%
best-simple-solution-ever-97-ms-beats-99-ak56
Code
Mathinraj
NORMAL
2025-02-20T11:48:45.024356+00:00
2025-02-20T11:48:45.024356+00:00
3
false
# Code ```javascript [] var sortBy = function(arr, fn) { return arr.sort((a,b) => fn(a) - fn(b)) }; ```
0
0
['JavaScript']
0
sort-by
Simple Solution Easy to understand
simple-solution-easy-to-understand-by-en-7b3u
IntuitionApproachComplexity Time complexity: Space complexity: Code
eng-rehman
NORMAL
2025-02-19T05:48:37.485145+00:00
2025-02-19T05:48:37.485145+00:00
3
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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a,b) => fn(a) - fn(b)) }; ```
0
0
['JavaScript']
0
sort-by
easy javascript solution
easy-javascript-solution-by-haneen_ep-ic17
IntuitionApproachComplexity Time complexity: Space complexity: Code
haneen_ep
NORMAL
2025-02-18T01:25:01.236489+00:00
2025-02-18T01:25:01.236489+00:00
5
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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a,b) => fn(a) - fn(b)); }; ```
0
0
['JavaScript']
0
sort-by
one line output in JavaScript and typescript
one-line-output-in-javascript-and-typesc-743v
IntuitionApproachComplexity Time complexity: Space complexity: Code
Barath_Balasubramanian
NORMAL
2025-02-05T13:06:33.066156+00:00
2025-02-05T13:06:33.066156+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: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```typescript [] type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue }; type Fn = (value: JSONValue) => number function sortBy(arr: JSONValue[], fn: Fn): JSONValue[] { return arr.sort((a, b) => fn(a) - fn(b)); }; ```
0
0
['TypeScript', 'JavaScript']
0
sort-by
Beat 91% | Easy JS solution
beat-91-easy-js-solution-by-nitinkumar-1-ld4a
Code
nitinkumar-19
NORMAL
2025-02-01T20:05:14.823466+00:00
2025-02-01T20:05:14.823466+00:00
7
false
# Code ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a,b)=>fn(a)-fn(b)); }; ```
0
0
['JavaScript']
0
sort-by
JS - using (sort function with compare function in it).
js-using-sort-function-with-compare-func-6xsp
IntuitionApproachComplexity Time complexity: Space complexity: Code
Manmohan_Choudhary
NORMAL
2025-01-30T17:46:59.427888+00:00
2025-01-30T17:46:59.427888+00:00
6
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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a,b)=> fn(a)-fn(b)); }; ```
0
0
['JavaScript']
0
sort-by
LS: #2724
ls-2724-by-jaalle-cbrt
IntuitionApproachComplexity Time complexity: Space complexity: Code
jaalle
NORMAL
2025-01-25T19:22:45.903383+00:00
2025-01-25T19:22:45.903383+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 ```typescript [] type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue }; type Fn = (value: JSONValue) => number function sortBy(arr: JSONValue[], fn: Fn): JSONValue[] { //let sortedArr: JSONValue[] = arr.toSorted((a, b) => fn(a) - fn(b)); let sortedArr: JSONValue[] = arr.sort((a, b) => fn(a) - fn(b)); return sortedArr; }; ``` ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ function sortBy(arr, fn) { //let sortedArr = arr.toSorted((a, b) => fn(a) - fn(b)); var sortedArr = arr.sort((a, b) => fn(a) - fn(b)); return sortedArr; } ```
0
0
['TypeScript', 'JavaScript']
0
sort-by
Sort By Solution.
sort-by-solution-by-johanc12-8ss0
IntuitionJust use sort method by subtracting fn(a) - fn(b)Code
johanc12
NORMAL
2025-01-24T02:42:11.555295+00:00
2025-01-24T02:42:11.555295+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Just use sort method by subtracting `fn(a) - fn(b)` # Code ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a, b) => fn(a) - fn(b)); }; ```
0
0
['JavaScript']
0
sort-by
Runtime 143 ms Beats 6.31% & Memory 70.26 MB Beats 5.34%
runtime-143-ms-beats-631-memory-7026-mb-mnjwj
IntuitionThe sortBy function sorts an array of elements based on the return value of a user-provided function fn. I decided to use the Quick Sort algorithm to r
bekcodingaddict
NORMAL
2025-01-23T08:38:52.696963+00:00
2025-01-23T08:38:52.696963+00:00
4
false
# Intuition The sortBy function sorts an array of elements based on the return value of a user-provided function fn. I decided to use the Quick Sort algorithm to recursively partition the array into smaller sub-arrays. # Approach Base Case: If the input array has 0 or 1 element, it is already sorted, so return it. Pivot Selection: The function selects the last element of the array as the pivot. Partitioning: The function iterates through all elements except the pivot. It compares the result of applying fn to each element with fn(pivot). Elements for which fn(arr[i]) is less than fn(pivot) are added to the left sub-array. Elements for which fn(arr[i]) is greater than or equal to fn(pivot) are added to the right sub-array. Recursive Sorting: The function recursively applies the same process to the left and right sub-arrays, and then combines the sorted left sub-array, the pivot, and the sorted right sub-array to return the fully sorted array. # Complexity - Time complexity: - Best Case: If the pivot divides the array into two equal halves at each step, the time complexity is O(n log n). This happens when the array is evenly partitioned. - Worst Case: If the array is already sorted or reverse sorted, the pivot produces highly unbalanced partitions, resulting in a time complexity of O(nΒ²). - Average Case: On average, the time complexity is O(n log n). - Space complexity: - Auxiliary Space: The space complexity of the sortBy function is O(n) due to the space required for: The recursive call stack (up to O(log n) calls in the best case). Temporary storage for the left and right sub-arrays (which can sum up to O(n) across recursive calls). - Overall Space Complexity: O(n). # Code ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function (arr, fn) { // Base case: arrays with 0 or 1 element are already sorted if (arr.length <= 1) { return arr; } // Choose a pivot element (here, the last element) const pivot = arr[arr.length - 1]; // Arrays to hold the elements less than and greater than the pivot const left = []; const right = []; // Partition the array into left and right sub-arrays for (let i = 0; i < arr.length - 1; i++) { if (fn(arr[i]) < fn(pivot)) { left.push(arr[i]); } else { right.push(arr[i]); } } // Recursively sort the left and right sub-arrays, and combine with the pivot return [...sortBy(left, fn), pivot, ...sortBy(right, fn)]; }; ```
0
0
['JavaScript']
0
sort-by
Simple Solution with explanation of the program and approach to solve the problem step by step
simple-solution-with-explanation-of-the-fplhn
IntuitionUnderstand the given condition and think the logic to the given problem and the return value.ApproachWe just have to return the sorted array.Program Br
Shashankpatelc
NORMAL
2025-01-21T04:58:57.841736+00:00
2025-01-21T04:58:57.841736+00:00
6
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Understand the given condition and think the logic to the given problem and the return value. - - - # Approach <!-- Describe your approach to solving the problem. --> We just have to return the sorted array. - - - # Program Breakdown ` arr` is a array which we have to sort. `fn` is a function that return a number which we pass to it. - - - # Program Breakdown **THIS IS A BREAKDOWN OF THE PROGRAM GIVEN BELLOW** - We have to retun a sorted array so we use only 1 line to sort and return the array by using in-buit function ` sort()`. - `return arr.sort((a,b)=>fn(a)-fn(b))` which sort and return the array. - `arr.sort()` sort the array based on the arrow functin `(a,b)=> fn(a) - fn(b)`.where `a` and `b` are the arguments represent the 2 elemens of the `arr` array. - `fn(a) - fn(b)` return a number which may be a positive or negetive number. If it return a positive number it sort `b` first and then `a`. If it return a negetive number it sort `a` first and them `b`.This contuinue ntil all elements are over in `arr` array. - - - # Complexity - Time complexity: $$O(n$$ $$log$$ $$n)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> The time complexity of the `sort` method in JavaScript is generally O(n log n) on average, where n is the number of elements in the array. This is because the sorting algorithm used (typically a variation of quicksort or mergesort) has an average-case time complexity of O(n log n) - Space complexity: $$O(n)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> The space complexity of the `sort` method is O(n) in the worst case due to the need for additional space for the sorting algorithm's operations. - - - # Code ```javascript [] var sortBy = function(arr, fn) { return arr.sort( (a, b) => fn(a) - fn(b)) }; ``` - - -
0
0
['JavaScript']
0
sort-by
One Line Solution
one-line-solution-by-kovilapuvivek-jxds
IntuitionApproachComplexity Time complexity: Space complexity: Code
KovilapuVivek
NORMAL
2025-01-17T16:25:42.744434+00:00
2025-01-17T16:25:42.744434+00:00
5
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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a,b)=>fn(a)-fn(b)); }; ```
0
0
['JavaScript']
0
sort-by
Solution in Javascript with decent memory and space complexity
solution-in-javascript-with-decent-memor-r4y8
Complexity Time complexity: Sorting an array has a worst-case time complexity of 𝑂(nlogn), where n is the length of the array. Space complexity: Average case
Mradulesh_Morya
NORMAL
2025-01-17T13:39:10.821565+00:00
2025-01-17T13:39:10.821565+00:00
6
false
# Complexity - Time complexity: Sorting an array has a worst-case time complexity of 𝑂(nlogn), where n is the length of the array. - Space complexity: Average case: O(log n) # Code ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a,b)=> fn(a)-fn(b)) }; ```
0
0
['JavaScript']
0
sort-by
Sorting Array Using a Comparator Function
sorting-array-using-a-comparator-functio-44cp
IntuitionApproachComplexity Time complexity: Space complexity: Code
chris0403
NORMAL
2025-01-16T06:08:42.850294+00:00
2025-01-16T06:08:42.850294+00:00
3
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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a,b)=>fn(a)-fn(b)) }; ```
0
0
['JavaScript']
0
sort-by
Easy approach πŸ”₯πŸ”₯
easy-approach-by-rajasibi-wc3d
IntuitionApproachComplexity Time complexity: Space complexity: Code
RajaSibi
NORMAL
2025-01-16T05:51:30.746409+00:00
2025-01-16T05:51:30.746409+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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a,b)=>fn(a)-fn(b)) }; ```
0
0
['JavaScript']
0
sort-by
Sort By simple solution βœ…πŸš€
sort-by-simple-solution-by-its_me_1-ceqi
IntuitionSorting an array based on a computed value for each element is a common task. The sortBy function takes an array and a callback function (fn), which de
its_me_1
NORMAL
2025-01-14T02:11:57.627466+00:00
2025-01-14T02:11:57.627466+00:00
5
false
# Intuition Sorting an array based on a computed value for each element is a common task. - The `sortBy` function takes an array and a callback function (`fn`), which determines the sort key for each element. - The key idea is to compare elements based on the value returned by the callback function. # Approach - **Use JavaScript's `Array.prototype.sort`**: - The `sort` method sorts elements in place and accepts a comparator function. - **Define the Comparator Function**: - For each pair of elements, apply the callback function (`fn`) to compute their respective sort keys. - Compare the keys: - If the key for the first element is smaller, return `1`. - If the key for the second element is smaller, return `1`. - If both keys are equal, return `0`. - **Return the Sorted Array**: - The `sort` method rearranges the elements based on the comparator logic and returns the sorted array. # Complexity - Time complexity: - Sorting Complexity: Sorting involves comparisons, leading to a time complexity of 𝑂(𝑛log - ⁑Key Calculation: The callback function (fn) is called for each comparison, which happens 𝑂(𝑛log𝑛)O(nlogn) times. - Space complexity: - Sorting is done in place, so no extra space is required for the array itself. However, the function calls for fn may require stack space depending on its implementation. # Code ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { function swap(a, b) { return (fn(a) < fn(b)) ? -1 : 1 } return arr.sort(swap) }; ```
0
0
['JavaScript']
0
sort-by
Javascript SortBy sollution
javascript-sortby-sollution-by-pankaj376-xing
IntuitionApproachComplexity Time complexity: Space complexity: Code
pankaj3765
NORMAL
2025-01-12T14:29:39.767398+00:00
2025-01-12T14:29:39.767398+00:00
3
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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a, b)=> fn(a) -fn(b)); }; ```
0
0
['JavaScript']
0
sort-by
Sort
sort-by-wnascimento-a7mg
IntuitionApproachComplexity Time complexity: Space complexity: Code
wNascimento
NORMAL
2025-01-06T23:26:22.890298+00:00
2025-01-06T23:26:22.890298+00:00
5
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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a, b) => fn(a) - fn(b)); }; ```
0
0
['JavaScript']
0
sort-by
2724. Sort By
2724-sort-by-by-g8xd0qpqty-0dff
IntuitionApproachComplexity Time complexity: Space complexity: Code
G8xd0QPqTy
NORMAL
2025-01-06T17:41:09.709087+00:00
2025-01-06T17:41:09.709087+00:00
5
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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a, b) => fn(a) - fn(b)); }; ```
0
0
['JavaScript']
0
sort-by
#2724: Sort By
2724-sort-by-by-dheeraj7321-fv95
IntuitionThe main idea behind solving this problem is to leverage JavaScript's built-in sort() method and customize it to sort elements based on a computed valu
Dheeraj7321
NORMAL
2025-01-03T11:50:32.249469+00:00
2025-01-03T11:50:32.249469+00:00
4
false
# Intuition The main idea behind solving this problem is to leverage JavaScript's built-in `sort()` method and customize it to sort elements based on a computed value using a function. The `sort()` method allows flexibility in defining sorting criteria by passing a comparator function. # Approach 1. The `sortBy` function takes two parameters: an array `arr` and a function `fn`. 2. It applies the `sort()` method on the array and provides a custom comparator function. 3. The comparator function takes two arguments, `a` and `b`, and uses `fn(a)` and `fn(b)` to determine their relative order. 4. The comparator returns the difference between `fn(a)` and `fn(b)` to sort the array in ascending order based on the computed values. 5. The original array is modified and returned as the sorted array. # Complexity - **Time Complexity**: - The sorting operation has a time complexity of $$O(n \log n)$$, where \(n\) is the size of the input array. - Applying the function `fn` to each element during the comparison adds a constant-time overhead, which does not change the overall complexity. - **Space Complexity**: - The space complexity is $$O(1)$$ additional space since the sorting is performed in place. However, the `sort()` method may use internal stack space for recursion, which depends on the JavaScript engine implementation. # Code ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a, b) => fn(a) - fn(b)); }; ```
0
0
['JavaScript']
0
sort-by
Easy one line solutions
easy-one-line-solutions-by-virendangi123-0s1c
IntuitionApproachComplexity Time complexity: Space complexity: Code
Virendangi123
NORMAL
2024-12-24T12:56:47.750274+00:00
2024-12-24T12:56:47.750274+00:00
5
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 ```javascript [] /** * @param {Array} arr * @param {Function} fn * @return {Array} */ var sortBy = function(arr, fn) { return arr.sort((a, b) => fn(a) - fn(b)); }; ```
0
0
['JavaScript']
0
sort-by
Sort By
sort-by-by-vitalii_baidak-7cy1
Code
vitalii_baidak
NORMAL
2024-12-20T08:03:49.933653+00:00
2024-12-20T08:03:49.933653+00:00
6
false
# Code ```typescript [] type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue }; type Fn = (value: JSONValue) => number function sortBy(arr: JSONValue[], fn: Fn): JSONValue[] { return arr.sort((a, b) => fn(a) - fn(b)); }; ```
0
0
['TypeScript']
0
sort-by
Basic approach ...!
basic-approach-by-vineeth_v_s-3h8l
IntuitionApproachComplexity Time complexity: Space complexity: Code
Vineeth_V_S
NORMAL
2024-12-18T05:13:42.286258+00:00
2024-12-18T05:13:42.286258+00:00
4
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```javascript []\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a,b) => fn(a) - fn(b))\n};\n\n\n```
0
0
['JavaScript']
0
sort-by
2724. Sort By
2724-sort-by-by-anikaleet-0qq2
IntuitionApproachExplanation: 1- Copying the Array:arr.slice() creates a shallow copy of the original array. This ensures the original array remains unchanged d
Anikaleet
NORMAL
2024-12-17T10:32:06.960301+00:00
2024-12-17T10:32:06.960301+00:00
5
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**Explanation:**\n1- Copying the Array:\n\n**arr.slice()** creates a shallow copy of the original array. This ensures the original array remains unchanged during the sort operation.\n\n2- Sorting Logic:\n**.sort((a, b) => fn(a) - fn(b))** sorts the copied array. The sort function compares elements a and b by applying the function fn to each element:\n\nIf **fn(a) < fn(b)**, the result is negative, and a comes before b.\n\nIf **fn(a) > fn(b)**, the result is positive, and a comes after b.\n\nIf **fn(a) === fn(b)**, the result is zero, and the order remains unchanged.\n\n# Complexity\n- Time complexity:- O(nlogn)\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# Code\n```javascript []\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n //bas array ko sort krna h chote se function se slice methode array ke copy return krta h \n return arr.slice().sort((a, b) => fn(a) - fn(b)) // a>b to negative result \n \n\n};\n```
0
0
['JavaScript']
0
sort-by
Sort By (JS)
sort-by-js-by-123malay-lb92
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
123Malay
NORMAL
2024-12-08T06:33:56.655089+00:00
2024-12-08T06:33:56.655134+00:00
3
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```javascript []\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nconst sortBy = (arr, fn) => arr.sort((a, b) => fn(a) - fn(b));\n```
0
0
['JavaScript']
0
sort-by
Simple Way To Solve
simple-way-to-solve-by-anushanarc-pcrb
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
anushanarc
NORMAL
2024-12-04T12:18:44.124307+00:00
2024-12-04T12:18:44.124335+00:00
4
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```javascript []\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a,b)=>fn(a)-fn(b))\n};\n```
0
0
['JavaScript']
0
sort-by
Js Easy
js-easy-by-hacker_bablu_123-qgt2
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires sorting an array based on a custom comparison function. The idea i
Hacker_Bablu_123
NORMAL
2024-12-02T17:17:04.645943+00:00
2024-12-02T17:17:04.645977+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires sorting an array based on a custom comparison function. The idea is to use JavaScript\'s built-in Array.prototype.sort() function and customize the comparison logic using the function fn provided as an argument.\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse the sort method:\n\nThe sort method is a natural choice for sorting an array as it allows custom comparator functions.\nCustom Comparator:\n\nFor each element in the array, apply the provided function fn.\nUse the result of fn to determine the sorting order.\nSpecifically, the comparator fn(a) - fn(b) calculates the difference between the results of fn applied to two elements, a and b, determining their order.\nReturn the Sorted Array:\n\nAfter sorting, the modified array is returned.\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```javascript []\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a,b)=>fn(a)-fn(b))\n \n};\n```
0
0
['JavaScript']
0
sort-by
One line
one-line-by-himanshusaini0345-5oc1
\n# Code\ntypescript []\ntype JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };\ntype Fn = (value: JSONValue) => number
himanshusaini0345
NORMAL
2024-11-28T11:23:04.821387+00:00
2024-11-28T11:23:04.821416+00:00
2
false
\n# Code\n```typescript []\ntype JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };\ntype Fn = (value: JSONValue) => number\n\nfunction sortBy(arr: JSONValue[], fn: Fn): JSONValue[] {\n return arr.sort((a,b) => fn(a) - fn(b))\n};\n```
0
0
['TypeScript']
0
sort-by
Easy and understandable solution.
easy-and-understandable-solution-by-azim-ph20
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
AzimovAsadbek
NORMAL
2024-11-18T19:27:06.969033+00:00
2024-11-18T19:27:06.969063+00:00
3
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```javascript []\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n return arr.sort((a,b) => fn(a) - fn(b))\n};\n```
0
0
['JavaScript']
0