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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
flatten-deeply-nested-array | 100% recursive memoization | 100-recursive-memoization-by-mailmeaaqib-oylc | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nRecursion \n\n# Complex | mailmeaaqib | NORMAL | 2023-04-12T11:07:56.543186+00:00 | 2023-04-21T16:02:14.807238+00:00 | 2,363 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nRecursion \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 {any[]} arr\n * @param {number} depth\n * @return {any[]}\n */\nvar flat = function (arr, n) {\n if(n==0) return arr;\n let result = [];\n const traverse = (a, n) => {\n for(let i in a) {\n if(n>0 && Array.isArray(a[i]))\n traverse(a[i], n-1)\n else\n result.push(a[i])\n }\n }\n traverse(arr, n);\n return result;\n};\n``` | 2 | 0 | ['JavaScript'] | 1 |
flatten-deeply-nested-array | Recursive solution | recursive-solution-by-bahoang3105-h236 | Code\n\n/**\n * @param {any[]} arr\n * @param {number} depth\n * @return {any[]}\n */\nvar flat = function (arr, n) {\n if (n === 0) return arr;\n let res = [ | bahoang3105 | NORMAL | 2023-04-12T06:44:26.478857+00:00 | 2023-04-14T03:14:29.957743+00:00 | 1,118 | false | # Code\n```\n/**\n * @param {any[]} arr\n * @param {number} depth\n * @return {any[]}\n */\nvar flat = function (arr, n) {\n if (n === 0) return arr;\n let res = [];\n for (let i = 0; i < arr.length; i++) {\n if (Array.isArray(arr[i])) {\n res.push(...flat(arr[i], n-1));\n } else {\n res.push(arr[i]);\n }\n }\n return res;\n};\n``` | 2 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | JavaScript | javascript-by-adchoudhary-4a8l | Code | adchoudhary | NORMAL | 2025-03-03T01:39:57.595423+00:00 | 2025-03-03T01:39:57.595423+00:00 | 182 | false | # Code
```javascript []
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
const stack = [...arr.map(item => [item, n])];
const result = [];
while (stack.length > 0) {
const [item, depth] = stack.pop();
if (Array.isArray(item) && depth > 0) {
stack.push(...item.map(subItem => [subItem, depth - 1]));
} else {
result.push(item);
}
}
return result.reverse();
};
``` | 1 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | || Shallow & Deep Copy || Recursion || Lot's of Concept || JS | shallow-deep-copy-recursion-lots-of-conc-1g4q | CodeThe Array slice() method returns selected elements in an array as a new array. It selects from a given start, up to a (not inclusive) given end. This method | Ashish_Ujjwal | NORMAL | 2025-02-22T10:01:40.533659+00:00 | 2025-02-22T10:01:40.533659+00:00 | 137 | false |
# Code
```javascript []
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
if(n === 0){
console.log(arr);
return arr.slice()
} // it create shallow copy of array
// Q. Why we are using slice method ...
// Ans. This is because in case we have to modify original array then it create some conflict.
let flatarr = [];
for(let i=0; i<arr.length; i++){
if(Array.isArray(arr[i])){ // this check that at index i there is array or not
const nested = flat(arr[i], n-1); //if n=0 then it hit base case and return as it is...
flatarr.push(...nested);
}else{
flatarr.push(arr[i]);
}
}
// [1,2,3,[4,5,6],[7,8,[9,10,11],12],[13,14,15]]
return flatarr;
};
```
The Array slice() method returns selected elements in an array as a new array. It selects from a given start, up to a (not inclusive) given end. This method does not change the original array, enabling non-destructive extraction of array segments.
```
// Syntax:
// arr.slice(begin, end);
```
Use of flat function
```
// const myArr = [1, 2, [3, [4, 5, 6], 7], 8];
// const newArr = myArr.flat(2);
// console.log(newArr);
```
# Shallow copy & Deep Copy
*JavaScripts has two data types, primitive data type and reference data type. The object comes under reference data type which means it follows copying data using its memory location i.e., copied by reference type.*
Let's see what problems are caused while copying an object from another object and when we have to use shallow and deep copy concepts.
```
let obj1 = {
name : "XYZ",
address : {
city : "Mumbai",
state : "Maharashtra"
}
}
// copying first object into new object i.e, obj2
let obj2 = obj1;
obj2.name = "QWERTY"
console.log("Object 1", obj1.name);
console.log("Object 2", obj2.name);
// result
"Object 1", "QWERTY"
"Object 2", "QWERTY"
```
**So in the above example, if we changed the name property from obj2 it will change the obj1 property as well. To resolve this we can use shallow and deep copy methods.**
1. Shallow copy ---------------------------------->
// In short free it from reference from single(first) level
```
let originalObj = {
name : "XYZ",
address : {
city : "Mumbai",
state : "Maharashtra"
}
}
//Shallow copy first way
//let copyObj = Object.assign({},originalObj);
//Shallow copy second way
let copyObj = {...originalObj};
copyObj.name = "QWERTY"
copyObj.address.city = "Pune"
console.log("originalObj name", originalObj.name);
console.log("copyObj name", copyObj.name);
console.log("originalObj city", originalObj.address.city);
console.log("copyObj city", copyObj.address.city);
```
**We copied the originalObj into the copyObj and changed the name of the copyObj. originalObj name will remain unchanged. i.e.**
Result
```
"originalObj name", "XYZ"
"copyObj name", "QWERTY"
"originalObj city", "Pune"
"copyObj city", "Pune"
```
**But shallow copy will work only first level. So when we change city from copyObj, it will change originalObj as well since it is on the second level.**
2. Deep copy --------------------------------------->
// In short free it from reference from nested level
// To solve the shallow copy issue we can use deep copy concept.
```
let originalObj = {
name : "XYZ",
address : {
city : "Mumbai",
state : "Maharashtra"
},
checkFun : function(){
return 100;
}
}
let copyObj = JSON.parse(JSON.stringify(originalObj));
copyObj.name = "QWERTY"
copyObj.address.city = "Pune"
console.log("originalObj name", originalObj.name);
console.log("originalObj city", originalObj.address.city);
console.log("copyObj", copyObj);
//result
"originalObj name", "XYZ"
"originalObj city", "Mumbai"
"copyObj", {
address: {
city: "Pune",
state: "Maharashtra"
},
name: "QWERTY"
}
```
In the above example, we can change all level values except checkFun property. checkFun is not available in the copied object.
To resolve this we have to use lodash library.
```
let copyObj = _.cloneDeep(originalObj)
console.log("copyObj", copyObj);
//result
"copyObj", {
address: {
city: "Mumbai",
state: "Maharashtra"
},
checkFun: function(){
return 100;
},
name: "XYZ"
}
``` | 1 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | With Recursion | with-recursion-by-davidchills-3ob8 | Code | davidchills | NORMAL | 2025-02-01T00:20:41.236353+00:00 | 2025-02-01T00:20:41.236353+00:00 | 204 | false | # Code
```javascript []
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
const out = [];
const concat = function (sub, currentDepth) {
for (let i = 0; i < sub.length; i++) {
if (Array.isArray(sub[i]) && currentDepth < n) {
concat(sub[i], currentDepth + 1);
}
else { out.push(sub[i]); }
}
}
concat(arr, 0);
return out;
};
``` | 1 | 0 | ['Recursion', 'JavaScript'] | 0 |
flatten-deeply-nested-array | Easy Explanation | easy-explanation-by-pratyushpanda91-ch7i | Explanation:Helper Function:The recursive helper function flattenHelper takes the current array and its depth as arguments.
If the current depth is greater than | pratyushpanda91 | NORMAL | 2025-01-26T13:45:44.069044+00:00 | 2025-01-26T13:45:44.069044+00:00 | 192 | false | # Explanation:
### Helper Function:
The recursive helper function flattenHelper takes the current array and its depth as arguments.
- If the current depth is greater than or equal to the specified n, the function stops recursing and returns the array as-is.
- Otherwise, it iterates through each element of the array. If an element is an array, it flattens it by making a recursive call with an increased depth. If it's not an array, it adds the element to the result.
### Base Case:
If the current depth equals or exceeds n, the recursion stops.
### Recursive Case: For each element in the array, it checks whether it’s an array:
If it is, it recursively calls the helper function.
Otherwise, it adds the element to the flattened result.
### Output: The final flattened array is returned.
This approach avoids using the Array.flat() method and handles the depth-based flattening manually. It is efficient and adheres to the constraints.
# Code
```javascript []
/**
* @param {Array} arr
* @param {number} n
* @return {Array}
*/
var flat = function (arr, n) {
// Helper function to recursively flatten the array
const flattenHelper = (array, currentDepth) => {
if (currentDepth >= n) {
return array; // If depth limit is reached, return array as is
}
const result = [];
for (const element of array) {
if (Array.isArray(element)) {
// Recursively flatten nested arrays
result.push(...flattenHelper(element, currentDepth + 1));
} else {
// Add non-array elements directly
result.push(element);
}
}
return result;
};
return flattenHelper(arr, 0); // Start with depth 0
};
// Example usage:
const arr1 = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]];
console.log(flat(arr1, 0)); // Output: [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
console.log(flat(arr1, 1)); // Output: [1, 2, 3, 4, 5, 6, 7, 8, [9, 10, 11], 12, 13, 14, 15]
console.log(flat(arr1, 2)); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
``` | 1 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | flatten func | 96.55% Beats | 79 ms | JavaScript | flatten-func-9655-beats-79-ms-php-by-ma7-v0qu | Code | Ma7med | NORMAL | 2025-01-14T17:23:09.280784+00:00 | 2025-01-15T08:35:59.828853+00:00 | 710 | false |
# Code
```javascript []
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
const result = [];
// Helper function to handle flattening recursively
function flatten(item, depth) {
if (Array.isArray(item) && depth < n) {
for (let i = 0; i < item.length; i++) {
flatten(item[i], depth + 1);
}
} else {
result.push(item);
}
}
// Start flattening from the input array with initial depth 0
for (let i = 0; i < arr.length; i++) {
flatten(arr[i], 0);
}
return result;
}
``` | 1 | 0 | ['JavaScript'] | 1 |
flatten-deeply-nested-array | Without Recursion || Easy Solution than others || C++ || 👍😊 | easy-solution-than-others-c-by-adarsh002-qafk | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | adarsh0024 | NORMAL | 2024-12-18T17:35:51.573695+00:00 | 2024-12-28T16:39:45.029528+00:00 | 101 | 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 {number} depth
* @return {Array}
*/
const flattenOneLevel = (arr) => {
const ans = [];
for (const item of arr) {
if (Array.isArray(item)) {
ans.push(...item);
}
else {
ans.push(item);
}
}
return ans;
}
var flat = function (arr, n) {
while (n--) {
arr = flattenOneLevel(arr);
}
return arr;
};
``` | 1 | 1 | ['JavaScript'] | 1 |
flatten-deeply-nested-array | Easy JS Soln Using Recursion | easy-js-soln-using-recursion-by-akhil148-b0l6 | 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 | Akhil1489 | NORMAL | 2024-08-02T08:06:07.992445+00:00 | 2024-08-02T08:06:07.992470+00:00 | 549 | 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 {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n) {\n \n if(n < 1){\n return arr.slice()\n }\n\n return arr.reduce((acc,val)=>{\n if(Array.isArray(val)){\n acc.push(...flat(val,n-1))\n } else {\n acc.push(val)\n }\n\n return acc\n },[])\n\n};\n``` | 1 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | One line solution | one-line-solution-by-abhilashabhi2003-usmr | 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 | abhilashabhi2003 | NORMAL | 2024-03-18T08:38:42.716173+00:00 | 2024-03-18T08:38:42.716216+00:00 | 360 | 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 {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n) {\n return arr.flat(n)\n};\n``` | 1 | 0 | ['JavaScript'] | 2 |
flatten-deeply-nested-array | Array.prototype.flat Approach | arrayprototypeflat-approach-by-lannuttia-xj49 | Intuition\nThis is something that can be handled using Array.prototype.flat\n\n# Approach\nI just made flat a wrapper function for Array.\n\n# Code\n\n/**\n * @ | lannuttia | NORMAL | 2023-12-20T22:49:59.946401+00:00 | 2023-12-20T22:49:59.946429+00:00 | 19 | false | # Intuition\nThis is something that can be handled using Array.prototype.flat\n\n# Approach\nI just made flat a wrapper function for Array.\n\n# Code\n```\n/**\n * @param {Array} arr\n * @param {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n) {\n return arr.flat(n)\n};\n``` | 1 | 1 | ['JavaScript'] | 1 |
flatten-deeply-nested-array | Java||BFS | javabfs-by-nikhilneo1-7ydc | Intuition\nThe goal of this problem is to flatten a nested array with a specified depth. We can achieve this by using a breadth-first approach where we process | nikhilneo1 | NORMAL | 2023-08-28T02:42:54.317212+00:00 | 2023-08-28T02:42:54.317239+00:00 | 213 | false | # Intuition\nThe goal of this problem is to flatten a nested array with a specified depth. We can achieve this by using a breadth-first approach where we process the array elements level by level up to the given depth.\n\n# Approach\n1. We start by initializing a queue to hold the elements of the array.\n2. We iterate through each depth level while reducing the depth count.\n3. For each level, we process the current number of elements in the queue (since the queue size may change as we add elements).\n4. If an element in the queue is a list, we convert it to a subarray and add its individual elements to the queue.\n5. If an element is not a list, we add it back to the queue.\n6. Repeat the above steps for the specified depth.\n7. After processing all levels, the queue contains the flattened array with the specified depth.\n\n# Complexity\n- Time complexity: O(N * D), where N is the total number of elements in the input array and D is the specified depth.\n- Space complexity: O(N), where N is the total number of elements in the input array.\n\n# Further improvements\nIn our current approach, we are processing each element as we reduce the depth. However, it\'s necessary to only process elements that are lists each time we delve deeper.\n\n# Code\n```java\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\n\npublic class FlattenArray {\n public static List<Object> flatten(Object[] arr, int depth) {\n Queue<Object> queue = new LinkedList<>();\n queue.addAll(Arrays.asList(arr));\n\n while (depth > 0) {\n int size = queue.size();\n for (int i = 0; i < size; i++) {\n Object item = queue.poll();\n if (item instanceof List<?>) {\n List<Object> subArray = new ArrayList<Object>((List<?>) item);\n queue.addAll(subArray);\n } else {\n queue.add(item);\n }\n }\n depth--;\n }\n\n return new ArrayList<Object>(queue);\n }\n\n public static void main(String[] args) {\n Object[] arr = new Object[]{\n 1, 2, 3,\n Arrays.asList(4, 5, 6),\n Arrays.asList(\n 7, 8,\n Arrays.asList(9, 10, 11),\n 12\n ),\n Arrays.asList(13, 14, 15)\n };\n\n List<Object> flattened = flatten(arr, 1);\n System.out.println(flattened);\n }\n}\n\n | 1 | 0 | ['Breadth-First Search', 'Java'] | 0 |
flatten-deeply-nested-array | 99% Easy DFS recursive solution with explanations ✅ | 99-easy-dfs-recursive-solution-with-expl-eenz | Hello everyone! So, I\'ve come up with a solution to resolve this problem, by the way i\'m new to JS so if you have any advice you\'re welcome. \uD83D\uDE01\n\n | RayanYI | NORMAL | 2023-08-15T17:05:19.564267+00:00 | 2023-08-15T17:05:19.564291+00:00 | 168 | false | **Hello everyone! So, I\'ve come up with a solution to resolve this problem, by the way i\'m new to JS so if you have any advice you\'re welcome. \uD83D\uDE01**\n\n# Intuition\nWhich algorithm can i use to keep tracking the deep ?`\uD83D\uDCA1DFS`\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nFirstly, I\'ve instantiated an array called ans, which will serve as a container for elements after they\'ve been flattened. It essentially acts as a receptacle for our final data.\n\nNext, I\'ve defined a function called dfs, which stands for "Depth First Search." This function lies at the core of the process of traversing arrays to extract elements for flattening.\n\nThe dfs function comprises three parameters: depth (representing the current depth), maxDepth (defining the maximum depth of traversal), and currArray (the array currently under exploration).\n\nNow, the conditional statement is where the intrigue lies. It checks if the current depth depth matches the maximum depth maxDepth. If true, it signifies that we\'ve reached the depth limit, so we add currArray (the array we\'ve explored) to our container ans and we stop the depth exploration.\n\nHowever, if we haven\'t reached the maximum depth yet, we enter a for...of loop. This acts like a machine to inspect each element within currArray.\n\nIf the element we\'re looking at is itself an array, it means we can dig even deeper. Thus, we recursively call the dfs function, incrementing the depth by 1 and passing the new element as currArray.\n\nIn the case where the element isn\'t an array, it simply indicates an ordinary value. In this case, we directly add that value to our container ans.\n\nFinally, the main flat function calls the dfs function with an initial depth of **-1** (to indicate we haven\'t started yet), the maximum depth **n**, and the initial input array **arr**.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n\n**m** = number of elements in arr\n\n**n** = maximum stack calls used by the recursion\n\n- Time complexity: **O(n)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(max(n, m))**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\n/**\n * @param {any[]} arr\n * @param {number} depth\n * @return {any[]}\n */\nvar flat = function (arr, n) {\n var ans= [];\n\n const dfs = (depth,maxDepth,currArray) =>{\n if(depth==maxDepth){\n ans.push(currArray);\n return;\n }\n\n for(element of currArray){\n if(Array.isArray(element)){\n dfs(depth+1,maxDepth,element);\n }else{\n ans.push(element);\n }\n }\n };\n\n dfs(-1,n,arr);\n\n return ans;\n};\n``` | 1 | 0 | ['Depth-First Search', 'Recursion', 'JavaScript'] | 0 |
flatten-deeply-nested-array | 🐰 Easy solution || 🥕Short & Simple || 🥕 | easy-solution-short-simple-by-gg8w7-bfxu | \n\n# Code\n\n/**\n * @param {any[]} arr\n * @param {number} depth\n * @return {any[]}\n */\nvar flat = function (arr, n) {\n const ans =[]\n const traver | GG8w7 | NORMAL | 2023-04-13T03:25:20.590228+00:00 | 2023-04-13T03:26:09.929479+00:00 | 126 | false | \n\n# Code\n```\n/**\n * @param {any[]} arr\n * @param {number} depth\n * @return {any[]}\n */\nvar flat = function (arr, n) {\n const ans =[]\n const traverse=(ele,i)=>{\n if(i > n || !Array.isArray(ele))return ans.push(ele)\n ele.forEach(e=>traverse(e ,i + 1))\n }\n traverse(arr,0)\n return ans \n};\n``` | 1 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | 2625. Flatten Deeply Nested Array Solution | 2625-flatten-deeply-nested-array-solutio-pimu | IntuitionThis problem is about flattening nested arrays to a given depth n. It tests our understanding of recursion, array traversal, and conditional logic base | runl4AVDwJ | NORMAL | 2025-04-09T15:15:43.750434+00:00 | 2025-04-09T15:15:43.750434+00:00 | 2 | false | # **Intuition**
This problem is about **flattening nested arrays** to a given depth `n`. It tests our understanding of **recursion**, **array traversal**, and **conditional logic based on depth**.
Flattening means converting nested arrays into a single-level array, but only up to `n` levels deep. If `n = 0`, we return the array as-is. If `n > 0`, we go deeper into each sub-array recursively.
---
# **Understanding Flattening with Depth**
✅ **What is Flattening?**
Flattening is the process of reducing the depth of nested arrays into a simpler, single-dimensional structure.
✅ **What is Depth-limited Flattening?**
Instead of completely flattening the array, we **only flatten `n` levels** deep. Each recursive level reduces `n` by 1, and stops when `n === 0`.
🔹 **Example:**
```js
Input: arr = [1,[2],[3,[4]]], n = 1
Output: [1,2,3,[4]]
```
---
# **Approach**
I explored a **recursive depth-first approach** that reduces `n` on each nested call. If the current element is an array and depth allows (`n > 0`), I flatten it recursively. Otherwise, I push the element as-is.
---
# 🔹 **Approach: Recursive Flattening with Depth Check**
```js
var flat = function (arr, n) {
let newArr = [];
if (n === 0) return arr;
arr.forEach((ele) => {
if (Array.isArray(ele)) {
newArr.push(...flat(ele, n - 1));
} else {
newArr.push(ele);
}
});
return newArr;
};
```
📌 **Explanation:**
- We loop over each element in the array.
- If the element is an array and `n > 0`, we recursively call `flat()` and spread its result.
- If it’s not an array or `n` is 0, we push it directly.
- `n` is decreased each time we go one level deeper.
✅ **Pros:**
- Simple and elegant.
- Avoids unnecessary loops with recursion.
- Fully respects the depth `n`.
---
# **Complexity Analysis**
- **Time Complexity:**
- $$O(m)$$ – where `m` is the total number of elements (including nested).
- **Space Complexity:**
- $$O(m)$$ – due to the new array and recursive call stack.
---
# **Code Implementation**
```js
/**
* @param {any[]} arr
* @param {number} n
* @return {any[]}
*/
var flat = function (arr, n) {
let newArr = [];
if (n === 0) return arr;
arr.forEach((ele) => {
if (Array.isArray(ele)) {
newArr.push(...flat(ele, n - 1));
} else {
newArr.push(ele);
}
});
return newArr;
};
```
---
# **Important Topics to Learn 📚**
- **Recursion**: Breaking the problem into smaller self-similar problems.
- **Array Traversal**: Using `forEach()` to iterate.
- **Spread Operator (`...`)**: Used to flatten arrays concisely.
- **Array.isArray()**: A must-know method for checking if a value is an array.
- **Depth Control in Recursion**: Managing depth in recursive algorithms.
---
# 🚀 **Support & Feedback**
✅ If you found this helpful, **please upvote & follow** for more clear JavaScript solutions!
💬 Found a better approach or edge case? Let’s discuss and grow together! 🚀🔥
--- | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | my Answer | my-answer-by-rwc8cinz7h-qwtq | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | RwC8cINz7h | NORMAL | 2025-03-29T20:22:15.458713+00:00 | 2025-03-29T20:22:15.458713+00:00 | 1 | 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 {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
return arr.flat(n)
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Flatten Deeply Nested Array | flatten-deeply-nested-array-by-shalinipa-49jf | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | ShaliniPaidimuddala | NORMAL | 2025-03-25T09:00:18.469192+00:00 | 2025-03-25T09:00:18.469192+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 {any[]} arr
* @param {number} depth
* @return {any[]}
*/
var flat = function(arr, depth) {
const stack = [...arr.map(item => [item, depth])];
const result = [];
while (stack.length > 0) {
const [item, depth] = stack.pop();
if (Array.isArray(item) && depth > 0) {
stack.push(...item.map(subItem => [subItem, depth - 1]));
} else {
result.push(item);
}
}
return result.reverse();
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | SberTest | sbertest-by-wasabully-hgtt | Интуиция | wasabully | NORMAL | 2025-03-24T16:01:58.281593+00:00 | 2025-03-24T16:01:58.281593+00:00 | 1 | false |
# Code
```javascript []
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function(array, depth) {
const result = [];
function flatten(arr, level) {
for (let item of arr) {
if (Array.isArray(item) && level > 0) {
flatten(item, level - 1);
} else {
result.push(item);
}
}
}
flatten(array, depth);
return result;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Рекурсия | rekursiia-by-artur-jk-pbq7 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Artur-jk | NORMAL | 2025-03-24T14:10:23.496643+00:00 | 2025-03-24T14:10:23.496643+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 []
var flat = function (arr, n) {
if(n == 0 || arr.every(el => typeof el === 'number')) return arr;
let res = [];
for(let i=0;i<arr.length;i++) {
if(Array.isArray(arr[i])) {
res.push(...flat(arr[i], n-1));
} else res.push(arr[i]);
}
return res;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Efficiently Flatten Deeply Nested Arrays with Controlled Depth | efficiently-flatten-deeply-nested-arrays-kaq6 | IntuitionThe idea is to iteratively flatten the array up to the given depth. We use a while loop to control the depth and a nested while loop to traverse the ar | doviethoang159 | NORMAL | 2025-03-11T02:20:28.153382+00:00 | 2025-03-11T02:20:28.153382+00:00 | 4 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The idea is to iteratively flatten the array up to the given depth. We use a while loop to control the depth and a nested while loop to traverse the array and flatten it.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Use a while loop to control the depth of flattening.
2. Within the loop, traverse the array and check if any element is an array.
3. If an element is an array, flatten it by using splice and spread operator.
4. If no elements are arrays, break the loop.
5. Decrease the depth after each iteration.
# Complexity
- Time complexity O(n * d): Where n is the number of elements in the array and d is the depth. In the worst case, we might need to traverse the entire array d times.
- Space complexity O(1): We are modifying the array in place, so no extra space is used.
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
const flat = (array, depth) => {
while (depth) {
let isFlattened = true;
let len = array.length;
let i = 0;
while (i < len) {
if (Array.isArray(array[i])) {
const currentLen = array[i].length;
array.splice(i, 1, ...array[i]);
i = i + currentLen - 1;
len = array.length;
isFlattened = false;
}
i++;
}
if (isFlattened) {
break;
}
depth--;
}
return array;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Faster recursive solution without spread operator | faster-recursive-solution-without-spread-s1x8 | IntuitionThe initial thought is to create a solution that flattens a nested array up to a specified depth. The problem requires recursively processing array ele | HakobYer | NORMAL | 2025-03-09T14:06:10.009513+00:00 | 2025-03-09T14:06:10.009513+00:00 | 3 | false | # Intuition
The initial thought is to create a solution that flattens a nested array up to a specified depth. The problem requires recursively processing array elements, where we need to:
- Handle nested arrays by diving deeper when depth allows
- Collect non-array elements into a result array
- Stop recursion when either we hit the depth limit or encounter non-array elements
# Approach
The solution uses a recursive approach with these steps:
1. Create an empty result array flattenArr to store flattened elements
2. Handle base case: if depth (n) is 0, return the array as-is
3. Use a helper function handleFlattening that:
- Iterates through each element in the array
- For array elements: recursively calls itself with decremented depth if n > 0
- For non-array elements: adds them to the result array
4. Return the flattened result
# Complexity
- Time complexity: O(n ∗ m)
- Where n is the total number of elements across all nested arrays
- m is the maximum depth of recursion
- Each element is processed once, but we may need to traverse through multiple levels
- Space complexity: O(m)
- Where m is the maximum depth of recursion
- Space is used by the recursive call stack
- The output array doesn't count toward space complexity by convention
# Code
```javascript []
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
const flattenArr = []
if (!n) {
return arr
}
const handleFlattening = (arr, n) => {
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i]) && n) {
handleFlattening(arr[i], n - 1)
} else {
flattenArr.push(arr[i])
}
}
}
handleFlattening(arr, n)
return flattenArr
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Solution Walkthrough | solution-walkthrough-by-tcw53qyc6i-16rv | IntuitionWe need a recursive function that can flatten the array based on n. For this, the function needs to know how deeply nested it is.Approach
We begin with | tCw53qyc6i | NORMAL | 2025-03-06T22:20:25.560728+00:00 | 2025-03-06T22:20:25.560728+00:00 | 2 | false | # Intuition
We need a recursive function that can flatten the array based on `n`. For this, the function needs to know how deeply nested it is.
# Approach
1. We begin with a simple copy of `arr`:
```javascript []
var flat = function (arr, n) {
let res = [];
for (const item of arr) res.push(item);
return res
};
```
This function returns a new array `res` that has every item in `arr`.
2. Next we can write the bones of the recursive function. Our function should take an `element`, check if it's an array. the function should call itself for every `item` in that `element`. If it's not an array, push to `res`.
```javascript []
var flat = function (arr, n) {
let res = [];
function recurse(element, depth) {
if (Array.isArray(element)) {
for (const item of element) {
recurse(item, 0);
}
} else {
res.push(element);
}
}
for (const item of arr) {
recurse(item, 0)
}
return res
};
```
`depth` here has no current use; it's just a place marker. The function at this point flattens `arr` without discretion. What we need now is to count decisively!
We can add `depth += 1` before running the `for...loop` inside `recurse()`, this way every `item` in the `element` begins with the same `depth`. We also need to reset the `depth` if we are pushing to `res`, so `depth = 0` should go just before that.
# Code
```javascript []
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
let res = [];
function recurse(element, depth) {
if (Array.isArray(element) && depth < n) {
depth += 1;
for (const item of element) {
recurse(item, depth)
}
} else {
depth = 0
res.push(element)
}
}
for (const item of arr) {
recurse(item, 0)
}
return res
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | flat it out! | flat-it-out-by-ecabigting-jpbq | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | ecabigting | NORMAL | 2025-03-05T11:31:09.934351+00:00 | 2025-03-05T11:31:09.934351+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 {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
const helper = (arr,currentDepth) => {
if(currentDepth === 0) {
return arr
}
let result = []
for(let i = 0; i < arr.length; i++) {
let element = arr[i];
if(Array.isArray(element) && currentDepth > 0) {
let flattenedSubArray = helper(element,currentDepth -1);
result.push(...flattenedSubArray);
}else {
result.push(element);
}
}
return result;
};
return helper(arr,n)
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Solution | solution-by-aradhanadevi_jadeja-6ngm | Code | Aradhanadevi_Jadeja | NORMAL | 2025-03-02T09:33:33.625235+00:00 | 2025-03-02T09:33:33.625235+00:00 | 6 | false |
# Code
```javascript []
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
if (n === 0) return arr;
let result = [];
for(let item of arr){
if (Array.isArray(item) && n > 0){
result.push(...flat(item, n-1));
}else{
result.push(item);
}
}
return result;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | flatten-deeply-nested-array easy way | flatten-deeply-nested-array-easy-way-by-iov4u | Code | devmazaharul | NORMAL | 2025-03-02T04:37:37.561920+00:00 | 2025-03-02T04:37:37.561920+00:00 | 3 | false |
# Code
```javascript []
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function (arr, n=0) {
return arr.flat(n)
}
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Flatten Deeply Nested Array (JS) - Easy Solution | flatten-deeply-nested-array-js-easy-solu-wbpq | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | alli_vinay | NORMAL | 2025-02-26T06:23:30.714697+00:00 | 2025-02-26T06:23:30.714697+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 []
/**
* Flattens a multi-dimensional array up to a specified depth.
* @param {Array} arr - The multi-dimensional array to flatten.
* @param {number} n - The depth level to flatten the array.
* @return {Array} - The flattened array.
*/
var flat = function(arr, n) {
// Initialize the result array
let result = [];
// Helper function to recursively flatten the array
function flattenHelper(currentArr, currentDepth) {
// Iterate through each element in the current array
for (let item of currentArr) {
// If the current depth is less than n, check if the item is an array
if (currentDepth < n && Array.isArray(item)) {
// Recursively flatten the sub-array
flattenHelper(item, currentDepth + 1);
} else {
// Otherwise, push the item to the result
result.push(item);
}
}
}
// Start the flattening process
flattenHelper(arr, 0);
return result;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | easy solution | easy-solution-by-haneen_ep-31yv | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | haneen_ep | NORMAL | 2025-02-23T07:02:38.532009+00:00 | 2025-02-23T07:02:38.532009+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 {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
let res = [];
const flatternArray = (flatArr, n) => {
for (let i = 0; i < flatArr.length; i++) {
if (Array.isArray(flatArr[i]) && n !== 0) {
flatternArray(flatArr[i], n - 1);
} else {
res.push(flatArr[i])
}
}
}
flatternArray(arr, n)
return res;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | for ... of.. recursive | for-of-recursive-by-rrazvan-rmhz | Code | rrazvan | NORMAL | 2025-02-20T13:43:18.699191+00:00 | 2025-02-20T13:43:18.699191+00:00 | 8 | false | # Code
```typescript []
type MultiDimensionalArray = (number | MultiDimensionalArray)[];
var flat = function (arr: MultiDimensionalArray, n: number): MultiDimensionalArray {
const res = [];
const flatUtil = (arr: MultiDimensionalArray, n: number) => {
for (const val of arr) {
if (Array.isArray(val) && n > 0) {
flatUtil(val, n -1)
} else {
res.push(val);
}
}
}
flatUtil(arr, n);
return res;
};
``` | 0 | 0 | ['TypeScript'] | 0 |
flatten-deeply-nested-array | Solution!! | solution-by-eishi-y73h | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | eishi | NORMAL | 2025-02-15T07:23:32.036456+00:00 | 2025-02-15T07:23:32.036456+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 {number} depth
* @return {Array}
*/
var flat = function (arr, n,current=0) {
let result=[];
if(n==0) return arr;
for(let el of arr){
if(Array.isArray(el) && current<n){
result.push(...flat(el,n,current+1));
}else{
result.push(el);
}
}
return result;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Flatten Deeply Nested Array || Easy Solution | flatten-deeply-nested-array-easy-solutio-j3rb | Complexity
Time complexity: O(n2)
Space complexity: O(n)
Code | nitinkumar-19 | NORMAL | 2025-02-05T17:01:18.452118+00:00 | 2025-02-05T17:02:05.270859+00:00 | 6 | false | # Complexity
- Time complexity: O(n2)
- Space complexity: O(n)
# Code
```javascript []
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
let ans = [];
for(const el of arr){
if(Array.isArray(el) && n>0){
ans.push(...flat(el, n-1));
}else{
ans.push(el);
}
}
return ans;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | One line solution! | one-line-solution-by-we6m4c74zc-7vi1 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | We6m4C74zC | NORMAL | 2025-02-05T13:03:22.024345+00:00 | 2025-02-05T13:03:22.024345+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 {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
return arr.flat(n);
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Easy JavaScript Solution | easy-javascript-solution-by-rajasibi-1hxw | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | RajaSibi | NORMAL | 2025-01-30T05:14:45.746073+00:00 | 2025-01-30T05:14:45.746073+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 {number} n
* @return {Array}
*/
var flat = function (arr, n) {
// Helper function to recursively flatten the array
const flattenHelper = (array, currentDepth) => {
if (currentDepth >= n) {
return array; // If depth limit is reached, return array as is
}
const result = [];
for (const element of array) {
if (Array.isArray(element)) {
// Recursively flatten nested arrays
result.push(...flattenHelper(element, currentDepth + 1));
} else {
// Add non-array elements directly
result.push(element);
}
}
return result;
};
return flattenHelper(arr, 0); // Start with depth 0
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Flattening Multi-Dimensional Arrays in JavaScript: A Simple Approach | flattening-multi-dimensional-arrays-in-j-n2nc | DescriptionThis solution provides a straightforward way to flatten multi-dimensional arrays in JavaScript based on a specified depth. It is designed for beginne | raed_al_masri | NORMAL | 2025-01-27T07:41:54.233991+00:00 | 2025-01-27T07:41:54.233991+00:00 | 1 | false | # Description
This solution provides a straightforward way to flatten `multi-dimensional arrays` in JavaScript based on a `specified depth`. It is designed for beginners and explains the logic behind the code` step-by-step`.
# Code Explanation
1. **Function Declaration**: The main function flat takes two parameters:
`arr`: The multi-dimensional array you want to flatten.
`maxDepth`: The maximum depth to which the array should be flattened.
2. **Final Result Array**: An empty array `finalResult` is initialized to store the flattened elements.
3. **Helper Function**:A nested function `flattenHelper` is defined to perform the actual flattening. This function takes two parameters:
`sub_arr`: The current sub-array being processed.
`depth`: The current depth of the recursion.
4.**Iterating Through the Array:** The ``forEach`` method is used to loop through each item in the `sub_arr`. For each item
- Check if the Item is an Array: If the item is an array and the current `depth` is less than `maxDepth`, the function calls itself recursively with the item and an increased depth `(depth + 1)`.
- `This allows the function to dive deeper into the nested arrays.`
- Pushing Non-Array Items If the item is not an array or the current `depth` has reached `maxDepth`, the item is pushed directly into `finalResult`
# Find Me :
- Portfolio Link: https://raed-almasri.netlify.app/
# Example Usage
```javascript []
// /**
// * @param {Array} arr
// * @param {number} depth
// * @return {Array}
// */
var flat = function (arr, maxDepth) {
let finalResult = [];
function flattenHelper (sub_arr, depth) {
sub_arr.forEach(item =>
// Note: You should use depth + 1, not depth++,
// because depth++ means you increase the current depth and then pass it to the recursive function.
// However, we should not do that because the current level should not be affected.
// that is take me some time to know that bug , however the problem must be easy level
Array.isArray(item) && depth < maxDepth ? flattenHelper(item, depth + 1) : finalResult.push(item)
);
};
flattenHelper(arr, 0);
return finalResult;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | LC #2625 | lc-2625-by-jaalle-ntw3 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | jaalle | NORMAL | 2025-01-26T19:19:00.780014+00:00 | 2025-01-26T19:19:00.780014+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
```typescript []
type MultiDimensionalArray = (number | MultiDimensionalArray)[];
var flat = function (arr: MultiDimensionalArray, n: number): MultiDimensionalArray {
const result: MultiDimensionalArray = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i]) && n > 0) {
result.push(...flat(arr[i] as MultiDimensionalArray, n-1));
} else {
result.push(arr[i]);
}
}
return result;
};
```
```javascript []
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
//return arr.flat(n);
var result = [];
for (var i = 0; i < arr.length; i++) {
Array.isArray(arr[i]) && n > 0
? result.push.apply(result, flat(arr[i], n - 1)) : result.push(arr[i]);
}
return result;
};
``` | 0 | 0 | ['TypeScript', 'JavaScript'] | 0 |
flatten-deeply-nested-array | Easy and way to solve Flat Array - 43ms | easy-and-way-to-solve-flat-array-43ms-by-o7xd | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | srinivas4596 | NORMAL | 2025-01-26T06:51:52.264325+00:00 | 2025-01-26T06:51:52.264325+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 {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
if(n <= 0) return arr
let list = []
for(let item of arr){
if(Array.isArray(item) && n>0)
list.push(...flat(item,n-1))
else list.push(item)
}
return list
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Recursion | recursion-by-stuymedova-a30f | Code | stuymedova | NORMAL | 2025-01-22T12:48:13.002972+00:00 | 2025-01-22T12:48:13.002972+00:00 | 3 | false | # Code
```javascript []
var flat = function (arr, n) {
const res = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i]) && n) {
res.push(...flat(arr[i], n - 1));
} else {
res.push(arr[i]);
}
}
return res;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Simple Solution with explanation of the program and approach to solve the problem step by step | simple-solution-with-explanation-of-the-ywyb1 | IntuitionUnderstand the given condition and think the logic to the given problem and the return value.ApproachWe have to flatten the array until the depth n wit | Shashankpatelc | NORMAL | 2025-01-22T02:42:01.227610+00:00 | 2025-01-22T02:42:01.227610+00:00 | 3 | 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 have to flatten the array until the depth `n` without using the built in function flat().But starting depth must be 0.
- - -
# Problem Breakdown
We just have to flatten the array without using the flat() until depth is `n`. If `n` is 1 we have to flatter array only for depth 1 we are not exced the depth more then `n`.Then Return that array.
- - -
# Program Breakdown
**THIS IS THE BREAKDOWN OF BELOW PROGRAM**
- We need a array to store the result so we use `res` array.
- I need a function that can help in Recursion which take 2 argument `item` which is element of the array,`depth` is a depth we reached in flattering the array,that is `function flatter(item,depth)`.
- Now let's skip the function and move to `for (let i = 0; i < arr.length; i++){flatter(arr[i], 0)}` for better understand how the program run
- The above for loop is the loop present in the end of the function `flat`.
- Which visit all elemnts of array and pass it to `flatter` function for the next process and makesure that no element is skip. which pass array element `arr[i]` and `0` as depth.
- Now back to the function `flatter`, `item` is array element and `depth` is how depth we want to flatter the arary.
- `if (Array.isArray(item) && depth < n)` check that `item` is a sub array or just a element by `Array.isArray(item)` and `depth < n` make sure that depth not exceed the `n`, if 1 of the conditon fail that means `depth` has reach to `n` or `item` is not a sub array,If array is not sub array we move to `else` block and push it to result array by `res.push(item)`.
- If `item` is sub array and `depth` npt reach `n` we have do the same process for all the elements of `item` until 1 of the 2 condition fails.
- If any 1 of the 2 condition fails in `if (Array.isArray(item) && depth < n)` Out mission is over.
- oh no we have to return the result array `res` by `return res` now its over.
- - -
# Complexity
- Time complexity: $$O(m)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
The time complexity of the `flat` function can be analyzed based on the number of elements in the input array and the depth of nesting. Let `m` be the total number of elements in the input array (including all nested arrays)
- Space complexity: $$O(m + n)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
The space complexity is determined by the space required to store the result array `res` and the call stack used for recursion.The result array will store all elements up to the specified depth, which can also be O(m) in the worst case. The maximum depth of the recursion stack can go up to n, leading to a space complexity of O(n) for the call stack. Therefore, the overall space complexity is O(m + n).
- - -
# Code
```javascript []
var flat = function (arr, n) {
let res = []
function flatter(item, depth) {
if (Array.isArray(item) && depth < n) {
for (let i = 0; i < item.length; i++) {
flatter(item[i], depth + 1)
}
}
else {
res.push(item)
}
}
for (let i = 0; i < arr.length; i++) {
flatter(arr[i], 0)
}
return res
};
```
- --
# Have a great time in coding see you soon.....!
- - - | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | 2625. Flatten Deeply Nested Array | 2625-flatten-deeply-nested-array-by-g8xd-4dp0 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | G8xd0QPqTy | NORMAL | 2025-01-19T05:37:35.510632+00:00 | 2025-01-19T05:37:35.510632+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 {number} depth
* @return {Array}
*/
var flat = function (arr, depthLimit) {
const flattened = [];
const recurse = (current, currentDepth) => {
if (!Array.isArray(current) || currentDepth === depthLimit) {
flattened.push(current);
} else {
for (const element of current) {
recurse(element, currentDepth + 1);
}
}
};
for (const item of arr) {
recurse(item, 0);
}
return flattened;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | While loop + splice + typeof | while-loop-splice-typeof-by-natteererer-3hsd | Code | natteererer | NORMAL | 2025-01-18T00:06:27.042881+00:00 | 2025-01-18T00:06:27.042881+00:00 | 3 | false |
# Code
```javascript []
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
let index = 0;
let count = 0;
while(n > 0){
while(index < arr.length){
if(String(typeof arr[index]) === 'object'){
count = arr[index].length;
arr.splice(index, 1, ...arr[index]);
index += count;
count = 0;
}
else{
index++;
}
}
index = 0;
n--;
}
return arr;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Better solution ✅🚀 | better-solution-by-its_me_1-7pi8 | IntuitionThe task is to flatten an array to a specified depth:
If an element is an array and the current depth allows further flattening, expand that array into | its_me_1 | NORMAL | 2025-01-16T11:07:27.063744+00:00 | 2025-01-16T11:07:27.063744+00:00 | 4 | false | # Intuition
The task is to flatten an array to a specified depth:
- If an element is an array and the current depth allows further flattening, expand that array into its elements.
- Otherwise, retain the element as is.
A stack-based approach provides an iterative alternative to recursion, allowing better control over depth and handling large arrays efficiently without risking a stack overflow.
# Approach
- **Initialize a Stack**:
- Each stack entry contains an array element and its current depth.
- Start by mapping all elements of the input array with the initial depth.
- **Iterate with a While Loop**:
- Pop the top element from the stack.
- If the element is an array and the depth is greater than 0:
- Decompose the array into individual elements and push them back onto the stack with reduced depth.
- Otherwise, add the element to the result array.
- **Reverse the Result**:
- Since the stack operates in LIFO (Last-In-First-Out) order, the result is constructed in reverse.
- Reverse the result array to obtain the correct order.
# Complexity
- Time complexity:
- Each element is processed once, either as a primitive value or as part of an array.
- The total complexity is O(n), where n is the number of elements in the array, including all nested arrays.
- Space complexity:
- The stack holds elements to be processed, which can grow up to 𝑂(𝑛) in the worst case.
- The result array also requires 𝑂(𝑛) space.
- Overall: 𝑂(𝑛).
# Code
```javascript []
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function(arr, depth) {
const stack = [...arr.map(item => [item, depth])];
const result = [];
while (stack.length > 0) {
const [item, depth] = stack.pop();
if (Array.isArray(item) && depth > 0) {
stack.push(...item.map(subItem => [subItem, depth - 1]));
} else {
result.push(item);
}
}
return result.reverse();
};
```

| 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Flatten array | flatten-array-by-moonlayt-j43h | IntuitionFirstly, we need to understand, what way we will use - recursive or loop, and start implement what we want.Approach
As we can see, if n===0, we can ret | MOONLAYT | NORMAL | 2025-01-14T19:28:22.224271+00:00 | 2025-01-14T19:28:22.224271+00:00 | 7 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Firstly, we need to understand, what way we will use - recursive or loop, and start implement what we want.
# Approach
<!-- Describe your approach to solving the problem. -->
1. As we can see, if `n===0`, we can return given array as is, so we can make a check for it.
2. Create a result array, whitch will be returned.
3. We will need a helper function, which will be called recursively
It will accept an array, and a current depth, to check, if `maxDepth`
exeeded.
4. Now we need to check - if `item` is a number, or if `maxDepth` is exeeded - in both ways we need to push an element to the result array.
5. If item is an array, and `maxDepth` is not exeeded - we need to go deeper, to call our helper one more time.
6. Enjoy recision magic))))
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
0(n)
# Code
```typescript []
type MultiDimensionalArray = (number | MultiDimensionalArray)[];
const flat = (arr: MultiDimensionalArray, maxDepth: number): MultiDimensionalArray => {
<!-- CHECK IF WE DONT NEED ANY ADDITIONAL ACTIONS -->
if(!n) return arr
<!-- CREATE A RESULT ARRAY -->
let result = []
<!-- CREATE HELPER FUNCTION -->
const flatten = (item, depth) => {
<!-- CHECH MAXIMUM DEPTH AND ARRAY -->
if (Array.isArray(item) && depth <= maxDepth ) {
item.forEach(el => {
<!-- CALL RECURSIVELY -->
flatten(el, depth + 1)
})
} else {
<!-- PUSH TO RESULT IF NUMBER OR DEPTH IS EXEEDED -->
result.push(item)
}
}
<!-- CALL HELPER FIRST TIME -->
flatten(arr,0)
return result
};
``` | 0 | 0 | ['TypeScript'] | 0 |
flatten-deeply-nested-array | || Beginner approach || | beginner-approach-by-ybcnvxeaod-do3k | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | UjjawalSingh123 | NORMAL | 2025-01-13T09:04:12.528247+00:00 | 2025-01-13T09:04:12.528247+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 {number} depth
* @return {Array}
*/
// Recursive Approach
function flat(arr, depth) {
if (depth === 0) {
return arr.slice(); // Base case: return a shallow copy of the array
}
let flattened = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
const nested = flat(arr[i], depth - 1); // Recursively flatten nested arrays
flattened.push(...nested); // Concatenate flattened nested arrays to the result
} else {
flattened.push(arr[i]); // Push individual elements to the result
}
}
return flattened; // Return the flattened array
}
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Flatten the array solution(Two sollutions) | flatten-the-array-solutiontwo-sollutions-jspa | Code | pankaj3765 | NORMAL | 2025-01-10T03:04:27.597233+00:00 | 2025-01-10T03:04:27.597233+00:00 | 4 | false |
# Code
```javascript []
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
const result = arr.reduce((acc, curr, index)=>{
if(Array.isArray(curr) && n>0){
acc.push(...flat(curr, n-1));
} else {
acc.push(curr)
}
return acc;
}, []);
return result;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | #2625. Flatten Deeply Nested | 2625-flatten-deeply-nested-by-dheeraj732-bhg6 | IntuitionWhen given a nested array and a depth, the task is to flatten the array up to the specified depth. Initially, it seems straightforward to iteratively o | Dheeraj7321 | NORMAL | 2025-01-05T11:46:02.050459+00:00 | 2025-01-05T11:46:02.050459+00:00 | 5 | false | # Intuition
When given a nested array and a depth, the task is to flatten the array up to the specified depth. Initially, it seems straightforward to iteratively or recursively traverse the array and unpack its elements based on the depth. The key challenge lies in properly handling nested arrays while respecting the depth constraint.
# Approach
1. **Recursive Flattening**:
- Define a helper function that takes the current array and depth as parameters.
- If the depth is 0, return the array as it is without further flattening.
- Iterate through the array:
- If an element is an array and the depth permits, recursively flatten it by decreasing the depth.
- Otherwise, include the element in the result as-is.
2. **Base Case**:
- Stop the recursion when the depth reaches 0 or when elements are no longer arrays.
3. **Result Construction**:
- Use a temporary result array and the spread operator to unpack elements when flattening.
4. **Final Output**:
- Return the fully or partially flattened array based on the given depth.
# Complexity
- **Time complexity**:
- $$O(n)$$, where $$n$$ is the total number of elements in the array, including nested ones. Each element is visited once.
- **Space complexity**:
- $$O(n)$$ in the worst case due to the recursive stack and storage for the flattened array.
# Code
```javascript []
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function (arr, depth) {
const flatten = (inputArray, currentDepth) => {
if (currentDepth === 0) return inputArray;
const result = [];
for (const item of inputArray) {
if (Array.isArray(item) && currentDepth > 0) {
result.push(...flatten(item, currentDepth - 1));
} else {
result.push(item);
}
}
return result;
};
return flatten(arr, depth);
};
/**
* Example Usage:
* console.log(flat([1, [2, [3, [4]]]], 2)); // [1, 2, 3, [4]]
* console.log(flat([1, [2, [3, [4]]]], 1)); // [1, 2, [3, [4]]]
* console.log(flat([1, [2, [3, [4]]]], 0)); // [1, [2, [3, [4]]]]
*/
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Truly a JavaScript miracle! | truly-a-javascript-miracle-by-timeforcha-gz57 | IntuitionAt first, I considered the array as one-dimensional and thought I could loop through each element to dive into the 2nd, 3rd, and 4th dimensions. Howeve | timeforchangegrandma | NORMAL | 2025-01-04T04:53:20.678910+00:00 | 2025-01-04T04:53:20.678910+00:00 | 3 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
At first, I considered the array as one-dimensional and thought I could loop through each element to dive into the 2nd, 3rd, and 4th dimensions. However, it became clear that this approach would be quite challenging.
# Approach
<!-- Describe your approach to solving the problem. -->
Later, I researched the flat function and realized it takes a depth parameter, allowing me to solve the problem with a single line of code.
# 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 {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
if (n === 0) {
return arr;
}
return arr.flat(n);
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | flat | flat-by-ka11den-g353 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | ka11den | NORMAL | 2025-01-01T11:08:23.621446+00:00 | 2025-01-01T11:08:23.621446+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 {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
let result = arr;
if (n >= 1) result = arr.flat(n)
return result
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | GOOD ONE | RECURSION | EASY MEDIUM | good-one-recursion-easy-medium-by-imran7-le7v | Code | imran7908 | NORMAL | 2024-12-30T05:16:55.638972+00:00 | 2024-12-30T05:16:55.638972+00:00 | 4 | false | # Code
```javascript []
function flatten(array, currentDepth, maxDepth, result) {
if (currentDepth > maxDepth) {
result.push(array);
return;
}
for (let el of array) {
if (Array.isArray(el)) {
flatten(el, currentDepth + 1, maxDepth, result);
} else {
result.push(el);
}
}
return;
}
var flat = function (arr, n) {
const result = [];
flatten(arr, 0, n, result);
return result;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | easy solution | easy-solution-by-virendangi123-jb6o | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Virendangi123 | NORMAL | 2024-12-26T14:33:14.780925+00:00 | 2024-12-26T14:33:14.780925+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 {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
const res = [];
function helper(arr,depth) {
for(const val of arr) {
if(typeof(val) === 'object' && depth < n) {
helper(val,depth + 1);
} else {
res.push(val);
}
}
return res;
}
return helper(arr,0);
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | JS solution with example | js-solution-with-example-by-muskan_kutiy-49ie | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Muskan_Kutiyal | NORMAL | 2024-12-25T09:47:31.218908+00:00 | 2024-12-25T09:47:31.218908+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 {number} n
* @return {Array}
*/
var flat = function (arr, n) {
const result = [];
const helper = (array, depth) => {
for (const item of array) {
if (Array.isArray(item) && depth < n) {
helper(item, depth + 1); // Recursively flatten if depth < n
} else {
result.push(item); // Add element to the result
}
}
};
helper(arr, 0); // Start flattening with depth 0
return result;
};
// Example usage:
const arr = [1, [2, [3, [4, [5]]]], 6];
const depth = 2;
console.log(flat(arr, depth));
// Output: [1, 2, 3, [4, [5]], 6]
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Simple Recursive Approach (JS) | simple-recursive-approach-js-by-karsian-t3qs | ApproachRecursive ApproachComplexity
Time complexity: O(N∗n)
Space complexity:O(N+n)
Code | Karsian | NORMAL | 2024-12-25T09:39:41.464503+00:00 | 2024-12-25T09:39:41.464503+00:00 | 3 | false | # Approach
<!-- Describe your approach to solving the problem. -->
Recursive Approach
# Complexity
- Time complexity: $$O(N*n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:$$O(N+n)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
if (!n) return arr
const newArr = []
arr.forEach(el => {
if (Array.isArray(el)) { newArr.push(...flat(el, n - 1)) }
else { newArr.push(el) }
})
return newArr
};
``` | 0 | 0 | ['Recursion', 'JavaScript'] | 0 |
flatten-deeply-nested-array | First Problem Solve | first-problem-solve-by-salman_00-67an | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Salman_00 | NORMAL | 2024-12-23T11:58:59.172467+00:00 | 2024-12-23T11:58:59.172467+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 []
var flat = function (arr, n) {
if (n === 0) return arr; // Agar depth 0 hai, toh original array return karein
return arr.reduce((acc, val) => {
if (Array.isArray(val) && n > 0) {
acc.push(...flat(val, n - 1)); // Recursive call with reduced depth
} else {
acc.push(val); // Non-array values ko directly add karein
}
return acc;
}, []);
};
// Test
console.log(flat([1, [2, 3], [4, [5, 6]]], 1)); // [1, 2, 3, 4, [5, 6]]
console.log(flat([1, [2, 3], [4, [5, 6]]], 2)); // [1, 2, 3, 4, 5, 6]
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Recursive if(Array.isArray(elem) && n > 0) { | recursive-ifarrayisarrayelem-n-0-by-roma-vezs | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | roman_gravit | NORMAL | 2024-12-20T18:19:27.479496+00:00 | 2024-12-20T18:19:27.479496+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 {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
const result = [];
for(let i = 0; i < arr.length; i++) {
const elem = arr[i];
if(Array.isArray(elem) && n > 0) {
result.push(...flat(elem, n-1))
} else {
result.push(elem)
}
}
return result;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | 2625. Flatten Deeply Nested Array | 2625-flatten-deeply-nested-array-by-anik-351o | IntuitionApproachComplexity
Time complexity:- o(m)
Space complexity:- o(m)
Code | Anikaleet | NORMAL | 2024-12-18T12:59:11.618159+00:00 | 2024-12-18T12:59:11.618159+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:- o(m)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:- o(m)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Array} arr\n * @param {number} depth\n * @return {Array}\n */\nvar flat = function(arr, n) {\n let stack = [...arr.map(item => [item, n])]; //Initialize a stack with the elements of the array, each paired with the initial depth.\n let result = []; //Initialize an empty result array to store the flattened elements.\n\n while (stack.length > 0) { //while there are elements in the stack.\n let [current, depth] = stack.pop(); //Pop an element from the stack along with its depth.\n\n if (Array.isArray(current) && depth > 0) {\n //If current is an array and depth is greater than 0, push its elements to the stack with the reduced depth.\n stack.push(...current.map(item => [item, depth - 1]));\n //If current is not an array or depth is 0, push it to the result array.\n } else {\n result.push(current);\n }\n }\n\n // The stack unwinds in LIFO order, so we need to reverse the result to maintain original order\n return result.reverse();\n};\n\n// Example usage\n// const nestedArray = [1, [2, [3, [4, 5]]], 6];\n// const depth = 2;\n// const flatArray = flat(nestedArray, depth);\n// console.log(flatArray); // Output: [1, 2, 3, [4, 5], 6]\n\n``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Basic recursion | basic-recursion-by-raulzc3-lxiv | IntuitionI see that this is going to be a recursive function since I would have to flatten the nested arrays too.ApproachFirst I have to iterate the given array | raulzc3 | NORMAL | 2024-12-17T21:02:02.044146+00:00 | 2024-12-17T21:02:02.044146+00:00 | 2 | false | # Intuition\nI see that this is going to be a recursive function since I would have to flatten the nested arrays too.\n\n\n# Approach\nFirst I have to iterate the given array and check if the depth is grater than 0, if not, return the array since the job is done. If n>0, iterate the array and check every position: if the position is a number, add it to the result array, else, apply the same function recursively to the array and n-1 depth.\n\n\n# Code\n```javascript []\n/**\n * @param {Array} arr\n * @param {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n) {\n if (n === 0) {\n return arr;\n }\n\n const result = [];\n\n arr.forEach((position) => {\n if (typeof position === "number") {\n result.push(position);\n } else {\n result.push(...flat(position, n - 1));\n }\n });\n\n return result;\n};\n\n``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | 简单的递归 | jian-dan-de-di-gui-by-caizhenci-scru | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | caizhenci | NORMAL | 2024-12-15T15:03:20.207675+00:00 | 2024-12-15T15:03:20.207675+00:00 | 2 | 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 {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n) {\n let ret = []\n let curDep = -1\n function helper(subArr) {\n curDep++\n if (curDep < n) {\n subArr.forEach(item => {\n if(Array.isArray(item)) {\n helper(item)\n } else {\n ret.push(item)\n }\n })\n } else {\n ret.push(subArr)\n }\n curDep--\n }\n arr.forEach(item => {\n if(Array.isArray(item)) {\n helper(item)\n } else {\n ret.push(item)\n }\n })\n return ret\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Recursive solution | recursive-solution-by-user7669j-pt5w | IntuitionApproachComplexity
Time complexity:
O(n), where n is the total number of elements and sub-elements in the array.
Space complexity:
O(n) due to the resu | user7669j | NORMAL | 2024-12-13T19:33:08.909827+00:00 | 2024-12-13T19:33:08.909827+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)$$ -->\nO(n), where n is the total number of elements and sub-elements in the array.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n) due to the result array and recursive stack.\n# Code\n```javascript []\n/**\n * @param {Array} arr\n * @param {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n, currentDepth = 0) {\n let res = []\n for (const element of arr) {\n if (Array.isArray(element) && currentDepth < n) {\n res.push(...flat(element, n, currentDepth + 1));\n } else {\n res.push(element);\n }\n }\n return res\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Simple ... Just use arr.Flat(n) . Check it now | simple-just-use-arrflatn-check-it-now-by-qgmc | null | divanshurohilla16 | NORMAL | 2024-12-11T13:39:14.435958+00:00 | 2024-12-11T13:39:14.435958+00:00 | 1 | false | \n# Code\n```javascript []\n/**\n * @param {Array} arr\n * @param {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n) {\n return arr.flat(n);\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | JavaScript simple O(n) solution | javascript-simple-on-solution-by-enmalaf-epuu | 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 | enmalafeev | NORMAL | 2024-12-06T09:41:42.173536+00:00 | 2024-12-06T09:41:42.173565+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\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 {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n) {\n const inner = (arr, depth) => {\n return arr.reduce((acc, el) => {\n if (Array.isArray(el) && depth < n) {\n acc.push(...inner(el, depth + 1));\n } else {\n acc.push(el);\n }\n return acc;\n },[]);\n }\n return inner(arr, 0);\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | js Easy | js-easy-by-hacker_bablu_123-p5o0 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe function utilizes a recursive approach to reduce the depth of the nested array laye | Hacker_Bablu_123 | NORMAL | 2024-12-02T17:33:50.690276+00:00 | 2024-12-02T17:33:50.690302+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe function utilizes a recursive approach to reduce the depth of the nested array layer by layer. For each recursive call, the function decreases the allowed depth by 1 until it reaches 0, at which point the array is no longer flattened further.\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBase Case:\nIf n (the remaining depth) is less than 1, the function returns a shallow copy of the array using slice(). This ensures no further flattening is done.\n\nRecursive Case:\nUse Array.prototype.reduce to iterate through the array.\n\nIf the current element (val) is an array, recursively flatten it with the depth decreased by 1.\nIf it\u2019s not an array, append it directly to the accumulator.\nCombining Results:\nFor each element, either push the flattened result of the nested array or the element itself to the accumulator. This builds the flattened array up to the specified depth.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n(n)\n\n# Code\n```javascript []\n/**\n * @param {Array} arr\n * @param {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n) {\n \n if(n < 1){\n return arr.slice()\n }\n\n return arr.reduce((acc,val)=>{\n if(Array.isArray(val)){\n acc.push(...flat(val,n-1))\n } else {\n acc.push(val)\n }\n\n return acc\n },[])\n\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | More you should know about Flatten || Best Soln | more-you-should-know-about-flatten-best-1mkkw | \n\uD83D\uDCA1 It is a process through which we can reduce the dimension of the array\n\n \n\n- We can use concat() method for flattening the array\n\njsx\nlet | AdityaSingh21 | NORMAL | 2024-11-30T10:35:50.801879+00:00 | 2024-11-30T10:35:50.801913+00:00 | 3 | false | <aside>\n\uD83D\uDCA1 It is a process through which we can reduce the dimension of the array\n\n</aside>\n\n- We can use concat() method for flattening the array\n\n```jsx\nlet arr = [[1,2],[3,[4,9]],[5,6]];\n\nlet flattened= [].concat(...arr);\nconsole.log(flattened); //[ 1, 2, 3, [ 4, 9 ], 5, 6 ]\n```\n\n- Use array.flat() method, here you have to give the depth level of the array\n \n for example: array.flat(2)\n \n ```jsx\n let arr = [[1,2],[3,[4,9]],[5,6]];\n \n console.log(arr.flat(2)); //[ 1, 2, 3, 4, 9 , 5, 6 ]\n ```\n \n- We can also make our own custom flat function for an array with the help of recursion\n\n```jsx\nlet arr = [[1,2],[3,[4,9]],[5,6]];\n\nfunction customFlat(arr, dept = 1){\n let result = [];\n arr.forEach((ar) => {\n if(Array.isArray(ar) && dept>0){\n result.push(...customFlat(ar, dept-1))\n } else result.push(ar)\n });\n return result;\n}\n\nconsole.log(customFlat(arr, 2));\n```\n\n\n\n# Code (The Simple Approach)\n```javascript []\n/**\n * @param {Array} arr\n * @param {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n) {\n let result = [];\n arr.forEach((ar) => {\n if(Array.isArray(ar) && n>0){\n result.push(...flat(ar,n-1));\n }\n else{\n result.push(ar);\n }\n })\n\n return result;\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | JavaScript | Typescript Solution with recursion | javascript-typescript-solution-with-recu-548n | Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \nO(n)\n\n- Space comp | sudhanshu221b | NORMAL | 2024-11-28T21:23:26.338492+00:00 | 2024-11-28T21:23:26.338526+00:00 | 6 | false | # 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$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ (If we consider the resulting array)\n\n\n# Code\n```typescript []\ntype MultiDimensionalArray = (number | MultiDimensionalArray)[];\n\nvar flat = function (arr: MultiDimensionalArray, n: number): MultiDimensionalArray {\n if(n === 0) return arr\n\n let resArr: MultiDimensionalArray = []\n\n for (let i = 0; i < arr.length; i++) {\n if(Array.isArray(arr[i])) {\n resArr.push(...flat(arr[i] as MultiDimensionalArray, n-1))\n } else {\n resArr.push(arr[i])\n }\n }\n return resArr\n};\n``` | 0 | 0 | ['Recursion', 'TypeScript'] | 0 |
flatten-deeply-nested-array | Explained with help of an example | explained-with-help-of-an-example-by-him-kwge | Example Walkthrough:\n- For input arr = [1, [2, [3, 4], 5], 6] and n = 2, here\u2019s what happens step-by-step:\n - The helper function starts with the oute | himanshusaini0345 | NORMAL | 2024-11-28T12:38:15.104410+00:00 | 2024-11-28T12:38:15.104441+00:00 | 6 | false | # Example Walkthrough:\n- For input arr = [1, [2, [3, 4], 5], 6] and n = 2, here\u2019s what happens step-by-step:\n - The helper function starts with the outer array [1, [2, [3, 4], 5], 6] and depth 0.\n - It adds 1 to res.\n - It sees the sub-array [2, [3, 4], 5] and recursively calls helper with this sub-array and depth 1.\n - It adds 2 to res.\n - It sees the nested array [3, 4] and calls helper recursively with depth 2.\n - It adds 3 and 4 to res.\n - It adds 5 to res.\n - It adds 6 to res.\n - The function returns [1, 2, 3, 4, 5, 6].\n\n# Code\n```typescript []\ntype MultiDimensionalArray = (number | MultiDimensionalArray)[];\n\nvar flat = function (arr: MultiDimensionalArray, n: number): MultiDimensionalArray {\n const res:MultiDimensionalArray = [];\n\n function helper(arr:MultiDimensionalArray, depth: number): MultiDimensionalArray{\n for(const val of arr){\n if(typeof val === \'object\' && depth < n){\n helper(val,depth + 1);\n }\n else res.push(val);\n }\n return res;\n }\n\n return helper(arr,0);\n\n};\n``` | 0 | 0 | ['TypeScript'] | 0 |
flatten-deeply-nested-array | recursion | recursion-by-user5469al-n8wv | 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 | user5469al | NORMAL | 2024-11-26T10:31:15.661782+00:00 | 2024-11-26T10:31:15.661804+00:00 | 0 | 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 {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n) {\n const flatArr = [];\n if(n< 1){\n return arr;\n }\n for(let i=0;i<arr.length;i++){\n if(Array.isArray(arr[i])){\n flatArr.push(...flat(arr[i], n-1))\n }else{\n flatArr.push(arr[i])\n }\n }\n return flatArr;\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Recursive check | recursive-check-by-svygzhryr-7xcl | Intuition\nIt\'s basically just recursive iteration through current array.\n\n# Approach\nCreate a function which will be iterating through current array and if | Svygzhryr | NORMAL | 2024-11-25T05:39:13.131364+00:00 | 2024-11-25T05:39:13.131396+00:00 | 3 | false | # Intuition\nIt\'s basically just recursive iteration through current array.\n\n# Approach\nCreate a function which will be iterating through current array and if current item is an array, recursively iterate through it as well if we still not exceeded allowed depth.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```typescript []\ntype MultiDimensionalArray = (number | MultiDimensionalArray)[];\n\nvar flat = function (arr: MultiDimensionalArray, n: number): MultiDimensionalArray {\n const ans = [];\n let remainingDepth = n;\n\n function recursiveCheck(array: MultiDimensionalArray, currentDepth: number) {\n\n for (let i = 0; i < array.length; i++) {\n const item = array[i];\n\n if (typeof item === \'number\' || currentDepth === 0) {\n ans.push(item);\n } else {\n recursiveCheck(item, currentDepth - 1);\n }\n }\n\n }\n\n recursiveCheck(arr, remainingDepth)\n\n return ans;\n};\n``` | 0 | 0 | ['TypeScript'] | 0 |
flatten-deeply-nested-array | Optimized Recursive Array Flattening -- Best Solution!! Well documented!! | optimized-recursive-array-flattening-bes-p3yd | \n# Runtime Performance\n- Runtime: 89 ms \n- Beats: 91.32% of submissions\n\nThis high performance is due to not using array spread operations. The only issue | rippl | NORMAL | 2024-11-21T17:00:00.150773+00:00 | 2024-11-21T17:45:29.972823+00:00 | 4 | false | \n# Runtime Performance\n- **Runtime**: `89 ms` \n- **Beats**: `91.32%` of submissions\n\nThis high performance is due to not using array spread operations. The only issue is by not using the spread you are passing the sub-arrays by reference.\n\n# Intuition\nI approached this problem as a graph problem. Instead of using a stack I am using recursion to act as the stack.\n\nBy decrementing `n` I can easily control how deeply I flatten the array.\n\nThis solution avoids the use of array spreads (`...`), which is not a good approach. They are O(`n \xD7 d`) time compleixty where d is the depth. Spreads (`...`) are not constant time operations. \n\nAdditionally, spreads (`...`) will introduce noticable performance overhead in JavaScript. \n\nInstead, directly pushing elements into the result array minimizes unnecessary operations, ensuring consistently better runtime performance.\n\n# Approach\n1. Use recursion to traverse the nested arrays. This allows us to explore the structure deeply and handle the multi-dimensional nature naturally.\n2. Maintain a result array `res` to store flattened elements.\n3. For each element in the input array:\n - If it\'s not an array or the depth has reached `0`, directly add it to the result.\n - Otherwise, recursively call the helper function `dfs` with the subarray and decremented depth.\n4. Avoid using array spread (`...`) or `concat`, which introduces performance overhead.\n\n# Complexity\n- Time complexity - O(`n`):\nYou visit every element in the input array exactly once, regardless of how deeply nested it is, as long as the depth k is sufficient to fully flatten the array. Even for nested structures, each element contributes once to the traversal, making the time complexity linear with respect to the total number of elements, n.\n\n Depth (k) does not directly affect the asymptotic time complexity, but for small k, fewer recursive calls occur, making the traversal faster in practice.\n\n- Space complexity:\n - Auxiliary Space Complexity: O(`d`)\n Space used by the recursion call stack.\n\nTechnically we are creating a new array to store the final flattened result and are using O(`n`). But in problems like this we are focusing on and want to minimize the auxiliary space complexity.\n\n# Code\n```typescript []\ntype MultiDimensionalArray = (number | MultiDimensionalArray)[];\n\nvar flat = function (arr: MultiDimensionalArray, n: number): MultiDimensionalArray {\n const res: MultiDimensionalArray = []\n \n const dfs = (arr: MultiDimensionalArray, n: number): void => {\n for (const val of arr) {\n if (!Array.isArray(val) || n === 0) {\n res.push(val)\n } else {\n dfs(val, n-1)\n }\n }\n }\n\n dfs(arr, n)\n return res\n};\n``` | 0 | 0 | ['TypeScript'] | 0 |
flatten-deeply-nested-array | [js] [Symbol.iterator] is solution | js-symboliterator-is-solution-by-andydan-u8tm | 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 | andydanilov | NORMAL | 2024-11-16T19:54:02.645785+00:00 | 2024-11-16T19:54:02.645816+00:00 | 1 | 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 {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n) {\n const stack = [[arr[Symbol.iterator](), n]]\n const result = []\n\n while (stack.length) {\n const [iterator, depth] = stack.pop()\n\n for (let el of iterator) {\n if (Array.isArray(el) && depth > 0) {\n stack.push([iterator, depth], [el[Symbol.iterator](), depth - 1])\n\n break\n } else {\n result.push(el)\n }\n }\n }\n\n return result;\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Каф кефтеме | kaf-kefteme-by-whitnessss-czk0 | 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 | Whitnessss | NORMAL | 2024-11-14T14:44:44.756915+00:00 | 2024-11-14T14:44:44.756944+00:00 | 0 | 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 {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n) {\n let newArray = [];\n for (let element of arr) {\n if (Array.isArray(element) && n > 0) {\n newArray.push(...flat(element, n - 1)); \n }\n else {\n newArray.push(element)\n }\n }\n return newArray;\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Flatten Deeply Nested Array | flatten-deeply-nested-array-by-maimuna_j-pymm | \n\n# Code\njavascript []\n/**\n * @param {Array} arr\n * @param {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n) {\n if (n === 0) {\n | Maimuna_Javed | NORMAL | 2024-11-14T14:30:14.630032+00:00 | 2024-11-14T14:30:14.630079+00:00 | 1 | false | \n\n# Code\n```javascript []\n/**\n * @param {Array} arr\n * @param {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n) {\n if (n === 0) {\n return arr;\n }\n return arr.flat(n);\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
flatten-deeply-nested-array | Best Solution in JAVASCRIPT solution with O(N) complexity | best-solution-in-javascript-solution-wit-8exe | 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 | samrat1010 | NORMAL | 2024-11-08T18:32:13.611069+00:00 | 2024-11-08T18:32:13.611099+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: O(n)\n\n\n- Space complexity: O(n)\n\n# Code\n```javascript []\n/**\n * @param {Array} arr\n * @param {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n) {\n\n let res = []\n\n function helperRec(arr, depth){\n\n for(const val of arr){\n if(Array.isArray(val) && depth < n){\n helperRec(val, depth +1)\n }\n else{\n res.push(val)\n }\n }\n return res\n }\n return helperRec(arr, 0)\n \n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
sort-an-array | C++ Clean Code Solution | Fastest | All (15+) Sorting Methods | Detailed | c-clean-code-solution-fastest-all-15-sor-93iw | Table of Content:\n STL\n\t Method1: Standard \n\t Method2: Stable\n Insertion Sort\n\t Method1: Iterative\n\t Method2: Recursive\n Selection Sort\n\t Method1: | umesh72614 | NORMAL | 2021-08-13T14:38:40.343511+00:00 | 2022-10-13T07:31:28.158609+00:00 | 48,751 | false | ### Table of Content:\n* STL\n\t* Method1: Standard \n\t* Method2: Stable\n* Insertion Sort\n\t* Method1: Iterative\n\t* Method2: Recursive\n* Selection Sort\n\t* Method1: Standard\n\t* Method2: Standard using inbuilt\n* Bubble Sort\n* Quick Sort\n\t* Method1: Standard\n\t* Method2: Randomised\n* Merge Sort\n\t* Method1: Outplace Merging\n\t* Method2: Inplace Merging\n* Generalised Radix Sort\n\t* Method1: Using MinVal\n\t* Method2: Using Partitioning\n* Generalised Counting Sort\n* Heap Sort\n* Bucket Sort\n\n##### STL\n\n1. Method1: Standard (Accepted) [T(n) = O(n * lgn)]\n\n```\nvoid stlSort(vector<int>& nums) {\n\tsort(nums.begin(), nums.end());\n}\n```\n\n2. Method2: Stable (Accepted) [T(n) = O(n * lgn)]\n```\nvoid stableStlSort(vector<int>& nums) {\n\tstable_sort(nums.begin(), nums.end());\n}\n```\n\n##### Insertion Sort\n\n1. Method1: Iterative (TLE) [T(n) = O(n^2)]\n\n```\nvoid insertionSort(vector<int> &nums) {\n\tint sortedInd, unsortedInd, key, size = nums.size();\n\tif (size <= 1) return;\n\tfor (unsortedInd = 1; unsortedInd < size; unsortedInd++) {\n\t\tkey = nums[unsortedInd], sortedInd = unsortedInd;\n\t\twhile (--sortedInd >= 0 and key < nums[sortedInd])\n\t\t\tnums[sortedInd + 1] = nums[sortedInd];\n\t\tnums[sortedInd + 1] = key;\n\t}\n}\n```\n\n2. Method2: Recursive (TLE) [T(n) = O(n^2)]\n\n```\nvoid recInsert(vector<int> &nums, int val) {\n\tif (!nums.size() or nums.back() <= val)\n\t\treturn nums.push_back(val);\n\tint last = nums.back();\n\tnums.pop_back();\n\trecInsert(nums, val);\n\tnums.push_back(last);\n}\n\t\nvoid recInsertionSort(vector<int> &nums) {\n\tif (nums.size() <= 1) return;\n\tint last = nums.back();\n\tnums.pop_back();\n\trecInsertionSort(nums);\n\trecInsert(nums, last);\n}\n```\n\n##### Selection Sort\n\n1. Method1: Standard (TLE) [T(n) = Theta(n^2)]\n\n```\nvoid selectionSort(vector<int> &nums) {\n\tint minInd, startInd, currInd, size = nums.size();\n\tif (size <= 1) return;\n\tfor (startInd = 0; startInd < size - 1; startInd++) {\n\t\tfor (currInd = startInd + 1, minInd = startInd; currInd < size; currInd++)\n\t\t\tif (nums[minInd] > nums[currInd])\n\t\t\t\tminInd = currInd;\n\t\tif (minInd != startInd)\n\t\t\tswap(nums[startInd], nums[minInd]);\n\t}\n}\n```\n\n2. Method2: Standard using inbuilt (TLE) [T(n) = Theta(n^2)]\n\n```\nvoid selectionSort(vector<int> &nums) {\n\tint minInd, startInd, size = nums.size();\n\tif (size <= 1) return;\n\tfor (startInd = 0; startInd < size - 1; startInd++) {\n\t\tminInd = min_element(nums.begin() + startInd, nums.end()) - nums.begin();\n\t\tif (minInd != startInd)\n\t\t\tswap(nums[startInd], nums[minInd]);\n\t}\n}\n```\n\n##### Bubble Sort (TLE) [T(n) = Theta(n^2)]\n\n```\nvoid bubbleSort(vector<int> &nums) {\n\tint endInd, currInd, size = nums.size();\n\tif (size <= 1) return;\n\tfor (endInd = size - 1; endInd; endInd--)\n\t\tfor (currInd = 0; currInd < endInd; currInd++)\n\t\t\tif (nums[currInd] > nums[currInd + 1])\n\t\t\t\tswap(nums[currInd], nums[currInd + 1]);\n}\n```\n\n##### Quick Sort\n\n1. Method1: Standard (TLE) [T(n) = O(n^2)]\n\n```\nint partitionArray(vector<int> &nums, int low, int high) {\n\tif (low >= high) return -1;\n\tint pivot = low, l = pivot + 1, r = high;\n\twhile (l <= r)\n\t\tif (nums[l] < nums[pivot]) l++;\n\t\telse if (nums[r] >= nums[pivot]) r--;\n\t\telse swap(nums[l], nums[r]);\n\tswap(nums[pivot], nums[r]);\n\treturn r;\n}\n\t\nvoid quickSort(vector<int> &nums, int low, int high) {\n\tif (low >= high) return;\n\tint pivot = partitionArray(nums, low, high);\n\tquickSort(nums, low, pivot);\n\tquickSort(nums, pivot + 1, high);\n}\n```\n\n2. Method2: Randomised (TLE) [T(n) = O(n * lgn) on avg. but O(n^2) in worst case]\n\n```\nint partitionArray(vector<int> &nums, int low, int high) {\n\tif (low >= high) return -1;\n\tint pivot = low, l = pivot + 1, r = high;\n\twhile (l <= r)\n\t\tif (nums[l] < nums[pivot]) l++;\n\t\telse if (nums[r] >= nums[pivot]) r--;\n\t\telse swap(nums[l], nums[r]);\n\tswap(nums[pivot], nums[r]);\n\treturn r;\n}\n\nvoid quickSort(vector<int> &nums, int low, int high) {\n\tif (low >= high) return;\n\tswap(nums[low + rand() % (high - low + 1)], nums[low]);\n\tint pivot = partitionArray(nums, low, high);\n\tquickSort(nums, low, pivot);\n\tquickSort(nums, pivot + 1, high);\n}\n```\n\n##### Merge Sort\n\n1. Method1: Outplace Merging (Accepted) [T(n) = O(n * lgn)]\n\n```\nvoid outPlaceMerge(vector<int> &nums, int low, int mid, int high) {\n\tif (low >= high) return;\n\tint l = low, r = mid + 1, k = 0, size = high - low + 1;\n\tvector<int> sorted(size, 0);\n\twhile (l <= mid and r <= high)\n\t\tsorted[k++] = nums[l] < nums[r] ? nums[l++] : nums[r++];\n\twhile (l <= mid) \n\t\tsorted[k++] = nums[l++];\n\twhile (r <= high) \n\t\tsorted[k++] = nums[r++];\n\tfor (k = 0; k < size; k++)\n\t\tnums[k + low] = sorted[k];\n}\n\nvoid mergeSort(vector<int> &nums, int low, int high) {\n\tif (low >= high) return;\n\tint mid = (high - low) / 2 + low;\n\tmergeSort(nums, low, mid);\n\tmergeSort(nums, mid + 1, high);\n\toutPlaceMerge(nums, low, mid, high);\n}\n```\n\n2. Method2: Inplace Merging (TLE) [T(n) = O(n^2)]\n\n```\nvoid inPlaceMerge(vector<int> &nums, int low, int mid, int high) {\n\tif (low >= high) return;\n\tint l = low, r = mid + 1, size = high - low + 1;\n\twhile (l <= mid and r <= high) {\n\t\tif (nums[l] <= nums[r]) l++;\n\t\telse {\n\t\t\tint val = nums[r];\n\t\t\tfor (int k = r++; k > l; k--)\n\t\t\t\tnums[k] = nums[k - 1];\n\t\t\tnums[l++] = val;\n\t\t\tmid++;\n\t\t}\n\t}\n}\n\nvoid mergeSort(vector<int> &nums, int low, int high) {\n\tif (low >= high) return;\n\tint mid = (high - low) / 2 + low;\n\tmergeSort(nums, low, mid);\n\tmergeSort(nums, mid + 1, high);\n\tinPlaceMerge(nums, low, mid, high);\n}\n```\n\n##### Generalised Couting Sort (Accepted) [T(n) = Theta(max(n, m)) where m = max(Arr)]\n\n```\nvoid countingSort(vector<int> &nums, bool isAscending=true) {\n\tint minVal = *min_element(nums.begin(), nums.end());\n\tint maxVal = *max_element(nums.begin(), nums.end());\n\t// int freqSize = maxVal - minVal + 1 is enough i.e its also correct\n\tint freqSize = maxVal - minVal + 1 + 1, size = nums.size();\n\tvector<int> freq(freqSize, 0), sorted(size, 0);\n\tfor (int ind = 0; ind < size; ind++)\n\t\tfreq[nums[ind] - minVal]++;\n\tif (isAscending)\n\t\tfor (int ind = 1; ind < freqSize; ind++)\n\t\t\tfreq[ind] += freq[ind - 1];\n\telse\n\t\tfor (int ind = freqSize - 2; ind >= 0; ind--)\n\t\t\tfreq[ind] += freq[ind + 1];\n\t// for stable sorting start ind from end and decrement till 0\n\tfor (int ind = size - 1; ind >= 0; ind--)\n\t\tsorted[freq[nums[ind] - minVal]-- - 1] = nums[ind];\n\tnums = sorted;\n}\n```\n\n##### Generalised Radix Sort \n\n1. Method1: Using MinVal (Accepted) [T(n) = Theta(n)]\n\n```\nint getDigit(int num, int factor) {\n\treturn (abs(num) / abs(factor)) % 10;\n}\n\nvoid radixCountingSort(vector<int> &nums, int factor) {\n\tint freqSize = 10, size = nums.size();\n\tvector<int> freq(freqSize, 0), sorted(size, 0);\n\tfor (int ind = 0; ind < size; ind++)\n\t\tfreq[getDigit(nums[ind], factor)]++;\n\tfor (int ind = 1; ind < freqSize; ind++)\n\t\tfreq[ind] += freq[ind - 1];\n\t// for stable sorting start ind from end and decrement till 0\n\tfor (int ind = size - 1; ind >= 0; ind--)\n\t\tsorted[freq[getDigit(nums[ind], factor)]-- - 1] = nums[ind];\n\tnums = sorted;\n}\n\nvoid radixSort(vector<int> &nums) {\n\tint minVal = *min_element(nums.begin(), nums.end());\n\tfor (auto &num : nums) num -= minVal;\n\tint factor = 1, maxVal = *max_element(nums.begin(), nums.end());\n\twhile (maxVal / factor) {\n\t\tradixCountingSort(nums, factor);\n\t\tfactor *= 10;\n\t}\n\tfor (auto &num : nums) num += minVal;\n}\n```\n\n2. Method2: Using Partitioning (Accepted) [T(n) = Theta(n)]\n\n\tIdea is to partition the Array with pivot as mininum Positive Element and thus, left half array is of -ve no.s (if any) and right half array is of +ve no.s (if any). Finally we apply Radix Sort on both the parts.\n\tNote that to sort -ve no.s only with Radix Sort, we need to reverse sort the -ve no.s (eg: [-5,-4,-3] and [3,4,5])\n\n```\nint partitionArray(vector<int> &nums, int low=0, int high=-1) {\n\thigh = high < 0 ? nums.size() - 1 : high;\n\tif (low >= high) return -1;\n\tint pivot = low, l = pivot + 1, r = high;\n\twhile (l <= r)\n\t\tif (nums[l] < nums[pivot]) l++;\n\t\telse if (nums[r] >= nums[pivot]) r--;\n\t\telse swap(nums[l], nums[r]);\n\tswap(nums[pivot], nums[r]);\n\treturn r;\n}\n\nint getDigit(int num, int factor) {\n\treturn (abs(num) / abs(factor)) % 10;\n}\n\npair<int, int> getMinAndNonNegMinInd(vector<int> &nums) {\n\tint minInd = nums.size(), minVal = INT_MAX;\n\tint nonNegMinInd = nums.size(), minNonNegVal = INT_MAX;\n\tfor (int i = 0; i < nums.size(); i++) {\n\t\tif (nums[i] >= 0 and nums[i] < minNonNegVal)\n\t\t\tnonNegMinInd = i, minNonNegVal = nums[i];\n\t\tif (nums[i] < minVal)\n\t\t\tminInd = i, minVal = nums[i];\n\t}\n\treturn {minInd, nonNegMinInd};\n}\n\nint radixSortPartionArray(vector<int> &nums) {\n\tauto [minInd, nonNegMinInd] = getMinAndNonNegMinInd(nums);\n\tif (nonNegMinInd < nums.size()) {\n\t\tif (nonNegMinInd) swap(nums[0], nums[nonNegMinInd]);\n\t\tif (nums[minInd] >= 0) nonNegMinInd = 0;\n\t\telse nonNegMinInd = partitionArray(nums);\n\t}\n\treturn nonNegMinInd;\n}\n\nvoid radixCountingSort(vector<int> &nums, int factor, int low, int high, bool isAscending=true) {\n\tif (low >= high) return;\n\tint freqSize = 10, size = high - low + 1;\n\tvector<int> freq(freqSize, 0), sorted(size, 0);\n\tfor (int ind = 0; ind < size; ind++)\n\t\tfreq[getDigit(nums[ind + low], factor)]++;\n\tif (isAscending)\n\t\t// reference: http://analgorithmaday.blogspot.com/2011/03/counting-sortlinear-time.html\n\t\tfor (int ind = 1; ind < freqSize; ind++)\n\t\t\tfreq[ind] += freq[ind - 1];\n\telse\n\t\tfor (int ind = freqSize - 2; ind >= 0; ind--)\n\t\t\tfreq[ind] += freq[ind + 1];\n\t// for stable sorting start ind from end and decrement till 0\n\tfor (int ind = size - 1; ind >= 0; ind--)\n\t\tsorted[freq[getDigit(nums[ind + low], factor)]-- - 1] = nums[ind + low];\n\tfor (int ind = 0; ind < size; ind++)\n\t\tnums[ind + low] = sorted[ind];\n}\n\nvoid radixSortHelper(vector<int> &nums, int low, int high, bool isAscending=true) {\n\tif (low >= high) return;\n\tint maxVal = *max_element(nums.begin() + low, nums.begin() + high + 1, [] (int &a, int &b) {\n\t\treturn abs(a) < abs(b);\n\t});\n\tint factor = 1;\n\twhile (maxVal / factor) {\n\t\tradixCountingSort(nums, factor, low, high, isAscending);\n\t\tfactor *= 10;\n\t}\n}\n\nvoid radixSort(vector<int> &nums) {\n\tint nonNegMinInd = radixSortPartionArray(nums);\n\tif (nonNegMinInd <= 1)\n\t\tradixSortHelper(nums, nonNegMinInd + 1, nums.size() - 1);\n\telse {\n\t\tradixSortHelper(nums, 0, nonNegMinInd - 1, false);\n\t\tradixSortHelper(nums, nonNegMinInd + 1, nums.size() - 1);\n\t}\n}\n```\n\n##### Heap Sort (Accepted) [T(n) = O(n * lgn)]\n\n```\nvoid heapifyDown(vector<int> &nums, int size, int rootInd, bool isMin=false) {\n\tif (size <= 1 or rootInd < 0 or rootInd >= size - 1) return;\n\tint keyInd = rootInd, leftChildInd = 2 * rootInd + 1, rightChildInd = 2 * rootInd + 2;\n\tif (leftChildInd < size and (isMin ? nums[leftChildInd] < nums[keyInd] : nums[leftChildInd] > nums[keyInd]))\n\t\tkeyInd = leftChildInd;\n\tif (rightChildInd < size and (isMin ? nums[rightChildInd] < nums[keyInd] : nums[rightChildInd] > nums[keyInd]))\n\t\tkeyInd = rightChildInd;\n\tif (nums[keyInd] != nums[rootInd]) {\n\t\tswap(nums[rootInd], nums[keyInd]);\n\t\theapifyDown(nums, size, keyInd, isMin);\n\t}\n}\n\nvoid heapifyArray(vector<int> &nums, bool isMin=false) {\n\tint size = nums.size();\n\tif (size <= 1) return;\n\tint tailRootInd = (size >> 1) - 1;\n\tfor (int rootInd = tailRootInd; rootInd >= 0; rootInd--)\n\t\theapifyDown(nums, size, rootInd, isMin);\n}\n\nvoid heapSort(vector<int> &nums) {\n\tif (nums.size() <= 1) return;\n\theapifyArray(nums);\n\tfor (int size = nums.size() - 1; size; size--) {\n\t\tswap(nums[size], nums[0]);\n\t\theapifyDown(nums, size, 0);\n\t}\n}\n```\n\n##### Bucket Sort\n\nBucket sort\'s performance depends upon the uniformity (distribution) of the input data. Hence, I am not discussing it here (I have not submitted it as well for given constraints). For more info on this Algo, you can google it.\n\n##### Among above, Counting Sort was fastest in Leetcode OJ.\n\n**IMP:** You can also bookmark/ subscribe to this post so as to revise above Sorting Algorithms whenvever you need to. \n\n**NOTE:** \n*If you find this post helpful then please **upvote**. It keeps me **motivated** to post such helpful solutions. Thanks!*\n\n**PS:**\nI have also written posts on Kadane\'s Algorithm and Follow up Questions [C++] in a cleaner way [here](https://leetcode.com/problems/maximum-subarray/discuss/1470547/C++-Easy-and-Clean-Solution-or-Fastest:-0ms-or-All-Methods-or-Follow-Ups-or-Detailed-Explanation) on leetcode.\n*Do check it out/ bookmark (and upvote :)) to revise those concepts for the interview. Thanks!*\n\n | 930 | 1 | ['Merge Sort', 'Bucket Sort', 'Radix Sort', 'Counting Sort', 'C++'] | 34 |
sort-an-array | [Python] bubble, insertion, selection, quick, merge, heap | python-bubble-insertion-selection-quick-q027g | in real life, we use\n\n def sortArray(self, nums):\n return sorted(nums)\n\n\nbut we are playing leetcode right now...\n\nclass Solution:\n def so | cc189 | NORMAL | 2019-04-18T00:22:09.408179+00:00 | 2020-05-25T08:09:32.982186+00:00 | 65,429 | false | in real life, we use\n```\n def sortArray(self, nums):\n return sorted(nums)\n```\n\nbut we are playing leetcode right now...\n```\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n # self.quickSort(nums)\n # self.mergeSort(nums)\n # self.bubbleSort(nums)\n # self.insertionSort(nums)\n\t\t# self.selectionSort(nums)\n self.heapSort(nums)\n return nums\n \n\t# @bubbleSort, TLE\n def bubbleSort(self, nums):\n n = len(nums)\n for i in range(n):\n for j in range(0, n - i - 1):\n if nums[j] > nums[j + 1]:\n nums[j], nums[j + 1] = nums[j + 1], nums[j]\n \n\t# @insertionSort, TLE\n def insertionSort(self, nums): \n for i in range(1, len(nums)): \n key = nums[i]\n j = i-1\n while j >= 0 and key < nums[j] : \n nums[j + 1] = nums[j] \n j -= 1\n nums[j + 1] = key\n\t\t\n\t# @selectionSort, TLE\n\tdef selectionSort(self, nums):\n\t\tfor i in range(len(nums)):\n\t\t\t_min = min(nums[i:])\n\t\t\tmin_index = nums[i:].index(_min)\n\t\t\tnums[i + min_index] = nums[i]\n\t\t\tnums[i] = _min\n\t\treturn nums\n \n\t# @quickSort\n def quickSort(self, nums):\n def helper(head, tail):\n if head >= tail: return \n l, r = head, tail\n m = (r - l) // 2 + l\n pivot = nums[m]\n while r >= l:\n while r >= l and nums[l] < pivot: l += 1\n while r >= l and nums[r] > pivot: r -= 1\n if r >= l:\n nums[l], nums[r] = nums[r], nums[l]\n l += 1\n r -= 1\n helper(head, r)\n helper(l, tail)\n\n helper(0, len(nums)-1)\n return nums\n \n\t# @mergeSort\n def mergeSort(self, nums): \n if len(nums) > 1: \n mid = len(nums)//2\n L = nums[:mid] \n R = nums[mid:] \n\n self.mergeSort(L)\n self.mergeSort(R)\n\n i = j = k = 0\n\n while i < len(L) and j < len(R): \n if L[i] < R[j]: \n nums[k] = L[i] \n i+=1\n else: \n nums[k] = R[j] \n j+=1\n k+=1\n \n while i < len(L): \n nums[k] = L[i] \n i+=1\n k+=1\n\n while j < len(R): \n nums[k] = R[j] \n j+=1\n k+=1\n \n # @heapSort\n def heapSort(self, nums):\n def heapify(nums, n, i): \n l = 2 * i + 1\n r = 2 * i + 2\n\t\t\t\n largest = i\n if l < n and nums[largest] < nums[l]: \n largest = l \n\n if r < n and nums[largest] < nums[r]: \n largest = r \n\n if largest != i: \n nums[i], nums[largest] = nums[largest], nums[i]\n \n heapify(nums, n, largest)\n \n n = len(nums) \n\n for i in range(n//2+1)[::-1]: \n heapify(nums, n, i) \n\n for i in range(n)[::-1]: \n nums[i], nums[0] = nums[0], nums[i]\n heapify(nums, i, 0) \n```\n\n---\nSort Objects:\n\n[Pyhon] \n```python\nclass Node:\n def __init__(self, val):\n self.val = val\n\n def __cmp__(self, other):\n if self.val < other.val:\n return -1\n elif self.val > other.val:\n return 1\n else:\n\t\t\treturn 0\n\nclass Solution(object):\n def sortArray(self, nums):\n nodes = [Node(n) for n in nums]\n return [node.val for node in sorted(nodes)]\n```\n\n[Pyhon3] notice, in python3, we don\'t have `__cmp__(self, other)` any more\n```python\nclass Node:\n def __init__(self, val):\n self.val = val\n\t\n\t# lt means less than, le means less or equal than etc.\n def __lt__(self, other):\n return self.val < other.val\n # incase you need more logic\n # def __le__(self, other):\n # return self.val <= other.val\n # def __eq__(self, other):\n # return self.val == other.val\n # def __ne__(self, other):\n # return self.val != other.val\n # def __gt__(self, other):\n # return self.val > other.val\n # def __ge__(self, other):\n # return self.val >= other.val\n\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n nodes = [Node(n) for n in nums]\n return [node.val for node in sorted(nodes)]\n```\n | 407 | 4 | [] | 31 |
sort-an-array | 7 Sorting Algorithms (quick sort, top-down/bottom-up merge sort, heap sort, etc.) | 7-sorting-algorithms-quick-sort-top-down-ab7t | 7 Sorting Algorithms:\n1. quick sort\n2. top-down merge sort\n3. bottom-up merge sort\n4. heap sort\n5. selection sort\n6. insertion sort\n7. bubble sort (TLE)\ | dreamyjpl | NORMAL | 2020-01-28T01:52:21.916753+00:00 | 2020-02-10T01:18:18.062313+00:00 | 50,862 | false | 7 Sorting Algorithms:\n1. quick sort\n2. top-down merge sort\n3. bottom-up merge sort\n4. heap sort\n5. selection sort\n6. insertion sort\n7. bubble sort (TLE)\n\nThe implementations are as below:\n1. quick sort\n```java\nclass Solution {\n public List<Integer> sortArray(int[] nums) {\n List<Integer> res = new ArrayList<>();\n if (nums == null || nums.length == 0) return res;\n quickSort(nums, 0, nums.length - 1);\n for (int i : nums) res.add(i);\n return res;\n }\n private void quickSort(int[] nums, int l, int r) {\n if (l >= r) return;\n int mid = partition(nums, l, r);\n quickSort(nums, l, mid);\n quickSort(nums, mid + 1, r);\n }\n private int partition(int[] nums, int l, int r) {\n int pivot = nums[l];\n while (l < r) {\n while (l < r && nums[r] >= pivot) r--;\n nums[l] = nums[r];\n while (l < r && nums[l] <= pivot) l++;\n nums[r] = nums[l];\n }\n nums[l] = pivot;\n return l;\n }\n}\n```\n\n2. top-down merge sort\n```java\nclass Solution {\n public List<Integer> sortArray(int[] nums) {\n List<Integer> res = new ArrayList<>();\n if (nums == null || nums.length == 0) return res;\n mergeSort(nums, 0, nums.length - 1);\n for (int i : nums) res.add(i);\n return res;\n }\n private void mergeSort(int[] nums, int l, int r) {\n if (l >= r) return;\n int mid = l + (r - l) / 2;\n mergeSort(nums, l, mid);\n mergeSort(nums, mid + 1, r);\n merge(nums, l, r);\n }\n private void merge(int[] nums, int l, int r) {\n int mid = l + (r - l) / 2;\n int[] tmp = new int[r - l + 1];\n int i = l, j = mid + 1, k = 0;\n while (i <= mid || j <= r) {\n if (i > mid || j <= r && nums[i] > nums[j]) {\n tmp[k++] = nums[j++];\n } else {\n tmp[k++] = nums[i++];\n }\n }\n System.arraycopy(tmp, 0, nums, l, r - l + 1);\n }\n}\n```\n\n3. bottom-up merge sort\n```java\nclass Solution {\n public List<Integer> sortArray(int[] nums) {\n List<Integer> res = new ArrayList<>();\n if (nums == null || nums.length == 0) return res;\n mergeSort2(nums);\n for (int i : nums) res.add(i);\n return res;\n }\n private void mergeSort2(int[] nums) {\n for (int size = 1; size < nums.length; size *= 2) {\n for (int i = 0; i < nums.length - size; i += 2 * size) {\n int mid = i + size - 1;\n int end = Math.min(i + 2 * size - 1, nums.length - 1);\n merge2(nums, i, mid, end);\n }\n }\n }\n private void merge2(int[] nums, int l, int mid, int r) {\n int[] tmp = new int[r - l + 1];\n int i = l, j = mid + 1, k = 0;\n while (i <= mid || j <= r) {\n if (i > mid || j <= r && nums[i] > nums[j]) {\n tmp[k++] = nums[j++];\n } else {\n tmp[k++] = nums[i++];\n }\n }\n System.arraycopy(tmp, 0, nums, l, r - l + 1);\n }\n}\n```\n\n4. heap sort\n```java\nclass Solution {\n public List<Integer> sortArray(int[] nums) {\n List<Integer> res = new ArrayList<>();\n if (nums == null || nums.length == 0) return res;\n heapSort(nums);\n for (int i : nums) res.add(i);\n return res;\n }\n private void heapSort(int[] nums) {\n for (int i = nums.length / 2 - 1; i >= 0; i--) {\n heapify(nums, i, nums.length - 1);\n }\n for (int i = nums.length - 1; i >= 1; i--) {\n swap(nums, 0, i);\n heapify(nums, 0, i - 1);\n }\n }\n private void heapify(int[] nums, int i, int end) {\n while (i <= end) {\n int l = 2 * i + 1, r = 2 * i + 2;\n int maxIndex = i;\n if (l <= end && nums[l] > nums[maxIndex]) maxIndex = l;\n if (r <= end && nums[r] > nums[maxIndex]) maxIndex = r;\n if (maxIndex == i) break;\n swap(nums, i, maxIndex);\n i = maxIndex;\n }\n }\n private void swap(int[] nums, int i, int j) {\n int tmp = nums[i];\n nums[i] = nums[j];\n nums[j] = tmp;\n }\n}\n```\n\n5. selection sort\n```java\nclass Solution {\n public List<Integer> sortArray(int[] nums) {\n List<Integer> res = new ArrayList<>();\n if (nums == null || nums.length == 0) return res;\n selectionSort(nums);\n for (int i : nums) res.add(i);\n return res;\n }\n private void selectionSort(int[] nums) {\n for (int i = 0; i < nums.length; i++) {\n int minIndex = i;\n for (int j = i + 1; j < nums.length; j++) {\n if (nums[j] < nums[minIndex]) minIndex = j;\n }\n if (minIndex != i) swap(nums, i, minIndex);\n }\n }\n private void swap(int[] nums, int i, int j) {\n nums[i] = nums[i] ^ nums[j];\n nums[j] = nums[i] ^ nums[j];\n nums[i] = nums[i] ^ nums[j];\n }\n}\n```\n\n6. insertion sort\n```java\nclass Solution {\n public List<Integer> sortArray(int[] nums) {\n List<Integer> res = new ArrayList<>();\n if (nums == null || nums.length == 0) return res;\n insertionSort(nums);\n for (int i : nums) res.add(i);\n return res;\n }\n private void insertionSort(int[] nums) {\n for (int i = 1; i < nums.length; i++) {\n for (int j = i; j >= 1; j--) {\n if (nums[j] >= nums[j - 1]) break;\n swap(nums, j, j - 1);\n }\n }\n }\n private void swap(int[] nums, int i, int j) {\n nums[i] = nums[i] ^ nums[j];\n nums[j] = nums[i] ^ nums[j];\n nums[i] = nums[i] ^ nums[j];\n }\n}\n```\n\n7. bubble sort (TLE)\n```java\nclass Solution {\n public List<Integer> sortArray(int[] nums) {\n List<Integer> res = new ArrayList<>();\n if (nums == null || nums.length == 0) return res;\n bubbleSort(nums);\n for (int i : nums) res.add(i);\n return res;\n }\n private void bubbleSort(int[] nums) {\n for (int k = nums.length - 1; k >= 1; k--) {\n for (int i = 0; i < k; i++) {\n if (nums[i] > nums[i + 1]) swap(nums, i, i + 1);\n }\n }\n }\n private void swap(int[] nums, int i, int j) {\n nums[i] = nums[i] ^ nums[j];\n nums[j] = nums[i] ^ nums[j];\n nums[i] = nums[i] ^ nums[j];\n }\n}\n``` | 302 | 3 | ['Sorting', 'Merge Sort', 'Java'] | 27 |
sort-an-array | 7-line quicksort to write in interviews (Python) | 7-line-quicksort-to-write-in-interviews-cr9k1 | This is my go-to solution when asked this question in interviews. It\'s short, simple to write, very bug free, and looks very clean and pythonic. Writing this v | twohu | NORMAL | 2019-04-18T07:11:23.634157+00:00 | 2019-06-02T06:30:30.263362+00:00 | 27,278 | false | This is my go-to solution when asked this question in interviews. It\'s short, simple to write, very bug free, and looks very clean and pythonic. Writing this version of quicksort is very effective in communicating your understanding of the algorithm and its concepts to the interviewer.\n\nThe only tradeoff in the code is it uses a bit of extra space. You can always write the messier in-place solution as a followup.\n```\ndef quicksort(self, nums):\n if len(nums) <= 1:\n return nums\n\n pivot = random.choice(nums)\n lt = [v for v in nums if v < pivot]\n eq = [v for v in nums if v == pivot]\n gt = [v for v in nums if v > pivot]\n\n return self.quicksort(lt) + eq + self.quicksort(gt)\n```\nRuntime: O(nlogn) expected, O(n^2) worst case.\nWith a proper choice of pivot (using the median of medians algorithm), the runtime can be reduced to strict O(nlogn).\nSpace: O(n) expected, O(n^2) worst case | 215 | 12 | ['Sorting', 'Python'] | 32 |
sort-an-array | Python 3 (Eight Sorting Algorithms) (With Explanation) | python-3-eight-sorting-algorithms-with-e-b5vw | Sorting Algorithms:\n1. Selection Sort\n2. Bubble Sort\n3. Insertion Sort\n4. Binary Insertion Sort\n5. Counting Sort\n6. QuickSort\n7. Merge Sort\n8. Bucket So | junaidmansuri | NORMAL | 2019-12-26T15:00:09.095166+00:00 | 2019-12-27T07:34:36.043267+00:00 | 21,630 | false | _Sorting Algorithms:_\n1. Selection Sort\n2. Bubble Sort\n3. Insertion Sort\n4. Binary Insertion Sort\n5. Counting Sort\n6. QuickSort\n7. Merge Sort\n8. Bucket Sort\n____________________________________________\n\n1) _Selection Sort:_\nThis program sorts the list by finding the minimum of the list, removing it from the original list, and appending it onto the output list. As it finds the minumum during each iteration, the length of the original list gets shorter by one and the length of the output list gets longer by one. This program uses the min function with a lambda function to find the index of the minimum value in the unsorted list. The output list is created using a list comprehension. This algorithm is O(n\xB2). It is able to sort 8 out of 10 test cases but exceeds the time limit on the ninth test case.\n\n```\nclass Solution:\n def sortArray(self, N: List[int]) -> List[int]:\n L = len(N)\n return [N.pop(min(range(L-i), key = lambda x: N[x])) for i in range(L)]\n\t\t\n\t\t\n```\n2) _Bubble Sort:_\nThis program sorts the list by looping through the original list and finding any adjacent pairs of numbers that are out of order. If it finds such a pair, it switches their locations. It continues to check for adjacent pairs that are out of order until it has completed the pass through the list. If it finds a pair, it will set B = 1 which tells the program to pass through the list again and continue switching adjacent values that are out of order. If it can make it through the list without finding any adjacent pairs that are out of order, we can conclude that the list is sorted. The value of B will stay 0 and the outer while loop will end. This algorithm is O(n\xB2). It is able to sort 8 out of 10 test cases but exceeds the time limit on the ninth test case.\n\n```\nclass Solution:\n def sortArray(self, N: List[int]) -> List[int]:\n L, B = len(N), 1\n while B:\n B = 0\n for i in range(L-1):\n if N[i] > N[i+1]: N[i], N[i+1], B = N[i+1], N[i], 1\n return N\n\t\t\n\t\t\n```\n3) _Insertion Sort:_\nThis program sorts the list by sequentially inserting each element into the proper location within the sorted front portion of the original list. It starts by inserting the second number into the proper location within the first two numbers. It then inserts the third number into the proper location within the first three numbers. After each iteration, the front portion of the list (i.e. the sorted portion) will grow in length by 1. A number is removed from the back portion of the list (i.e. the unsorted portion) and placed into the appropriate location in the sorted portion of the list. Once we place the last number into the correct location within the sorted numbers, the entire list will have become sorted. This algorithm is O(n\xB2). It is able to sort 9 out of 10 test cases but exceeds the time limit on the last test case.\n\n```\nclass Solution:\n def sortArray(self, N: List[int]) -> List[int]:\n L = len(N)\n for i in range(1,L):\n for j in range(0,i):\n if N[i] < N[j]:\n N.insert(j, N.pop(i))\n break\n return N\t\t\n\t\t\n\t\t\n```\n4) _Binary Insertion Sort:_ (944 ms) (beats ~6%)\nThis program sorts the list by sequentially inserting each element into the proper location within the sorted front portion of the original list. It starts by inserting the second number into the proper location within the first two numbers. It then inserts the third number into the proper location within the first three numbers. After each iteration, the front portion of the list (i.e. the sorted portion) will grow in length by 1. A number is removed from the back portion of the list (i.e. the unsorted portion) and placed into the appropriate location in the sorted portion of the list. Once we place the last number into the correct location within the sorted numbers, the entire list will have become sorted. This algorithm is still O(n\xB2). It is not O(n log n) despite using a binary search because the insertion step is time consuming. The advantage of the binary insertion sort versus the generic insertion sort is that this one does a binary search which is O(log i) (for the ith iteration) while the generic one does a linear search which is O(i) (for the ith iteration). Because of this improvement, this program is able to sort all 10 cases although it is not a very fast approach compared to some of the other algorithms.\n```\nclass Solution:\n def sortArray(self, N: List[int]) -> List[int]:\n L = len(N)\n for i in range(1,L): bisect.insort_left(N, N.pop(i), 0, i)\n return N\n\t\t\n\t\t\n```\n5) _Counting Sort:_ (136 ms) (beats ~97%)\nThis program starts by creating a dictionary of key-value pairs that records the total count of each element of the original list. The minimum and maximum value of the list is also found. The program then loops through every integer between the min and max value (in order) and appends that number to the output list based on its count within the original list. For example, if the number 3 occurs 4 times in the original list, then the output list will be extended by [3,3,3,3]. The output will be the sorted form of the original list as it consists of an ordered list of the numbers in the original list. This approach is a linear time sorting algorithm that sorts in O(n+k) time, where n is the number of elements and k is the statistical range of the dataset (i.e. max(N) - min(N)). It is able to sort all test cases in only 136 ms.\n\n```\nclass Solution:\n def sortArray(self, N: List[int]) -> List[int]:\n C, m, M, S = collections.Counter(N), min(N), max(N), []\n for n in range(m,M+1): S.extend([n]*C[n])\n return S\n\t\t\n\t\t\n```\n6) _QuickSort:_ (316 ms) (beats ~54%)\nThis program uses a recursive Divide and Conquer approach to sort the original list. The recursive function ```quicksort``` is called on the original list. A ```partition``` subroutine then takes the input and pivots around the median position\'s value (pivot value). Specifically, it uses swaps to place numbers less than the pivot value to the left of the pivot index and numbers greater than the pivot value to the right of the pivot index. At the end of the ```partition``` subroutine, we are left with the situation that the value at the pivot index is located at what will be its final position in the sorted output. We then do a quicksort on these left and right halves and continue this rescursively until we get a list of length 1 which is already sorted. Once all of the quicksort subroutines are completed, the entire list is in sorted order and the initial quicksort call completes and we can return the sorted list. In the average case, this method is O(n log n). In the worst case, however, it is O(n\xB2). It is able to sort all test cases in 316 ms.\n\n```\nclass Solution:\n def sortArray(self, N: List[int]) -> List[int]:\n def quicksort(A, I, J):\n if J - I <= 1: return\n p = partition(A, I, J)\n quicksort(A, I, p), quicksort(A, p + 1, J)\n \n def partition(A, I, J):\n A[J-1], A[(I + J - 1)//2], i = A[(I + J - 1)//2], A[J-1], I\n for j in range(I,J):\n if A[j] < A[J-1]: A[i], A[j], i = A[j], A[i], i + 1\n A[J-1], A[i] = A[i], A[J-1]\n return i\n \n quicksort(N,0,len(N))\n return N\n\t\t\n\t\t\n```\n7) _Merge Sort:_ (324 ms) (beats ~51%)\nThis program uses a recursive Divide and Conquer approach to sort the original list. The recursive function ```mergesort``` is called on the original list. The function divides the list into two halves (a left half and a right half) and calls the mergesort routine recursively on each of them. Once each half is sorted, the ```merge``` subroutine merges the two lists into one list by appending the lower number from the front of each half into the output list S. If one list is exhausted before the other, the remaining list is appended onto S before S is returned. The ```mergesort``` function recursively calls on lists that are half the size of the previous list until their length is 1. Such a list is trivially sorted and that list can be returned for ```merge``` to join with another list. Eventually all the small lists are merged back into larger lists until the final sorted version of the original list is formed. This method is O(n log n). It is able to sort all test cases in 324 ms.\n\n```\nclass Solution:\n def sortArray(self, N: List[int]) -> List[int]:\n def mergesort(A):\n LA = len(A)\n if LA == 1: return A\n LH, RH = mergesort(A[:LA//2]), mergesort(A[LA//2:])\n return merge(LH,RH)\n\n def merge(LH, RH):\n LLH, LRH = len(LH), len(RH)\n S, i, j = [], 0, 0\n while i < LLH and j < LRH:\n if LH[i] <= RH[j]: i, _ = i + 1, S.append(LH[i])\n else: j, _ = j + 1, S.append(RH[j])\n return S + (RH[j:] if i == LLH else LH[i:])\n \n return mergesort(N)\t\t\n\t\t\n\t\t\n```\n8) _Bucket Sort:_ (196 ms) (beats ~78%)\nThis program sorts the original list by dividing the numbers in the list into 1000 non-overlapping adjacent buckets. The ```bucketsort``` function finds the statistical range of the numbers in the original list (i.e. R = max(N) - min(N)) to help map each number into the appropriate bucket. The ```insertion_sort``` subroutine is then used to sort the numbers in each of these buckets. The sorted adjacent buckets are then appended onto the output list S which is the sorted version of the original list. This method is O(n\xB2) in the worst case and O(n) on average. The large number of buckets (1000 buckets) was chosen to decrease the time needed to sort the final test case. If too few buckets are used, the time limit gets exceeded for the final test case. It is able to sort all test cases in 196 s.\n\n```\nclass Solution:\n def sortArray(self, N: List[int]) -> List[int]:\n def insertion_sort(A):\n for i in range(1,len(A)):\n for j in range(0,i):\n if A[i] < A[j]:\n A.insert(j, A.pop(i))\n break\n return A\n \n def bucketsort(A):\n buckets, m, S = [[] for _ in range(1000)], min(A), []\n R = max(A) - m\n if R == 0: return A\n for a in A: buckets[999*(a-m)//R]\n for b in buckets: S.extend(insertion_sort(b))\n return S\n \n return bucketsort(N)\n \n\t\t\n\t\t\n- Junaid Mansuri\n- Chicago, IL | 186 | 5 | ['Sorting', 'Counting Sort', 'Python', 'Python3'] | 10 |
sort-an-array | ✅💯🔥Explanations No One Will Give You🎓🧠3 Detailed Approaches🎯🔥Extremely Simple And Effective🔥 | explanations-no-one-will-give-you3-detai-7nsc | \n \n \n A year from now you may wish you had started today.\n \n \n \n --- Karen L | heir-of-god | NORMAL | 2024-07-25T06:30:11.144675+00:00 | 2024-07-25T06:34:31.438570+00:00 | 28,303 | false | <blockquote>\n <p>\n <b>\n A year from now you may wish you had started today.\n </b> \n </p>\n <p>\n --- Karen Lamb ---\n </p>\n</blockquote>\n\n# \uD83D\uDC51Problem Explanation and Understanding:\n\n## \uD83C\uDFAF Problem Description\nYou are given a list of integers `nums` and is asked to sort it. That\'s all, but you\'re not allowed to use built-in sort functions.\n\n## \uD83D\uDCE5\u2935\uFE0F Input:\n- Integer array `nums`\n\n## \uD83D\uDCE4\u2934\uFE0F Output:\nSorted array `nums`\n\n---\n\n# 1\uFE0F\u20E3\uD83E\uDD18 Approach 1: Quick Sort [Fu**ing TLE]\n\n# \uD83E\uDD14 Intuition\nOkay guys, someone have been talking about that in problems about sorting you need to write your own sorting function, at least for this problem I agree with you. I think it\'s ideal chance for us yo learn some sorting algorithms today, I\'ll cover here 3 options - Quick Sort, Merge Sort and Counting Sort. Let\'s start with first one.\n\n- Okay, let\'s think about how quick sort is working (in fact, this algorithm is broadly used in many languages since its perfomance where a stable sort is not needed):\n - Quick Sort resembles to Merge Sort, it\'s also recursive and also use `divide and conquer` principe, algorithm works with these steps in general:\n 1. Choose `pivot` - this is the number for which we will find `correct` location (where it will end after sotring whole array). What we know need to be true for this number after we foud its `correct` index is that: 1. All numbers to left are less than this number 2. All numbers to right are greater than or equal to this number. This ensures that position for this element was chosen correctly\n 2. In fact, for algorithm it doesn\'t matter which element we will choose as a pivot, at most cases it\'s either first, last or middle element in the array. Formula to know which pivote would be the best doesn\'t exist, so it\'s just our luck whether we will choose good pivot. Exists technique where among those 3 elements you "sort" them and choose the middle as pivot, but, obviously this doesn\'t ensure that this is the best choice of pivot.\n 3. I said that this algorithm is recursive, why? Because while we\'re looking for the pivot element index we\'re also "sorting" elements based on whether they smaller or bigger than pivot, than, when we place pivot in its place we know that at right all elements are bigger and at left they\'re all smaller, but we don\'t know whether they\'re sorted, so we call recursively QuickSort function on both left and right sides from our pivot. \n\n## Here\'s quick sort animation (not mine, source: [opengenus](https://iq.opengenus.org/quick-sort/))\n\n<img src="https://iq.opengenus.org/content/images/2018/02/quick_sort.gif" width="80%">\n\n\nAlso here\'s youtube video with example explanation: [video](https://youtu.be/Vtckgz38QHs?si=zTsYybILkYyioFCG)\n\n# \uD83D\uDC69\uD83C\uDFFB\u200D\uD83D\uDCBB Coding \n- Define the `partition` function to rearrange the elements around a pivot:\n - Choose a random pivot within the range `[low, high]`.\n - Initialize `write_ind_smaller` to `low` for elements smaller than the pivot.\n - Initialize `write_ind_greater` to `high` for elements greater than the pivot.\n - Use `cur` to iterate through the array from `low` to `write_ind_greater`.\n - Compare each element `num` at index `cur` with the pivot:\n - If `num` is smaller than the pivot, swap it with the element at `write_ind_smaller`, then increment both `write_ind_smaller` and `cur`.\n - If `num` is greater than the pivot, swap it with the element at `write_ind_greater`, then decrement `write_ind_greater`.\n - If `num` is equal to the pivot, just increment `cur`.\n - Return the index `write_ind_smaller` as the position of the pivot.\n- Define the `quick_sort` function to recursively sort the array:\n - Base case: If the range `[low, high]` is empty or has one element, return.\n - Call the `partition` function to partition the array and get the pivot index.\n - Recursively apply `quick_sort` to the left part `[low, pivot_ind - 1]`.\n - Recursively apply `quick_sort` to the right part `[pivot_ind + 1, high]`.\n- In the `Solution` class:\n - Call the `quick_sort` function to sort the input array `nums`.\n - Return the sorted array `nums`.\n\n# \uD83D\uDCD9 Complexity Analysis\n- \u23F0 Time complexity: O(n^2), basically average time complexity of quicksort is O(n * log n) but here\'s the worst case where the array is already sorted (For this implemantation the worst case is very unlikely to occur, quicksort perfomance is VERY dependable on how you choose your pivot index and I wrote randomized quicksort which choose random pivot index so it\'s very unlikely to every time choose the biggest or the smallest element)\n- \uD83E\uDDFA Space complexity: O(n), though average time complexity is O(log n) but in the worst scenario (array sorted, or as dumb testcase 17 where there\'re just too many 2) this is O(n) due to recursion call\n\n# \uD83D\uDCBB Code (works but gives TLE, so I decided to leave it only in Python to not waste my time)\n``` python []\nfrom random import randint\n\n\ndef partition(array: list[int], low: int, high: int) -> int:\n # this is function for choosing pivot and partitate the array\n pivot: int = array[randint(low, high)]\n write_ind_smaller: int = low # where to write elements smaller than pivot\n write_ind_greater: int = high # where to write elements greater than pivot\n cur = low\n\n while cur < write_ind_greater + 1:\n num = array[cur]\n if num < pivot:\n array[write_ind_smaller], array[cur] = array[cur], array[write_ind_smaller]\n write_ind_smaller += 1\n cur += 1\n elif num > pivot:\n array[write_ind_greater], array[cur] = array[cur], array[write_ind_greater]\n write_ind_greater -= 1\n else:\n cur += 1\n\n return write_ind_smaller # return index of the pivot\n\n\ndef quick_sort(array, low, high) -> None: # [low, high]\n # Base case: if range is empty or contains only 1 element\n if low >= high:\n return\n\n pivot_ind: int = partition(array, low, high)\n quick_sort(array, low, pivot_ind - 1) # left part\n quick_sort(array, pivot_ind + 1, high) # right part\n\n\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n quick_sort(nums, 0, len(nums) - 1)\n return nums\n```\n\n# 2\uFE0F\u20E3\uD83C\uDFC6 Approach 2: Merge Sort\n\n# \uD83E\uDD14 Intuition\n- Merge sort is quite resemble to quick sort but uses another technique - here we want to break our array on subarrays with 1 elements and then recursively reconstruct our array sorted.\n- You break problem on smaller parts - first break it on sorted arrays with 1 element, then "merge" this arrays comparing their elements one-by-one.\n- This works because we know that these smaller parts are already sorted when they came back from recursive function.\n- Unlike the quick sort here we do need to create new arrays so space complexity will be bigger in the average case.\n\nHere\'s very good animation how merge sort works: (source: [wikimedia](https://commons.wikimedia.org/wiki/File:Merge-sort-example-300px.gif))\n\n<img src="https://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif?20151222172210" width="80%">\n\n# \uD83D\uDC69\uD83C\uDFFB\u200D\uD83D\uDCBB Coding \n- Define the `merge_sort` function to sort an array:\n - Get the length `n` of the array.\n - If `n` is 1 or less, return as the array is already sorted.\n - Calculate the middle index `midle_ind`.\n - Split the array into `left_part` and `right_part`.\n - Recursively call `merge_sort` on `left_part` and `right_part`. By the time we call it here this arrays will be already sorted\n - Merge the sorted `left_part` and `right_part` back into the original array using the `merge` function.\n- Define the `merge` function to merge two sorted arrays:\n - Initialize pointers `p1` and `p2` to 0 for `array1` and `array2`.\n - Initialize `n1` and `n2` for the lengths of `array1` and `array2`.\n - Initialize `write_ind` to 0 for the position in `source_array`.\n - While either `p1` or `p2` is within bounds:\n - If `p1` is out of bounds or `array2[p2]` is smaller than `array1[p1]`, copy `array2[p2]` to `source_array` and increment `p2`.\n - If `p2` is out of bounds or `array1[p1]` is less than or equal to `array2[p2]`, copy `array1[p1]` to `source_array` and increment `p1`.\n - Increment `write_ind`.\n- In the `Solution` class:\n - Call the `merge_sort` function to sort the input array `nums`.\n - Return the sorted array `nums`.\n\n# \uD83D\uDCD8 Complexity Analysis\n- \u23F0 Time complexity: O(n * log n), in any case we divide array in half up to arrays of size 1 and then perform sorting an smaller parts so even in the worst case time complexity is still will be O(n * log n)\n- \uD83E\uDDFA Space complexity: O(n), since we\'re creating new `n` arrays of size 1 and also there some recursion stack space\n\n# \uD83D\uDCBB Code\n``` python []\ndef merge_sort(array: list[int]) -> None:\n n: int = len(array)\n if n <= 1:\n return\n midle_ind: int = n // 2\n left_part: list[int] = array[:midle_ind][:]\n right_part: list[int] = array[midle_ind:][:]\n\n merge_sort(left_part)\n merge_sort(right_part)\n merge(left_part, right_part, array)\n\n\ndef merge(array1: list[int], array2: list[int], source_array: list[int]) -> None:\n p1: int = 0\n p2: int = 0\n n1: int = len(array1)\n n2: int = len(array2)\n write_ind = 0\n\n while p1 < n1 or p2 < n2:\n if p1 == n1 or (p2 != n2 and array2[p2] < array1[p1]):\n source_array[write_ind] = array2[p2]\n p2 += 1\n elif p2 == n2 or array1[p1] <= array2[p2]:\n source_array[write_ind] = array1[p1]\n p1 += 1\n write_ind += 1\n\n\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n merge_sort(nums)\n return nums\n```\n``` C++ []\nvoid merge(vector<int>& array, int low, int mid, int high) {\n int n1 = mid - low + 1;\n int n2 = high - mid;\n vector<int> left_part(n1), right_part(n2);\n\n for (int i = 0; i < n1; ++i)\n left_part[i] = array[low + i];\n for (int i = 0; i < n2; ++i)\n right_part[i] = array[mid + 1 + i];\n\n int p1 = 0, p2 = 0, write_ind = low;\n while (p1 < n1 && p2 < n2) {\n if (left_part[p1] <= right_part[p2]) {\n array[write_ind] = left_part[p1++];\n } else {\n array[write_ind] = right_part[p2++];\n }\n ++write_ind;\n }\n\n while (p1 < n1)\n array[write_ind++] = left_part[p1++];\n\n while (p2 < n2)\n array[write_ind++] = right_part[p2++];\n}\n\nvoid merge_sort(vector<int>& array, int low, int high) {\n if (low >= high)\n return;\n\n int mid = low + (high - low) / 2;\n merge_sort(array, low, mid);\n merge_sort(array, mid + 1, high);\n merge(array, low, mid, high);\n}\n\nclass Solution {\npublic:\n vector<int> sortArray(vector<int>& nums) {\n merge_sort(nums, 0, nums.size() - 1);\n return nums;\n }\n};\n\n```\n``` JavaScript []\nvar sortArray = function(nums) {\n mergeSort(nums, 0, nums.length - 1);\n return nums;\n};\n\nfunction mergeSort(array, low, high) {\n if (low >= high) return;\n \n const mid = Math.floor((low + high) / 2);\n mergeSort(array, low, mid);\n mergeSort(array, mid + 1, high);\n merge(array, low, mid, high);\n}\n\nfunction merge(array, low, mid, high) {\n const n1 = mid - low + 1;\n const n2 = high - mid;\n const leftPart = array.slice(low, mid + 1);\n const rightPart = array.slice(mid + 1, high + 1);\n \n let p1 = 0, p2 = 0, writeInd = low;\n \n while (p1 < n1 && p2 < n2) {\n if (leftPart[p1] <= rightPart[p2]) {\n array[writeInd++] = leftPart[p1++];\n } else {\n array[writeInd++] = rightPart[p2++];\n }\n }\n \n while (p1 < n1) {\n array[writeInd++] = leftPart[p1++];\n }\n \n while (p2 < n2) {\n array[writeInd++] = rightPart[p2++];\n }\n}\n```\n``` Java []\nclass Solution {\n public int[] sortArray(int[] nums) {\n mergeSort(nums, 0, nums.length - 1);\n return nums;\n }\n\n private void mergeSort(int[] array, int low, int high) {\n if (low >= high) {\n return;\n }\n int mid = low + (high - low) / 2;\n mergeSort(array, low, mid);\n mergeSort(array, mid + 1, high);\n merge(array, low, mid, high);\n }\n\n private void merge(int[] array, int low, int mid, int high) {\n int n1 = mid - low + 1;\n int n2 = high - mid;\n int[] leftPart = new int[n1];\n int[] rightPart = new int[n2];\n\n System.arraycopy(array, low, leftPart, 0, n1);\n System.arraycopy(array, mid + 1, rightPart, 0, n2);\n\n int p1 = 0, p2 = 0, writeInd = low;\n while (p1 < n1 && p2 < n2) {\n if (leftPart[p1] <= rightPart[p2]) {\n array[writeInd++] = leftPart[p1++];\n } else {\n array[writeInd++] = rightPart[p2++];\n }\n }\n\n while (p1 < n1) {\n array[writeInd++] = leftPart[p1++];\n }\n\n while (p2 < n2) {\n array[writeInd++] = rightPart[p2++];\n }\n }\n}\n```\n``` C []\nvoid merge(int* array, int low, int mid, int high) {\n int n1 = mid - low + 1;\n int n2 = high - mid;\n int* left_part = (int*)malloc(n1 * sizeof(int));\n int* right_part = (int*)malloc(n2 * sizeof(int));\n\n for (int i = 0; i < n1; ++i)\n left_part[i] = array[low + i];\n for (int i = 0; i < n2; ++i)\n right_part[i] = array[mid + 1 + i];\n\n int p1 = 0, p2 = 0, write_ind = low;\n while (p1 < n1 && p2 < n2) {\n if (left_part[p1] <= right_part[p2]) {\n array[write_ind++] = left_part[p1++];\n } else {\n array[write_ind++] = right_part[p2++];\n }\n }\n\n while (p1 < n1)\n array[write_ind++] = left_part[p1++];\n\n while (p2 < n2)\n array[write_ind++] = right_part[p2++];\n\n free(left_part);\n free(right_part);\n}\n\nvoid merge_sort(int* array, int low, int high) {\n if (low >= high)\n return;\n\n int mid = low + (high - low) / 2;\n merge_sort(array, low, mid);\n merge_sort(array, mid + 1, high);\n merge(array, low, mid, high);\n}\n\nint* sortArray(int* nums, int numsSize, int* returnSize) {\n *returnSize = numsSize;\n merge_sort(nums, 0, numsSize - 1);\n return nums;\n}\n```\n\n\n# 3\uFE0F\u20E3\uD83C\uDF1F Approach 3: Counting Sort\n\n# \uD83E\uDD14 Intuition\n- I don\'t know how on Earth author decided to cut the quick sort with 17 test case and allow counting sort to work here and not throw memory limit exceeded\n- I saw many questions about how sorting in O(n) could exist and why this is works - okay guys, this is works, but works very limited. The problem is, counting sort is supposed to store counting for EVERY possible value in the array, it means that if you can have very large integers like -10^9 and 10^9 you MUST allocate memory for 2 * 10^9 + 1 numbers which is very much memory and now assume you need tens times more for larger numbers - but, because constaints says `-5 * 10^4 <= nums[i] <= 5 * 10^4` we need only `2 * 5 * 10^4 + 1` cells for storing values which is not that big.\nHow this works? You just count elements and store their counting, then you go through your counting list from smallest to biggest elements and add to your array as many elements of this as needed - this is it, no hard partition or sort, just counting.\n\n\nToday I\'m showing a lot of animations, so let\'s look at one more (source: [Github explanations](https://github.com/Lugriz/typescript-algorithms/blob/master/src/algorithms/sorting/counting-sort/README.md))\n\n<img src="https://camo.githubusercontent.com/5422ea175c8af5e1538e1e9ec2b714fa9acc27b211c4978d463a60fd399f2f14/68747470733a2f2f332e62702e626c6f6773706f742e636f6d2f2d6a4a63686c7931426b54632f574c4771434644647643492f41414141414141414148412f6c756c6a416c7a3270744d6e64495a4e48304b4c545475514d4e73667a44654651434c63422f73313630302f43536f72745570646174656453746570492e676966" width="80%">\n<img src="https://camo.githubusercontent.com/02ac6776f263dcfe117a77edaf82175e305fb4774e3dc870731021dedd4ec2e2/68747470733a2f2f312e62702e626c6f6773706f742e636f6d2f2d317646752d5649526139592f574c4847755a6b644633492f41414141414141414148732f386a4b7532646251656534617039786c56634e73494c72636c7177305578415641434c63422f73313630302f537465702d49492e706e67" width="80%">\n<img src="https://camo.githubusercontent.com/9654388769617ec8682b8e19aacc9729b223b5028727a0a288374fdd4fa91e2f/68747470733a2f2f312e62702e626c6f6773706f742e636f6d2f2d785071796c6e67714153592f574c47713370396e3976492f414141414141414141484d2f4a48647458416b4a593877597a444d4258787161726a6d687050684d3075384d41434c63422f73313630302f526573756c74417272617943532e676966" width="80%">\n\n\n\n# \uD83D\uDC69\uD83C\uDFFB\u200D\uD83D\uDCBB Coding \n- Initialize a `counting` array with size `2 * 5 * 10^4 + 1` (to accommodate both positive and negative numbers) and fill it with zeros.\n- Iterate through each element `num` in the input `nums` array:\n- Increment the corresponding index in the `counting` array by adding `5 * 10^4` to `num` to handle negative values.\n- Initialize `write_ind` to 0 to track the position in the original `nums` array for writing sorted values.\n- Iterate through the `counting` array with index `number_ind` and frequency `freq`:\n- While `freq` is not zero, write the value `(number_ind - 5 * 10^4)` back to the `nums` array, update `write_ind`, and decrement `freq`.\n- Return the sorted `nums` array.\n\n# \uD83D\uDCD8 Complexity Analysis\n- \u23F0 Time complexity: O(n), we go through each element in `nums` once and then go through frequency array (exactly 2 * 5 * 10^4 + 1 operations) \n- \uD83E\uDDFA Space complexity: O(1), we always use constant space (BUT BE CAREFUL! This just means our memory doesn\'t depend on input size but this doesn\'t mean that merge sort will use more memory than this, in fact, quite possible otherwise)\n\n# \uD83D\uDCBB Code\n``` python []\nclass Solution:\n def sortArray(self, nums: list[int]) -> list[int]:\n counting: list[int] = [0 for _ in range(2 * 5 * 10**4 + 1)]\n for num in nums:\n # we add 5 * 10^4 because for smallest possible element -5 * 10^4 index must be 0\n counting[num + 5 * 10**4] += 1\n write_ind: int = 0\n for number_ind, freq in enumerate(counting):\n while freq != 0:\n nums[write_ind] = number_ind - 5 * 10**4\n write_ind += 1\n freq -= 1\n\n return nums\n```\n``` C++ []\nclass Solution {\npublic:\n vector<int> sortArray(vector<int>& nums) {\n vector<int> counting(2 * 50000 + 1, 0);\n for (int num : nums) {\n // we add 5 * 10^4 because for smallest possible element -5 * 10^4 index must be 0\n counting[num + 50000]++;\n }\n int write_ind = 0;\n for (int number_ind = 0; number_ind < counting.size(); ++number_ind) {\n int freq = counting[number_ind];\n while (freq != 0) {\n nums[write_ind] = number_ind - 50000;\n write_ind++;\n freq--;\n }\n }\n return nums;\n }\n};\n```\n``` JavaScript []\nvar sortArray = function(nums) {\n let counting = new Array(2 * 50000 + 1).fill(0);\n for (let num of nums) {\n // we add 5 * 10^4 because for smallest possible element -5 * 10^4 index must be 0\n counting[num + 50000]++;\n }\n let writeInd = 0;\n for (let numberInd = 0; numberInd < counting.length; numberInd++) {\n let freq = counting[numberInd];\n while (freq != 0) {\n nums[writeInd] = numberInd - 50000;\n writeInd++;\n freq--;\n }\n }\n return nums;\n};\n```\n``` Java []\nclass Solution {\n public int[] sortArray(int[] nums) {\n int[] counting = new int[2 * 50000 + 1];\n for (int num : nums) {\n // we add 5 * 10^4 because for smallest possible element -5 * 10^4 index must be 0\n counting[num + 50000]++;\n }\n int writeInd = 0;\n for (int numberInd = 0; numberInd < counting.length; numberInd++) {\n int freq = counting[numberInd];\n while (freq != 0) {\n nums[writeInd] = numberInd - 50000;\n writeInd++;\n freq--;\n }\n }\n return nums;\n }\n}\n```\n``` C []\nint* sortArray(int* nums, int numsSize, int* returnSize) {\n int max_size = 2 * 50000 + 1;\n int* counting = (int*)calloc(max_size, sizeof(int));\n int offset = 50000;\n for (int i = 0; i < numsSize; i++) {\n // we add 5 * 10^4 because for smallest possible element -5 * 10^4 index must be 0\n counting[nums[i] + offset]++;\n }\n int write_ind = 0;\n for (int number_ind = 0; number_ind < max_size; number_ind++) {\n int freq = counting[number_ind];\n while (freq != 0) {\n nums[write_ind] = number_ind - offset;\n write_ind++;\n freq--;\n }\n }\n free(counting);\n *returnSize = numsSize;\n return nums;\n}\n```\n\n## \uD83D\uDCA1\uD83D\uDCA1\uD83D\uDCA1I encourage you to check out [my profile](https://leetcode.com/heir-of-god/) and [Project-S](https://github.com/Heir-of-God/Project-S) project for detailed explanations and code for different problems (not only Leetcode). Happy coding and learning!\uD83D\uDCDA\n\n### Please consider *upvote*\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F because I try really hard not just to put here my code and rewrite testcase to show that it works but explain you WHY it works and HOW. Thank you\u2764\uFE0F\n\n## If you have any doubts or questions feel free to ask them in comments. I will be glad to help you with understanding\u2764\uFE0F\u2764\uFE0F\u2764\uFE0F\n\n\n | 163 | 37 | ['Array', 'Divide and Conquer', 'Sorting', 'Merge Sort', 'Counting Sort', 'Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 22 |
sort-an-array | ✅ Java | Merge Sort | Easy | java-merge-sort-easy-by-kalinga-x5v5 | Merge Sort Time Complexity -> Best :- O(N log N)\tAverage :- O(N log N)\tWorst :- O(N log N)\t\nSpace Complexity :- O(N)\nStable and not in-place\nExplanation : | kalinga | NORMAL | 2023-03-01T00:38:15.709826+00:00 | 2023-03-01T00:44:03.412722+00:00 | 20,640 | false | **Merge Sort Time Complexity -> Best :- O(N log N)\tAverage :- O(N log N)\tWorst :- O(N log N)\t\nSpace Complexity :- O(N)\nStable and not in-place\nExplanation :- [Link](https://youtu.be/ogjf7ORKfd8)**\n```\nclass Solution {\n public int[] sortArray(int[] nums) {\n mergeSort(nums,0,nums.length-1);\n return nums;\n }\n public static void mergeFun(int[] arr, int l, int m, int r) {\n int n1 = m + 1 - l;\n int n2 = r - m;\n int[] left = new int[n1];\n for (int i = 0; i < n1; i++) {\n left[i] = arr[l + i];\n }\n int[] right = new int[n2];\n for (int i = 0; i < n2; i++) {\n right[i] = arr[m + 1 + i];\n }\n int i = 0, j = 0, k = l;\n while (i < n1 || j < n2) {\n if (j == n2 || i < n1 && left[i] < right[j])\n arr[k++] = left[i++];\n else\n arr[k++] = right[j++];\n }\n }\n\n public static void mergeSort(int[] arr, int low, int high) {\n if (low < high) {\n int middle = (high - low) / 2 + low;\n mergeSort(arr, low, middle);\n mergeSort(arr, middle + 1, high);\n mergeFun(arr, low, middle, high);\n }\n }\n}\n```\n\n | 140 | 1 | ['Sorting', 'Merge Sort', 'Java'] | 10 |
sort-an-array | C++ merge, insertion, bubble, quick, heap | c-merge-insertion-bubble-quick-heap-by-s-hlra | Bubble sort\n\n\t// bubbleSort(nums);\n\tvoid bubbleSort(vector<int>& nums){\n for(int i = nums.size() - 1; i >= 0; i--)\n for(int j = 0; j < | sunhaozhe | NORMAL | 2019-12-11T09:58:29.066133+00:00 | 2020-08-17T14:21:11.342217+00:00 | 18,699 | false | Bubble sort\n```\n\t// bubbleSort(nums);\n\tvoid bubbleSort(vector<int>& nums){\n for(int i = nums.size() - 1; i >= 0; i--)\n for(int j = 0; j < i; j++)\n if(nums[j] > nums[j + 1]) \n swap(nums[j], nums[j + 1]);\n }\n```\n\n*********************************************************\n\nInsertion sort\n```\n\t// insertionSort(nums);\n\tvoid insertionSort(vector<int>& nums){\n if(nums.size() == 0 || nums.size() == 1) return;\n for(int i = 1; i < nums.size(); i++){\n int tmp = nums[i];\n int j = i - 1;\n while(j >= 0 && nums[j] > tmp){\n nums[j + 1] = nums[j];\n j--;\n }\n nums[j + 1] = tmp;\n }\n }\n```\n*********************************************************\n\nHeap sort\n\nIn terms of `heapify` stage:\n* Bottom up approach (beginning from bottom + sift down) `O(n)`\n* Top down approach (beginning from top + sift up) `O(nlogn)`\n* Beginning from top + sift down `not working` \n\nIn fact, "sift down" of a certain node `x` works properly only if both of its left subtree and right subtree (if any) already satisfy the heap property.\n\n\nFor zero-based arrays, for a certain node `x`:\n* its parent `floor( (x - 1) / 2 )`\n* its left child `2x + 1`\n* its right child `2x + 2`\n\nThe index of the last non-leaf node of a `n`-sized heap is `floor( n / 2 ) - 1`.\n```\n\tvoid siftDown(vector<int>& nums, int n, int i){\n int biggest = i;\n int l = 2 * i + 1;\n int r = 2 * i + 2;\n if(l < n && nums[biggest] < nums[l])\n biggest = l;\n if(r < n && nums[biggest] < nums[r])\n biggest = r;\n if(biggest != i){\n swap(nums[i], nums[biggest]);\n siftDown(nums, n, biggest);\n }\n }\n \n\t// heapSort(nums);\n void heapSort(vector<int>& nums){\n // heapify stage (bottom up approach)\n for(int i = nums.size() / 2 - 1; i >= 0; i--)\n siftDown(nums, nums.size(), i);\n // sorting stage\n for(int i = nums.size() - 1; i > 0; i--){\n swap(nums[0], nums[i]);\n siftDown(nums, i, 0);\n }\n }\n```\n\n*********************************************************\nMerge sort (recursive version)\n```\n\tvoid merge(vector<int>& nums, int l, int m, int r){\n vector<int> tmp(r - l + 1);\n int i = l; // index for left subarray\n int j = m + 1; // index for right subarray\n int k = 0; // index for temporary array\n while(i <= m && j <= r){\n if(nums[i] <= nums[j]) tmp[k++] = nums[i++]; \n else tmp[k++] = nums[j++];\n }\n while(i <= m) tmp[k++] = nums[i++];\n while(j <= r) tmp[k++] = nums[j++]; \n for(i = 0; i < k; i++) nums[l + i] = tmp[i];\n }\n\t\n\t// mergeSort(nums, 0, nums.size() - 1);\n void mergeSort(vector<int>& nums, int l, int r){\n if(l >= r) return;\n int m = l + (r - l) / 2; //middle index, same as (l+r)/2\n mergeSort(nums, l, m);\n mergeSort(nums, m + 1, r);\n merge(nums, l, m, r);\n }\n```\n\n*********************************************************\nQuick sort (recursive version)\n```\n\t// quickSort(nums, 0, nums.size() - 1);\n void quickSort(vector<int>& nums, int l, int r){\n if(l >= r) return;\n int i = l; // cursor for final pivot location \n for(int j = l; j <= r - 1; j++){ // nums[r] is chosen as the pivot\n if(nums[j] <= nums[r]){\n swap(nums[i], nums[j]);\n i++; // smaller or equal elements go to the left of i \n }\n }\n swap(nums[i], nums[r]); // after swap, the pivot is nums[i]\n quickSort(nums, l, i - 1);\n quickSort(nums, i + 1, r);\n }\n```\n\n\n*********************************************************\nThe utility function `swap` is defined as follows\n```\n\tvoid swap(int& a, int& b){\n int tmp = a;\n a = b;\n b = tmp;\n }\n``` | 109 | 4 | ['C', 'Sorting', 'Heap (Priority Queue)', 'Merge Sort', 'C++'] | 15 |
sort-an-array | 🚀Simplest Solution🚀3 Approaches||🔥Heap Sort | Merge Sort || Priority Queue ||🔥C++ | simplest-solution3-approachesheap-sort-m-jydb | Consider\uD83D\uDC4D\n\n Please Upvote If You Find It Helpful\n\n # Intuition \n Describe your first thoughts on how to solve this problem. \ | naman_ag | NORMAL | 2023-03-01T01:45:01.743843+00:00 | 2023-03-01T09:53:42.947536+00:00 | 15,434 | false | # Consider\uD83D\uDC4D\n```\n Please Upvote If You Find It Helpful\n```\n<!-- # 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**Heap Sort**\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n```\nclass Solution {\npublic:\n void maxHeapify(vector<int>& nums, int n, int i){\n int largest = i;\n int left = (2 * i) + 1, right = (2 * i) + 2;\n if(left < n && nums[left] > nums[largest])\n largest = left;\n if(right < n && nums[right] > nums[largest])\n largest = right;\n if(largest != i){\n swap(nums[largest], nums[i]);\n maxHeapify(nums, n, largest);\n }\n }\n\n void heapSort(vector<int>& nums, int n){\n for(int i = n/2-1; i >= 0; i--)\n maxHeapify(nums, n, i);\n for(int i = n-1; i >= 0; i--){\n swap(nums[0], nums[i]);\n maxHeapify(nums, i, 0);\n }\n }\n\n vector<int> sortArray(vector<int>& nums) {\n heapSort(nums, nums.size());\n return nums;\n }\n};\n```\n\n**Merge Sort**\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```\nclass Solution {\npublic:\n void merge(int low, int mid, int high, vector<int> &nums) {\n if (low >= high) return;\n int l = low, r = mid + 1, k = 0, size = high - low + 1;\n vector<int> sorted(size, 0);\n while (l <= mid and r <= high)\n sorted[k++] = nums[l] < nums[r] ? nums[l++] : nums[r++];\n while (l <= mid) \n sorted[k++] = nums[l++];\n while (r <= high) \n sorted[k++] = nums[r++];\n for (k = 0; k < size; k++)\n nums[k + low] = sorted[k];\n }\n\n void mergeSort(vector<int>& nums, int start, int end){\n if(start < end){\n int mid = start + (end - start) / 2;\n mergeSort(nums, start, mid);\n mergeSort(nums, mid + 1, end);\n merge(start, mid, end, nums);\n }\n }\n\n vector<int> sortArray(vector<int>& nums) {\n mergeSort(nums, 0, nums.size()-1);\n return nums;\n }\n};\n```\n**Priority Queue**\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```\nclass Solution {\npublic:\n vector<int> sortArray(vector<int>& nums) {\n priority_queue<int, vector<int>, greater<int>> pq;\n for(int i : nums)\n pq.push(i);\n for(int i=0;i<nums.size();i++){\n nums[i] = pq.top();\n pq.pop();\n }\n return nums;\n }\n};\n```\n```\n `Give a \uD83D\uDC4D. It motivates me alot`\n```\nLet\'s Connect On [Linkedin](https://www.linkedin.com/in/naman-agarwal-0551aa1aa/) | 104 | 1 | ['Divide and Conquer', 'C', 'Heap (Priority Queue)', 'Merge Sort', 'C++'] | 9 |
sort-an-array | Explanation which makes the concept clear to interpret... Beats 98.75% | explanation-which-makes-the-concept-clea-e5r7 | no misunderstandings please legal upvotes from my peers..\n\n# Approach\nThe main function sortArray contains a nested function quick_sort, which is a common pa | Aim_High_212 | NORMAL | 2024-07-25T00:13:31.195569+00:00 | 2024-07-25T09:41:20.162511+00:00 | 15,778 | false | ## no misunderstandings please legal upvotes from my peers..\n\n# Approach\nThe main function sortArray contains a nested function quick_sort, which is a common pattern to encapsulate the recursive logic within the sorting function and allows us to use variables from the outer scope.\n\nquick_sort takes two arguments, l and r, which are the indices of the left and right boundaries of the sub-array that it needs to sort.\n\nThe termination condition for the recursion is when the left boundary l is greater than or equal to the right boundary r. At this point, the sub-array has zero or one element and is considered sorted.\n\nA pivot element x is chosen using randint(l, r) to randomly select an index between l and r, inclusive. The random pivot mitigates the risk of encountering the worst-case time complexity.\n\nThree pointers are established: i is initially set to one less than the left boundary l, j is one more than the right boundary r, and k is set to the left boundary l.\n\nAn iterative process starts where the k pointer moves from l to j. During this process:\n\nIf the current element nums[k] is less than the pivot x, it is swapped with the element at i+1, and both i and k are incremented. This effectively moves the current element to the left partition (elements less than the pivot).\nIf nums[k] is greater than the pivot x, the current element is swapped with the element just before j, and j is decreased. This moves the current element to the right partition (elements greater than the pivot).\nIf nums[k] is equal to the pivot x, only k is incremented since the element at k is already equal to the pivot, and we want to keep this partition in the middle.\nThe array now has three partitions: elements less than the pivot (l to i), elements equal to the pivot (i+1 to j-1), and elements greater than the pivot (j to r). The elements equal to the pivot are already at their final destination.\n\nRecursive calls are made to quick_sort for the left partition (l to i) and the right partition (j to r). Note that the elements equal to the pivot are not included.\n\nOnce all recursive calls are completed, the entire array has been sorted in place, and the sorted array nums is returned.\n\nData Structures Used:\n\nThe primary data structure is the input array nums. No additional data structure is utilized, which contributes to the algorithm\'s small space complexity.\n\n# Code\n\n```python3 []\nfrom random import randint\nfrom typing import List\n\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n # Helper function to perform quick sort.\n def quick_sort(left, right):\n # Base case: If the current segment is empty or has only one element, no need to sort.\n if left >= right:\n return\n \n # Choose a random pivot element from the segment.\n pivot = nums[randint(left, right)]\n # Initialize pointers: \n # \'less_than_pointer\' marks the end of the segment with elements less than pivot.\n # \'greater_than_pointer\' marks the start of the segment with elements greater than pivot.\n # \'current\' is used to scan through the list. \n less_than_pointer, greater_than_pointer, current = left - 1, right + 1, left\n \n # Iterate until \'current\' is less than \'greater_than_pointer\'.\n while current < greater_than_pointer:\n if nums[current] < pivot:\n # Move the element to the segment with elements less than pivot.\n less_than_pointer += 1\n nums[less_than_pointer], nums[current] = nums[current], nums[less_than_pointer]\n current += 1\n elif nums[current] > pivot:\n # Move the element to the segment with elements greater than pivot.\n greater_than_pointer -= 1\n nums[greater_than_pointer], nums[current] = nums[current], nums[greater_than_pointer]\n else:\n # If the current element is equal to the pivot, move to the next element.\n current += 1\n\n # Recursively apply quick sort to the segment with elements less than pivot.\n quick_sort(left, less_than_pointer)\n # Recursively apply quick sort to the segment with elements greater than pivot.\n quick_sort(greater_than_pointer, right)\n\n # Call the quick_sort function with the initial boundaries of the list.\n quick_sort(0, len(nums) - 1)\n # Return the sorted list.\n return nums\n```\n```javascript []\n// This function sorts an array of numbers using Quick Sort algorithm.\nfunction sortArray(nums: number[]): number[] {\n // Helper function to perform the quickSort algorithm.\n function quickSort(left: number, right: number) {\n // If the current segment is empty or has one element, no sorting is needed.\n if (left >= right) {\n return;\n }\n\n let i = left - 1;\n let j = right + 1;\n\n // Choose the pivot element from the middle of the segment.\n const pivot = nums[(left + right) >> 1];\n\n // Partition process: elements < pivot go to the left, elements > pivot go to the right.\n while (i < j) {\n // Find left element greater than or equal to the pivot.\n while (nums[++i] < pivot);\n // Find right element less than or equal to the pivot.\n while (nums[--j] > pivot);\n\n // If pointers have not crossed, swap the elements.\n if (i < j) {\n [nums[i], nums[j]] = [nums[j], nums[i]];\n }\n }\n\n // Recursively apply the same logic to the left partition.\n quickSort(left, j);\n // Recursively apply the same logic to the right partition.\n quickSort(j + 1, right);\n }\n\n // Obtain the length of the array to sort.\n const n = nums.length;\n // Call the quickSort helper function on the entire array.\n quickSort(0, n - 1);\n\n // Return the sorted array.\n return nums;\n}\n\n```\n\n```C++ []\n#include <vector>\n#include <functional> // For std::function\n\nclass Solution {\npublic:\n vector<int> sortArray(vector<int>& nums) {\n // A lambda function for recursive quick sort\n std::function<void(int, int)> quickSort = [&](int left, int right) {\n // Base case: If the current segment is empty or a single element, no need to sort\n if (left >= right) {\n return;\n }\n\n // Initialize pointers for partitioning process\n int pivotIndex = left + (right - left) / 2; // Choose middle element as pivot\n int pivotValue = nums[pivotIndex];\n int i = left - 1;\n int j = right + 1;\n \n // Partition the array into two halves\n while (i < j) {\n // Increment i until nums[i] is greater or equal to pivot\n do {\n i++;\n } while (nums[i] < pivotValue);\n\n // Decrement j until nums[j] is less or equal to pivot\n do {\n j--;\n } while (nums[j] > pivotValue);\n\n // If i and j haven\'t crossed each other, swap the elements\n if (i < j) {\n std::swap(nums[i], nums[j]);\n }\n }\n\n // Recursively apply the same logic to the left and right halves of the array\n quickSort(left, j); // Apply quicksort to the left subarray\n quickSort(j + 1, right); // Apply quicksort to the right subarray\n };\n\n // Start the quick sort from the first to the last element\n quickSort(0, nums.size() - 1);\n\n // Return the sorted array\n return nums;\n }\n};\n\n```\n\n | 94 | 11 | ['Python', 'C++', 'Python3', 'JavaScript'] | 15 |
sort-an-array | Merge Sort | merge-sort-by-eddiecarrillo-vqq8 | \nclass Solution {\n public int[] sortArray(int[] nums) {\n int N = nums.length;\n mergeSort(nums, 0, N-1);\n return nums;\n }\n \ | eddiecarrillo | NORMAL | 2019-07-08T00:03:06.606069+00:00 | 2019-07-08T00:03:06.606118+00:00 | 39,988 | false | ```\nclass Solution {\n public int[] sortArray(int[] nums) {\n int N = nums.length;\n mergeSort(nums, 0, N-1);\n return nums;\n }\n \n \n void mergeSort(int[] nums, int start, int end){\n if (end - start+1 <= 1) return; //Already sorted.\n int mi = start + (end - start)/ 2;\n mergeSort(nums, start, mi);\n mergeSort(nums, mi+1, end);\n merge(nums, start,mi, end);\n }\n \n void merge(int[] nums, int start, int mi, int end){\n int lp = start;\n int rp = mi + 1;\n int[] buffer = new int[end-start+1];\n int t = 0; //buffer pointer\n \n while (lp <= mi && rp <= end){\n if (nums[lp] < nums[rp]){\n buffer[t++] = nums[lp++];\n }else{\n buffer[t++] = nums[rp++];\n }\n }\n \n while (lp <= mi) buffer[t++] = nums[lp++];\n while (rp <= end) buffer[t++] = nums[rp++];\n //Now copy sorted buffer into original array\n for (int i = start; i <= end; i++){\n nums[i] = buffer[i-start];\n }\n }\n \n \n}\n``` | 61 | 3 | [] | 7 |
sort-an-array | Merge Sort|Radix sort|counting sort|heap sort||47ms Beats 99.41% | merge-sortradix-sortcounting-sortheap-so-9odo | Intuition\n Describe your first thoughts on how to solve this problem. \n1. Try merge sort which is stable & O(n log n) time\n2. Radix sort is a stable sort wit | anwendeng | NORMAL | 2024-07-25T00:06:33.345214+00:00 | 2024-07-25T04:40:26.112508+00:00 | 12,490 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Try merge sort which is stable & O(n log n) time\n2. Radix sort is a stable sort with 64 buckets with 3 passes & O(3n) time\n3. Counting sort is very suitible for this question which can be done very quickly.\n4. Heap sort is unstable, but at worst O(n log n)\n# Approach\n<!-- Describe your approach to solving the problem. -->\nJust pratice for different implementations.\nWhy not quick sort? quick sort has at worst O(n^2); the choice of the pivot & the partition must be very careful. The textbook version for the quick sort might not pass the LC\'s testcases.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nMerge sort: O(n log n)\nRadix sort: O(3n)\nCounting sort: O(n+m) where m=max(x)-min(x)+1\nHeap sort: O(n log n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nMerge sort:O(n)\nRadix sort: O(|buckets|+n)\nCounting sort: O(m) where m=max(x)-min(x)+1\nHeap sort: O(log n) (for the recursion stack); O(1) (iterative version for heapify)\n# Code Merge Sort\n```\nclass Solution {\npublic:\n void merge(vector<int>& A, int start, int mid, int end, vector<int>& buff)\n {\n int left=start, right=mid+1;\n int s=end-start+1;\n for(int i=0; i<s; i++)\n { \n int i0=start+i;\n if(left>mid){\n buff[i0]=A[right];\n right++;\n } else if (right>end){\n buff[i0]=A[left];\n left++;\n } else if (A[left]<A[right]){\n buff[i0]=A[left];\n left++;\n } else{\n buff[i0]=A[right];\n right++;\n }\n }\n for(int i=start; i<start+s; i++) A[i]=buff[i];\n }\n void mergeSort(vector<int>& A, int start, int end, vector<int>& buff )\n {\n if(end<=start) return;\n int mid=start+(end-start)/2;\n mergeSort(A, start, mid, buff);\n mergeSort(A, mid+1, end, buff);\n merge(A, start, mid, end, buff);\n }\n vector<int> sortArray(vector<int>& nums) {\n vector<int> buff(nums.size());\n mergeSort(nums, 0, nums.size()-1 ,buff);\n return nums;\n }\n};\n```\n# C++ Radix sort||47ms Beats 99.41%\n```\nclass Solution {\npublic:\n const int xmin=-5*1e4;\n vector<int> bucket[64];//64**3=262144>1e5+1\n void radix_sort(vector<int>& nums) {\n // 1st round\n for (int& x : nums){// adjust x-=xmin\n x-=xmin;\n bucket[x&63].push_back(x);\n }\n int i = 0;\n for (auto &B : bucket) {\n for (auto v : B)\n nums[i++] = v;\n B.clear();\n }\n // 2nd round\n for (int& x : nums)\n bucket[(x>>6)&63].push_back(x);\n i=0;\n for (auto &B : bucket) {\n for (auto v : B)\n nums[i++] = v;\n B.clear();\n }\n // 3rd round\n for (int& x : nums)\n bucket[x>>12].push_back(x);\n i=0;\n for (auto &B : bucket) {\n for (auto v : B)//adjust back\n nums[i++] = v+xmin;\n // B.clear();\n }\n }\n vector<int> sortArray(vector<int>& nums) {\n radix_sort(nums);\n return nums;\n }\n};\n\n\n\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}(); \n```\n# C++ using counting sort||49ms Beats 99.22%\n```\nclass Solution {\npublic:\n vector<int> sortArray(vector<int>& nums) {\n const int vmin=-5*1e4, N=1e5+1;\n int freq[N]={0}, xMax=-1, xmin=N;\n for(int x:nums) {\n x-=vmin;\n freq[x]++;\n xMax=max(x, xMax);\n xmin=min(x, xmin);\n }\n for(int i=0, x=xmin; x<=xMax; x++){\n int f=freq[x];\n fill(nums.begin()+i, nums.begin()+i+f, x+vmin);//adjust back\n i+=f;\n }\n return nums;\n }\n};\n\n\n\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}(); \n```\n# C++ using heap sort||84ms Beats 90.20%\n```\nclass Solution {\npublic:\n inline void heapify(vector<int>& nums, int l, int r){\n int parent=l, child=(parent<<1)+1;\n if (child>r) return;\n if (child+1 <= r && nums[child]<nums[child+1]) child++;\n if (nums[parent]>nums[child]) return;\n swap(nums[parent], nums[child]);\n heapify(nums, child, r);\n }\n inline void heap_sort(vector<int>& nums){\n const int n=nums.size();\n for(int i=n/2-1; i>=0; i--)\n heapify(nums, i, n-1);\n for(int i=n-1; i>0; i--){\n swap(nums[0], nums[i]);\n heapify(nums, 0, i-1);\n }\n }\n vector<int> sortArray(vector<int>& nums) {\n heap_sort(nums);\n return nums;\n }\n};\n\n\n\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}(); \n```\n# iterative version for heapify \n```\n inline void heapify(vector<int>& nums, int l, int r){\n int parent=l, child=(parent<<1)+1;\n while (child<=r){\n if (child+1 <= r && nums[child]<nums[child+1]) child++;\n if (nums[parent]>nums[child]) return;\n else{\n swap(nums[parent], nums[child]);\n parent=child;\n child=(parent<<1)+1;\n }\n }\n }\n``` | 54 | 3 | ['Array', 'Divide and Conquer', 'Sorting', 'Heap (Priority Queue)', 'Merge Sort', 'Radix Sort', 'Counting Sort', 'C++'] | 13 |
sort-an-array | 912. Sort an Array (Sorting Algorithms) | 912-sort-an-array-sorting-algorithms-by-csv9y | Few Sorting Algorithms:\n1. Selection Sort \n1. Bubble Sort\n1. Insertion Sort\n1. QuickSort\n1. Merge Sort\n\nSelection Sort - O(n^2)\n\n\nvar selectionSort = | kondaldurgam | NORMAL | 2020-09-16T07:49:21.124837+00:00 | 2020-09-20T01:26:32.587857+00:00 | 9,507 | false | **Few Sorting Algorithms**:\n1. Selection Sort \n1. Bubble Sort\n1. Insertion Sort\n1. QuickSort\n1. Merge Sort\n\n**Selection Sort - O(n^2)**\n\n```\nvar selectionSort = function(nums) {\n var n = nums.length;\n for (var i = 0; i <n-1; i++) {\n var min = i;\n for (var j = i+1; j < n; j++ ) {\n if (nums[j] < nums[min]) {\n min = j; \n }\n }\n var temp = nums[i];\n nums[i] = nums[min];\n nums[min] = temp;\n }\n return nums;\n}\n```\n**Bubble Sort** - **Best Case : O (n)**, **Average Case : O (n^2)**,**Worst Case : O (n^ 2)**\n```\nvar bubbleSort = function(nums) {\n for (var k = nums.length - 1; k >= 1; k--) {\n for (var i = 0; i < k; i++) {\n if (nums[i] > nums[i + 1]) {\n swap(i, i + 1);\n } \n }\n }\n function swap(i,j) {\n var temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n }\n return nums;\n}\n```\n**Insertion Sort**-**Best Case : O (n)**, **Average Case : O (n^2)**,**Worst Case : O (n^ 2)**\n\n```\nvar insertionSort = function(nums) {\n for (var i = 1; i < nums.length; i++) {\n var value = nums[i];\n var hole = i;\n while(hole > 0 && nums[hole-1] > value) {\n nums[hole] = nums[hole-1];\n hole = hole-1\n }\n nums[hole] = value;\n }\n return nums;\n}\n```\n\n**Merge Sort** - **Best Case : O(n log n)**, **Average Case :O(n log n)**, **Worst Case : O(n log n)**\n\n```\nvar mergeSort = function(nums) {\n if (nums.length < 2) return nums;\n var mid = Math.floor(nums.length/2);\n var left = nums.slice(0,mid);\n var right = nums.slice(mid);\n \n function merge(left,right) {\n var result = [],lLen = left.length, rLen = right.length, l = 0, r = 0;\n while(l < lLen && r < rLen){\n if(left[l] < right[r]){\n result.push(left[l++]);\n }\n else{\n result.push(right[r++]);\n }\n } \n return result.concat(left.slice(l)).concat(right.slice(r));\n }\n\n return merge(mergeSort(left),mergeSort(right));\n}\n```\n\n**Quick Sort** - **Best Case : O(n log n)**, **Average Case :O(n log n)**, **Worst Case : O(n^2)**\n```\nvar quickSort = function(nums) {\n \n function quickSortHelper(nums, start, end) {\n if (start >= end) return nums\n \n var pivotValue = nums[start]\n var smaller = start\n for (var i = start + 1; i <= end; i++) {\n var bigger = i\n if (nums[bigger] < pivotValue) {\n smaller++\n var smallerValue = nums[bigger]\n nums[bigger] = nums[smaller]\n nums[smaller] = smallerValue\n }\n }\n var smallerCache = nums[smaller]\n nums[smaller] = nums[start]\n nums[start] = smallerCache\n \n quickSortHelper(nums, start, smaller - 1)\n quickSortHelper(nums, smaller + 1, end)\n return nums\n }\n \n return quickSortHelper(nums, 0, nums.length - 1)\n};\n```\n\nBut we use real time\n```\nvar sortArray = function(nums) {\n return nums.sort((a,b)=>a-b);\n};\n``` | 47 | 1 | ['JavaScript'] | 8 |
sort-an-array | Merge Sort for Interviews! Short and Pythonic. | merge-sort-for-interviews-short-and-pyth-kzus | \ndef sortArray(self, nums: List[int]) -> List[int]:\n def mergeTwoSortedArrays(a, b , res):\n i, j, k = 0, 0, 0\n while i<len(a) a | azaansherani | NORMAL | 2022-04-19T21:41:45.208435+00:00 | 2022-04-19T21:44:46.497630+00:00 | 4,734 | false | ```\ndef sortArray(self, nums: List[int]) -> List[int]:\n def mergeTwoSortedArrays(a, b , res):\n i, j, k = 0, 0, 0\n while i<len(a) and j<len(b):\n if a[i]<b[j]:\n res[k] = a[i]\n i+=1\n else:\n res[k] = b[j]\n j+=1\n k+=1\n \n res[k:] = a[i:] if i<len(a) else b[j:]\n \n def mergesort(nums):\n if len(nums) == 1: return\n mid = len(nums)//2\n L = nums[:mid]\n R = nums[mid:]\n \n mergesort(L)\n mergesort(R)\n \n mergeTwoSortedArrays(L, R, nums)\n \n mergesort(nums)\n return nums\n``` | 41 | 0 | ['Merge Sort', 'Python', 'Python3'] | 6 |
sort-an-array | ✅ Easy 3 step Sort Cpp / Java / Py / JS Solution | MergeSort _DivideNdConquer🏆| | easy-3-step-sort-cpp-java-py-js-solution-agr2 | You may be wondering why we don\'t use Bubble Sort, Insertion Sort, or Selection Sort for this problem?\nThe constraint specifies that the solution must achieve | dev_yash_ | NORMAL | 2024-07-25T02:49:46.441974+00:00 | 2024-08-09T00:28:16.867077+00:00 | 9,158 | false | #### You may be wondering why we don\'t use Bubble Sort, Insertion Sort, or Selection Sort for this problem?\nThe constraint specifies that the solution must achieve a time complexity of O(n log n).. or better. Algorithms like Bubble Sort, Insertion Sort, and Selection Sort have a time complexity of O(n^2), which is inefficient for large datasets. Therefore, using these algorithms would result in exceeding the time limits. Instead, algorithms like Quick Sort or Merge Sort, which have a time complexity of \uD835\uDC42 (\uD835\uDC5B log \uD835\uDC5B), are more suitable for meeting the constraints and ensuring efficient performance\n## Visualization\n\n Merge Sort Visualization -Consider nums = [5, 1, 1, 2, 0, 0]\n```\n// Initial input:\nnums = [5, 1, 1, 2, 0, 0]\n\n// Divide step:\n\n// First split:\nLeft half: [5, 1, 1]\nRight half: [2, 0, 0]\n\n// Second split (Left half):\nLeft half: [5]\nRight half: [1, 1]\n\n// Second split (Right half):\nLeft half: [2]\nRight half: [0, 0]\n\n// Third split (Left half of right half):\nLeft half: [1]\nRight half: [1]\n\n// Third split (Right half of right half):\nLeft half: [0]\nRight half: [0]\n\n// Conquer step:\n\n// First merge (Right half of right half):\nMerging: [0] and [0] => [0, 0]\n\n// First merge (Left half of right half):\nMerging: [1] and [1] => [1, 1]\n\n// Second merge (Right half):\nMerging: [2] and [0, 0] => [0, 0, 2]\n\n// Second merge (Left half):\nMerging: [5] and [1, 1] => [1, 1, 5]\n\n// Final merge:\nMerging: [1, 1, 5] and [0, 0, 2] => [0, 0, 1, 1, 2, 5]\n\n// Final output:\nnums = [0, 0, 1, 1, 2, 5]\n\n```\n### C++\n```\n//Easy to understand\nclass Solution\n{\npublic:\n vector<int> sortArray(vector<int> &nums)\n {\n mergeSort(nums, 0, nums.size() - 1);\n return nums;\n }\n\nprivate:\n void merge(vector<int> &nums, int low, int mid, int high)\n {\n vector<int> temp;\n int left = low;\n int right = mid + 1;\n // while\n while (left <= mid && right <= high)\n {\n if (nums[left] <= nums[right])\n {\n temp.push_back(nums[left]);\n left++;\n }\n else\n {\n temp.push_back(nums[right]);\n right++;\n }\n }\n // push remaining\n while (left <= mid)\n {\n temp.push_back(nums[left]);\n left++;\n }\n while (right <= high)\n {\n\n temp.push_back(nums[right]);\n right++;\n }\n // modify in place\n for (int i = low; i <= high; i++)\n {\n nums[i] = temp[i - low];\n }\n }\n\n void mergeSort(vector<int> &nums, int low, int high)\n {\n if (low == high)\n {\n return;\n }\n int mid = (low + high) / 2;\n mergeSort(nums, low, mid);\n mergeSort(nums, mid + 1, high);\n\n merge(nums, low, mid, high);\n }\n};\n\n```\n```\n//Optimized\nclass Solution {\npublic:\n vector<int> sortArray(vector<int>& nums) {\n mergeSort(nums, 0, nums.size() - 1);\n return nums;\n }\n\nprivate:\n void mergeSort(vector<int>& nums, int left, int right) {\n // Base case: if the subarray has one or zero elements, it is already sorted\n if (left >= right) return;\n \n // Divide: find the midpoint to split the array into two halves\n int mid = left + (right - left) / 2;\n \n // Conquer: recursively sort the left and right halves\n mergeSort(nums, left, mid);\n mergeSort(nums, mid + 1, right);\n \n // Combine: merge the sorted halves\n merge(nums, left, mid, right);\n }\n\n void merge(vector<int>& nums, int left, int mid, int right) {\n int n1 = mid - left + 1;\n int n2 = right - mid;\n \n // Create temporary arrays to hold the left and right halves\n vector<int> leftArray(n1);\n vector<int> rightArray(n2);\n \n // Copy data to temporary arrays\n for (int i = 0; i < n1; ++i)\n leftArray[i] = nums[left + i];\n for (int i = 0; i < n2; ++i)\n rightArray[i] = nums[mid + 1 + i];\n \n // Initial indices for left, right, and merged subarrays\n int i = 0, j = 0, k = left;\n \n // Merge the temporary arrays back into the original array\n while (i < n1 && j < n2) {\n if (leftArray[i] <= rightArray[j]) {\n nums[k++] = leftArray[i++];\n } else {\n nums[k++] = rightArray[j++];\n }\n }\n \n // Copy any remaining elements of leftArray\n while (i < n1) {\n nums[k++] = leftArray[i++];\n }\n \n // Copy any remaining elements of rightArray\n while (j < n2) {\n nums[k++] = rightArray[j++];\n }\n }\n};\n\n\n```\n### Java\n```\nclass Solution {\n public int[] sortArray(int[] nums) {\n mergeSort(nums, 0, nums.length - 1);\n return nums;\n }\n\n private void mergeSort(int[] nums, int left, int right) {\n if (left >= right) return;\n\n int mid = left + (right - left) / 2;\n\n mergeSort(nums, left, mid);\n mergeSort(nums, mid + 1, right);\n\n merge(nums, left, mid, right);\n }\n\n private void merge(int[] nums, int left, int mid, int right) {\n int n1 = mid - left + 1;\n int n2 = right - mid;\n\n int[] leftArray = new int[n1];\n int[] rightArray = new int[n2];\n\n for (int i = 0; i < n1; ++i)\n leftArray[i] = nums[left + i];\n for (int i = 0; i < n2; ++i)\n rightArray[i] = nums[mid + 1 + i];\n\n int i = 0, j = 0, k = left;\n\n while (i < n1 && j < n2) {\n if (leftArray[i] <= rightArray[j]) {\n nums[k++] = leftArray[i++];\n } else {\n nums[k++] = rightArray[j++];\n }\n }\n\n while (i < n1) {\n nums[k++] = leftArray[i++];\n }\n\n while (j < n2) {\n nums[k++] = rightArray[j++];\n }\n }\n}\n\n\n```\n\n### Python3\n```\n\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n self.mergeSort(nums, 0, len(nums) - 1)\n return nums\n\n def mergeSort(self, nums: List[int], left: int, right: int) -> None:\n if left >= right:\n return\n\n mid = (left + right) // 2\n\n self.mergeSort(nums, left, mid)\n self.mergeSort(nums, mid + 1, right)\n\n self.merge(nums, left, mid, right)\n\n def merge(self, nums: List[int], left: int, mid: int, right: int) -> None:\n n1 = mid - left + 1\n n2 = right - mid\n\n leftArray = nums[left:mid + 1]\n rightArray = nums[mid + 1:right + 1]\n\n i = j = 0\n k = left\n\n while i < n1 and j < n2:\n if leftArray[i] <= rightArray[j]:\n nums[k] = leftArray[i]\n i += 1\n else:\n nums[k] = rightArray[j]\n j += 1\n k += 1\n\n while i < n1:\n nums[k] = leftArray[i]\n i += 1\n k += 1\n\n while j < n2:\n nums[k] = rightArray[j]\n j += 1\n k += 1\n```\n### JavaScript\n```\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar sortArray = function(nums) {\n mergeSort(nums, 0, nums.length - 1);\n return nums;\n};\n\nfunction mergeSort(nums, left, right) {\n if (left >= right) return;\n\n const mid = Math.floor((left + right) / 2);\n\n mergeSort(nums, left, mid);\n mergeSort(nums, mid + 1, right);\n\n merge(nums, left, mid, right);\n}\n\nfunction merge(nums, left, mid, right) {\n const n1 = mid - left + 1;\n const n2 = right - mid;\n\n const leftArray = new Array(n1);\n const rightArray = new Array(n2);\n\n for (let i = 0; i < n1; ++i)\n leftArray[i] = nums[left + i];\n for (let i = 0; i < n2; ++i)\n rightArray[i] = nums[mid + 1 + i];\n\n let i = 0, j = 0, k = left;\n\n while (i < n1 && j < n2) {\n if (leftArray[i] <= rightArray[j]) {\n nums[k++] = leftArray[i++];\n } else {\n nums[k++] = rightArray[j++];\n }\n }\n\n while (i < n1) {\n nums[k++] = leftArray[i++];\n }\n\n while (j < n2) {\n nums[k++] = rightArray[j++];\n }\n}\n\n\n\n```\n#### STAY COOL STAY DISCIPLINED..\n\n | 36 | 0 | ['Array', 'Divide and Conquer', 'C', 'Sorting', 'Heap (Priority Queue)', 'Python', 'Java', 'Python3', 'JavaScript'] | 9 |
sort-an-array | Very Easy 100% Easiest Logic Ever (Fully Explained Step by Step)(C++, JavaScript, Java) | very-easy-100-easiest-logic-ever-fully-e-nx09 | Intuition\nIf you wanna to solve this problem then you have a good grip on Recusrion because you have to solve this problem in O(nlogn) which is only possible b | EmraanHash | NORMAL | 2023-03-01T05:56:15.295819+00:00 | 2023-03-01T06:58:38.653367+00:00 | 7,996 | false | # Intuition\nIf you wanna to solve this problem then you have a good grip on Recusrion because you have to solve this problem in O(nlogn) which is only possible by using Merge sort or Quick Sort. but here in my solution I am using Merge Sort Algorithm\n\n# Approach\nHere\'s how the algorithm works step by step:\n\n**Divide the array in half**. The first step in this code is to divide the input array into two halves. This is done by finding the middle index of the array and creating two new arrays: one containing the elements from the start of the array up to the middle index, and one containing the elements from the middle index to the end of the array.\n\n**Recursively sort each half.** Once we have divided the input array into two halves, we recursively sort each half using the same algorithm. We repeat this process until each half contains only one element, at which point we consider them to be sorted.\n\n**Merge the sorted halves.** After both halves are sorted, we merge them back together into a single, sorted array. We do this by comparing the first element of each half and adding the smaller element to a new array. We then move the index of the array from which we took the smaller element by one and repeat the process until we have added all elements from both halves to the new array.\n\nReturn the sorted array. Finally, we return the merged array.\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code by using Merge Sort Algorithm\n```\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar sortArray = function(nums) {\n if(nums.length < 2) return nums\n let mid = Math.floor(nums.length/2);\n let left = nums.slice(0, mid);\n let right = nums.slice(mid);\n return merge(sortArray(left), sortArray(right));\n};\n\nvar merge = function(left, right) {\n let sortedArray = [];\n while(left.length && right.length){\n if(left[0] <= right[0]){\n sortedArray.push(left.shift())\n }else {\n sortedArray.push(right.shift())\n }\n }\n\n return [...sortedArray, ...left, ...right]\n}\n```\n# Code by using Binary Sort Algorithm\n```\n// Time Complexity Big-O = O(n^2)\n\nvar sortArray = function (nums) {\n let sorted;\n do {\n sorted = false;\n for (let i = 0; i <= nums.length; i++) {\n if (nums[i] > nums[i + 1]) {\n let temp = nums[i + 1];\n nums[i + 1] = nums[i];\n nums[i] = temp;\n sorted = true;\n }\n }\n } while (sorted);\n return nums;\n};\n```\n\nI am working hard for you guys...\nPlease upvote if you found any help with this code... | 34 | 0 | ['C++', 'Java', 'JavaScript'] | 6 |
sort-an-array | Java QuickSort + SelectionSort + MergeSort summary | java-quicksort-selectionsort-mergesort-s-hpck | https://leetcode.com/submissions/detail/222979198/\n\nclass Solution {\n \n private static final int QUICKSORTSHOLD = 50;\n private static final int ME | scorego | NORMAL | 2019-04-17T03:19:02.044324+00:00 | 2019-04-17T03:19:02.044383+00:00 | 13,728 | false | https://leetcode.com/submissions/detail/222979198/\n```\nclass Solution {\n \n private static final int QUICKSORTSHOLD = 50;\n private static final int MERGESORTSHOLD = 300;\n \n public int[] sortArray(int[] nums) {\n if (nums == null || nums.length < 2){\n return nums;\n }\n \n if (nums.length < QUICKSORTSHOLD){\n selectionSort(nums); \n }else if (nums.length < MERGESORTSHOLD) {\n quickSort(nums);\n }else{\n mergeSort(nums);\n }\n return nums;\n }\n \n private void selectionSort(int[] nums){\n for (int i = 0; i < nums.length; i++){\n int minIndex = i;\n for (int j = i + 1; j < nums.length; j++){\n if (nums[j] < nums[minIndex]){\n minIndex = j;\n }\n }\n exch(nums, i, minIndex);\n }\n }\n \n private void quickSort(int[] nums){\n quickSort(nums, 0, nums.length - 1);\n }\n \n private void quickSort(int[] nums, int lo, int hi){\n if (lo >= hi)\n return ;\n int pivot = partition(nums, lo, hi);\n quickSort(nums, lo, pivot - 1);\n quickSort(nums, pivot + 1, hi);\n }\n \n private int partition(int[] nums, int lo, int hi){\n int q = lo + (int)(Math.random() * (hi - lo + 1));\n exch(nums, lo, q);\n \n int index = lo + 1;\n for (int i = lo + 1; i <= hi; i++){\n if (nums[i] < nums[lo]){\n exch(nums, i, index++);\n }\n }\n exch (nums, lo, --index);\n return index;\n }\n \n private void mergeSort(int[] nums){\n mergeSort(nums, 0, nums.length - 1);\n }\n \n private void mergeSort(int[] nums, int lo, int hi){\n if (lo >= hi)\n return ;\n int mid = (lo + hi) >>> 1;\n mergeSort(nums, lo, mid);\n mergeSort(nums, mid + 1, hi);\n merge(nums, lo, mid, mid + 1, hi);\n }\n \n private void merge(int[] nums, int preLo, int preHi, int endLo, int endHi){\n if (preLo == endHi)\n return;\n int lo = preLo;\n int hi = endHi;\n \n int[] newArr = new int[preHi - preLo + 1 + endHi - endLo + 1];\n int index = 0;\n while (preLo <= preHi && endLo <= endHi){\n newArr[index++] = (nums[preLo] < nums[endLo]) ? nums[preLo++] : nums[endLo++];\n }\n while (preLo <= preHi){\n newArr[index++] = nums[preLo++];\n }\n while (endLo <= endHi){\n newArr[index++] = nums[endLo++];\n }\n \n index = 0;\n while (lo <= hi){\n nums[lo++] = newArr[index++];\n }\n }\n \n private void exch(int[] nums, int i, int j){\n if (i == j)\n return;\n nums[i] ^= nums[j];\n nums[j] ^= nums[i];\n nums[i] ^= nums[j];\n }\n \n}\n``` | 30 | 2 | [] | 10 |
sort-an-array | Java | Easy to Understand | 5 lines | java-easy-to-understand-5-lines-by-akash-t4d0 | # Intuition \n\n\n# Approach : PriorityQueue\n- Step 1 : Take one ans array to store the sorted array and PriorityQueue pq. Default PriorityQueue is Min Heap | Akash_Markad_001 | NORMAL | 2023-03-01T04:13:00.566107+00:00 | 2023-03-01T04:13:00.566153+00:00 | 5,099 | false | <!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach : PriorityQueue\n- **Step 1** : Take one ```ans``` array to store the sorted array and PriorityQueue ```pq```. Default PriorityQueue is Min Heap , It store all elements in ascending order.\n- **Step 2** : Add all elements in PriorityQueue.\n- **Step 3** : Now add elements of ```pq``` to the ```ans``` array.\n- **Step 4** : Return ```ans``` array.\n \n<!-- Describe your approach to solving the problem. -->\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```\nclass Solution {\n public int[] sortArray(int[] nums) {\n\n int i=0;\n int[] ans = new int[nums.length];\n PriorityQueue<Integer> pq = new PriorityQueue<>();\n for(int num : nums) pq.offer(num);\n while(!pq.isEmpty()) ans[i++] = pq.poll();\n return ans;\n }\n}\n```\n```\nIf you like Please UpVote solution\n``` | 28 | 0 | ['Array', 'Sorting', 'Heap (Priority Queue)', 'Java'] | 4 |
sort-an-array | Optimized Counting Sort | 3-ms Beats 100 % | Java | Python | C++ | JavaScript | Go | optimized-counting-sort-3-ms-beats-100-j-bqvr | \n# Problem Explanation:\n\nThis problem is asking us to create a function that sorts an array of numbers from smallest to largest (ascending order). However, t | kartikdevsharma_ | NORMAL | 2024-07-25T04:23:30.129063+00:00 | 2024-07-25T06:42:24.654835+00:00 | 3,684 | false | \n# Problem Explanation:\n\n***This problem is asking us to create a function that sorts an array of numbers from smallest to largest (ascending order). However, there are some specific requirements we need to follow:***\n\n \n We can\'t use any built-in sorting functions.\n Our solution needs to be efficient, with a time complexity of O(nlog(n)).\n We should use as little extra space as possible.\n\n---\n\n\n\n\n\n\n# Intuition\n\nWhen we have a limited range of integers to sort, we can use their values directly to determine their position in the sorted array. This is the core idea behind Counting Sort. Instead of comparing elements, we count how many times each number appears and use this information to place the numbers in the correct order.\n\n\n# Approach\n\nThe Counting Sort algorithm we\'ve implemented follows a straightforward yet efficient method to sort an array of integers within a specific range. We begin by scanning through the entire input array to identify the minimum and maximum values. This step is crucial as it allows us to determine the range of numbers we\'re dealing with, which in turn helps us optimize our space usage.\n\nOnce we have this range, we create a counting array. The size of this array is equal to the difference between the maximum and minimum values, plus one. Each index in this counting array corresponds to a number in our input range, offset by the minimum value. We then proceed to count the occurrences of each number in the original array. This is done by iterating through the input array once more, and for each number, we increment the count at the corresponding index in our counting array.\n\nAfter the counting phase, we have a complete tally of how many times each number appears in our input. The final step is to reconstruct the sorted array. We do this by iterating through our counting array. For each index, we know that the number it represents (index plus minimum value) should appear in our sorted array as many times as the count stored at that index. We use this information to place each number in its correct position in the original array, effectively sorting it in-place.\n\nThis approach is particularly efficient for arrays with a limited range of integers, as it avoids comparisons between elements and instead uses the integer values directly to determine their positions. The algorithm\'s efficiency comes from the fact that it makes only a few passes through the data, regardless of how unsorted it initially was.\n\n# Complexity\n- **Time complexity: O(n + k)**\n Where n is the number of elements in the input array, and k is the range of input (max - min + 1).\n We go through the array twice (once to count, once to place elements) and once through the counting array.\n\n- **Space complexity: O(k)**\n We use extra space for the counting array, which has a size equal to the range of input values.\n\n### Code\n\n\n```java []\nclass Solution {\n public int[] sortArray(int[] nums) {\n if (nums == null || nums.length <= 1) return nums;\n \n int max = nums[0], min = nums[0];\n for (int num : nums) {\n if (num > max) max = num;\n if (num < min) min = num;\n }\n \n int range = max - min + 1;\n int[] count = new int[range];\n \n for (int num : nums) {\n count[num - min]++;\n }\n \n int index = 0;\n for (int i = 0; i < range; i++) {\n int freq = count[i];\n if (freq > 0) {\n int value = i + min;\n while (freq-- > 0) {\n nums[index++] = value;\n }\n }\n }\n \n return nums;\n }\n}\n```\n\n```cpp []\nclass Solution {\npublic:\n vector<int> sortArray(vector<int>& nums) {\n if (nums.empty()) return nums;\n \n int min = *min_element(nums.begin(), nums.end());\n int max = *max_element(nums.begin(), nums.end());\n \n vector<int> count(max - min + 1, 0);\n for (int num : nums) {\n count[num - min]++;\n }\n \n int index = 0;\n for (int i = 0; i < count.size(); i++) {\n while (count[i]-- > 0) {\n nums[index++] = i + min;\n }\n }\n \n return nums;\n }\n};\n\n```\n\n```python []\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n if not nums:\n return nums\n \n min_val, max_val = min(nums), max(nums)\n count = [0] * (max_val - min_val + 1)\n \n for num in nums:\n count[num - min_val] += 1\n \n index = 0\n for i in range(len(count)):\n while count[i] > 0:\n nums[index] = i + min_val\n index += 1\n count[i] -= 1\n \n return nums\n\n```\n```python []\nf = open(\'user.out\', \'w\')\nfor nums in map(loads, stdin):\n print(str(sorted(nums)).replace(\' \',\'\'), file=f)\nexit(0)\n```\n\n```javascript []\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar sortArray = function(nums) {\n if (nums.length <= 1) return nums;\n \n let min = Math.min(...nums);\n let max = Math.max(...nums);\n \n let count = new Array(max - min + 1).fill(0);\n for (let num of nums) {\n count[num - min]++;\n }\n \n let index = 0;\n for (let i = 0; i < count.length; i++) {\n while (count[i]-- > 0) {\n nums[index++] = i + min;\n }\n }\n \n return nums;\n};\n\n```\n\n```go []\nfunc sortArray(nums []int) []int {\n if len(nums) <= 1 {\n return nums\n }\n \n min, max := nums[0], nums[0]\n for _, num := range nums {\n if num < min {\n min = num\n }\n if num > max {\n max = num\n }\n }\n \n count := make([]int, max - min + 1)\n for _, num := range nums {\n count[num - min]++\n }\n \n index := 0\n for i := 0; i < len(count); i++ {\n for count[i] > 0 {\n nums[index] = i + min\n index++\n count[i]--\n }\n }\n \n return nums\n}\n\n```\n\n | 26 | 1 | ['Array', 'Divide and Conquer', 'Sorting', 'C++', 'Java', 'Go', 'Python3', 'JavaScript'] | 3 |
sort-an-array | All 15 sorting methods solution is here_ | all-15-sorting-methods-solution-is-here_-24i3 | \nTable of Content:\nSTL\nMethod1: Standard\nMethod2: Stable\nInsertion Sort\nMethod1: Iterative\nMethod2: Recursive\nSelection Sort\nMethod1: Standard\nMethod2 | NextThread | NORMAL | 2022-01-13T05:37:12.621713+00:00 | 2022-01-13T05:37:12.621756+00:00 | 3,957 | false | ```\nTable of Content:\nSTL\nMethod1: Standard\nMethod2: Stable\nInsertion Sort\nMethod1: Iterative\nMethod2: Recursive\nSelection Sort\nMethod1: Standard\nMethod2: Standard using inbuilt\nBubble Sort\nQuick Sort\nMethod1: Standard\nMethod2: Randomised\nMerge Sort\nMethod1: Outplace Merging\nMethod2: Inplace Merging\nGeneralised Radix Sort\nMethod1: Using MinVal\nMethod2: Using Partitioning\nGeneralised Counting Sort\nHeap Sort\nBucket Sort\nSTL\nMethod1: Standard (Accepted) [T(n) = O(n * lgn)]\nvoid stlSort(vector<int>& nums) {\n\tsort(nums.begin(), nums.end());\n}\nMethod2: Stable (Accepted) [T(n) = O(n * lgn)]\nvoid stableStlSort(vector<int>& nums) {\n\tstable_sort(nums.begin(), nums.end());\n}\nInsertion Sort\nMethod1: Iterative (TLE) [T(n) = O(n^2)]\nvoid insertionSort(vector<int> &nums) {\n\tint sortedInd, unsortedInd, key, size = nums.size();\n\tif (size <= 1) return;\n\tfor (unsortedInd = 1; unsortedInd < size; unsortedInd++) {\n\t\tkey = nums[unsortedInd], sortedInd = unsortedInd;\n\t\twhile (--sortedInd >= 0 and key < nums[sortedInd])\n\t\t\tnums[sortedInd + 1] = nums[sortedInd];\n\t\tnums[sortedInd + 1] = key;\n\t}\n}\nMethod2: Recursive (TLE) [T(n) = O(n^2)]\nvoid recInsert(vector<int> &nums, int val) {\n\tif (!nums.size() or nums.back() <= val)\n\t\treturn nums.push_back(val);\n\tint last = nums.back();\n\tnums.pop_back();\n\trecInsert(nums, val);\n\tnums.push_back(last);\n}\n\t\nvoid recInsertionSort(vector<int> &nums) {\n\tif (nums.size() <= 1) return;\n\tint last = nums.back();\n\tnums.pop_back();\n\trecInsertionSort(nums);\n\trecInsert(nums, last);\n}\nSelection Sort\nMethod1: Standard (TLE) [T(n) = Theta(n^2)]\nvoid selectionSort(vector<int> &nums) {\n\tint minInd, startInd, currInd, size = nums.size();\n\tif (size <= 1) return;\n\tfor (startInd = 0; startInd < size - 1; startInd++) {\n\t\tfor (currInd = startInd + 1, minInd = startInd; currInd < size; currInd++)\n\t\t\tif (nums[minInd] > nums[currInd])\n\t\t\t\tminInd = currInd;\n\t\tif (minInd != startInd)\n\t\t\tswap(nums[startInd], nums[minInd]);\n\t}\n}\nMethod2: Standard using inbuilt (TLE) [T(n) = Theta(n^2)]\nvoid selectionSort(vector<int> &nums) {\n\tint minInd, startInd, size = nums.size();\n\tif (size <= 1) return;\n\tfor (startInd = 0; startInd < size - 1; startInd++) {\n\t\tminInd = min_element(nums.begin() + startInd, nums.end()) - nums.begin();\n\t\tif (minInd != startInd)\n\t\t\tswap(nums[startInd], nums[minInd]);\n\t}\n}\nBubble Sort (TLE) [T(n) = Theta(n^2)]\nvoid bubbleSort(vector<int> &nums) {\n\tint endInd, currInd, size = nums.size();\n\tif (size <= 1) return;\n\tfor (endInd = size - 1; endInd; endInd--)\n\t\tfor (currInd = 0; currInd < endInd; currInd++)\n\t\t\tif (nums[currInd] > nums[currInd + 1])\n\t\t\t\tswap(nums[currInd], nums[currInd + 1]);\n}\nQuick Sort\nMethod1: Standard (TLE) [T(n) = O(n^2)]\nint partitionArray(vector<int> &nums, int low, int high) {\n\tif (low >= high) return -1;\n\tint pivot = low, l = pivot + 1, r = high;\n\twhile (l <= r)\n\t\tif (nums[l] < nums[pivot]) l++;\n\t\telse if (nums[r] >= nums[pivot]) r--;\n\t\telse swap(nums[l], nums[r]);\n\tswap(nums[pivot], nums[r]);\n\treturn r;\n}\n\t\nvoid quickSort(vector<int> &nums, int low, int high) {\n\tif (low >= high) return;\n\tint pivot = partitionArray(nums, low, high);\n\tquickSort(nums, low, pivot);\n\tquickSort(nums, pivot + 1, high);\n}\nMethod2: Randomised (Accepted) [T(n) = O(n * lgn)]\nint partitionArray(vector<int> &nums, int low, int high) {\n\tif (low >= high) return -1;\n\tint pivot = low, l = pivot + 1, r = high;\n\twhile (l <= r)\n\t\tif (nums[l] < nums[pivot]) l++;\n\t\telse if (nums[r] >= nums[pivot]) r--;\n\t\telse swap(nums[l], nums[r]);\n\tswap(nums[pivot], nums[r]);\n\treturn r;\n}\n\nvoid quickSort(vector<int> &nums, int low, int high) {\n\tif (low >= high) return;\n\tswap(nums[low + rand() % (high - low + 1)], nums[low]);\n\tint pivot = partitionArray(nums, low, high);\n\tquickSort(nums, low, pivot);\n\tquickSort(nums, pivot + 1, high);\n}\nMerge Sort\nMethod1: Outplace Merging (Accepted) [T(n) = O(n * lgn)]\nvoid outPlaceMerge(vector<int> &nums, int low, int mid, int high) {\n\tif (low >= high) return;\n\tint l = low, r = mid + 1, k = 0, size = high - low + 1;\n\tvector<int> sorted(size, 0);\n\twhile (l <= mid and r <= high)\n\t\tsorted[k++] = nums[l] < nums[r] ? nums[l++] : nums[r++];\n\twhile (l <= mid) \n\t\tsorted[k++] = nums[l++];\n\twhile (r <= high) \n\t\tsorted[k++] = nums[r++];\n\tfor (k = 0; k < size; k++)\n\t\tnums[k + low] = sorted[k];\n}\n\nvoid mergeSort(vector<int> &nums, int low, int high) {\n\tif (low >= high) return;\n\tint mid = (high - low) / 2 + low;\n\tmergeSort(nums, low, mid);\n\tmergeSort(nums, mid + 1, high);\n\toutPlaceMerge(nums, low, mid, high);\n}\nMethod2: Inplace Merging (TLE) [T(n) = O(n^2)]\nvoid inPlaceMerge(vector<int> &nums, int low, int mid, int high) {\n\tif (low >= high) return;\n\tint l = low, r = mid + 1, size = high - low + 1;\n\twhile (l <= mid and r <= high) {\n\t\tif (nums[l] <= nums[r]) l++;\n\t\telse {\n\t\t\tint val = nums[r];\n\t\t\tfor (int k = r++; k > l; k--)\n\t\t\t\tnums[k] = nums[k - 1];\n\t\t\tnums[l++] = val;\n\t\t\tmid++;\n\t\t}\n\t}\n}\n\nvoid mergeSort(vector<int> &nums, int low, int high) {\n\tif (low >= high) return;\n\tint mid = (high - low) / 2 + low;\n\tmergeSort(nums, low, mid);\n\tmergeSort(nums, mid + 1, high);\n\tinPlaceMerge(nums, low, mid, high);\n}\nGeneralised Couting Sort (Accepted) [T(n) = Theta(max(n, m)) where m = max(Arr)]\nvoid countingSort(vector<int> &nums, bool isAscending=true) {\n\tint minVal = *min_element(nums.begin(), nums.end());\n\tint maxVal = *max_element(nums.begin(), nums.end());\n\tint freqSize = maxVal - minVal + 1 + 1, size = nums.size();\n\tvector<int> freq(freqSize, 0), sorted(size, 0);\n\tfor (int ind = 0; ind < size; ind++)\n\t\tfreq[nums[ind] - minVal]++;\n\tif (isAscending)\n\t\tfor (int ind = 1; ind < freqSize; ind++)\n\t\t\tfreq[ind] += freq[ind - 1];\n\telse\n\t\tfor (int ind = freqSize - 2; ind >= 0; ind--)\n\t\t\tfreq[ind] += freq[ind + 1];\n\t// for stable sorting start ind from end and decrement till 0\n\tfor (int ind = size - 1; ind >= 0; ind--)\n\t\tsorted[freq[nums[ind] - minVal]-- - 1] = nums[ind];\n\tnums = sorted;\n}\nGeneralised Radix Sort\nMethod1: Using MinVal (Accepted) [T(n) = Theta(n)]\nint getDigit(int num, int factor) {\n\treturn (abs(num) / abs(factor)) % 10;\n}\n\nvoid radixCountingSort(vector<int> &nums, int factor) {\n\tint freqSize = 10, size = nums.size();\n\tvector<int> freq(freqSize, 0), sorted(size, 0);\n\tfor (int ind = 0; ind < size; ind++)\n\t\tfreq[getDigit(nums[ind], factor)]++;\n\tfor (int ind = 1; ind < freqSize; ind++)\n\t\tfreq[ind] += freq[ind - 1];\n\t// for stable sorting start ind from end and decrement till 0\n\tfor (int ind = size - 1; ind >= 0; ind--)\n\t\tsorted[freq[getDigit(nums[ind], factor)]-- - 1] = nums[ind];\n\tnums = sorted;\n}\n\nvoid radixSort(vector<int> &nums) {\n\tint minVal = *min_element(nums.begin(), nums.end());\n\tfor (auto &num : nums) num -= minVal;\n\tint factor = 1, maxVal = *max_element(nums.begin(), nums.end());\n\twhile (maxVal / factor) {\n\t\tradixCountingSort(nums, factor);\n\t\tfactor *= 10;\n\t}\n\tfor (auto &num : nums) num += minVal;\n}\nMethod2: Using Partitioning (Accepted) [T(n) = Theta(n)]\n\nIdea is to partition the Array with pivot as mininum Positive Element and thus, left half array is of -ve no.s (if any) and right half array is of +ve no.s (if any). Finally we apply Radix Sort on both the parts.\nNote that to sort -ve no.s only with Radix Sort, we need to reverse sort the -ve no.s (eg: [-5,-4,-3] and [3,4,5])\n\nint partitionArray(vector<int> &nums, int low=0, int high=-1) {\n\thigh = high < 0 ? nums.size() - 1 : high;\n\tif (low >= high) return -1;\n\tint pivot = low, l = pivot + 1, r = high;\n\twhile (l <= r)\n\t\tif (nums[l] < nums[pivot]) l++;\n\t\telse if (nums[r] >= nums[pivot]) r--;\n\t\telse swap(nums[l], nums[r]);\n\tswap(nums[pivot], nums[r]);\n\treturn r;\n}\n\nint getDigit(int num, int factor) {\n\treturn (abs(num) / abs(factor)) % 10;\n}\n\npair<int, int> getMinAndNonNegMinInd(vector<int> &nums) {\n\tint minInd = nums.size(), minVal = INT_MAX;\n\tint nonNegMinInd = nums.size(), minNonNegVal = INT_MAX;\n\tfor (int i = 0; i < nums.size(); i++) {\n\t\tif (nums[i] >= 0 and nums[i] < minNonNegVal)\n\t\t\tnonNegMinInd = i, minNonNegVal = nums[i];\n\t\tif (nums[i] < minVal)\n\t\t\tminInd = i, minVal = nums[i];\n\t}\n\treturn {minInd, nonNegMinInd};\n}\n\nint radixSortPartionArray(vector<int> &nums) {\n\tauto [minInd, nonNegMinInd] = getMinAndNonNegMinInd(nums);\n\tif (nonNegMinInd < nums.size()) {\n\t\tif (nonNegMinInd) swap(nums[0], nums[nonNegMinInd]);\n\t\tif (nums[minInd] >= 0) nonNegMinInd = 0;\n\t\telse nonNegMinInd = partitionArray(nums);\n\t}\n\treturn nonNegMinInd;\n}\n\nvoid radixCountingSort(vector<int> &nums, int factor, int low, int high, bool isAscending=true) {\n\tif (low >= high) return;\n\tint freqSize = 10, size = high - low + 1;\n\tvector<int> freq(freqSize, 0), sorted(size, 0);\n\tfor (int ind = 0; ind < size; ind++)\n\t\tfreq[getDigit(nums[ind + low], factor)]++;\n\tif (isAscending)\n\t\t// reference: http://analgorithmaday.blogspot.com/2011/03/counting-sortlinear-time.html\n\t\tfor (int ind = 1; ind < freqSize; ind++)\n\t\t\tfreq[ind] += freq[ind - 1];\n\telse\n\t\tfor (int ind = freqSize - 2; ind >= 0; ind--)\n\t\t\tfreq[ind] += freq[ind + 1];\n\t// for stable sorting start ind from end and decrement till 0\n\tfor (int ind = size - 1; ind >= 0; ind--)\n\t\tsorted[freq[getDigit(nums[ind + low], factor)]-- - 1] = nums[ind + low];\n\tfor (int ind = 0; ind < size; ind++)\n\t\tnums[ind + low] = sorted[ind];\n}\n\nvoid radixSortHelper(vector<int> &nums, int low, int high, bool isAscending=true) {\n\tif (low >= high) return;\n\tint maxVal = *max_element(nums.begin() + low, nums.begin() + high + 1, [] (int &a, int &b) {\n\t\treturn abs(a) < abs(b);\n\t});\n\tint factor = 1;\n\twhile (maxVal / factor) {\n\t\tradixCountingSort(nums, factor, low, high, isAscending);\n\t\tfactor *= 10;\n\t}\n}\n\nvoid radixSort(vector<int> &nums) {\n\tint nonNegMinInd = radixSortPartionArray(nums);\n\tif (nonNegMinInd <= 1)\n\t\tradixSortHelper(nums, nonNegMinInd + 1, nums.size() - 1);\n\telse {\n\t\tradixSortHelper(nums, 0, nonNegMinInd - 1, false);\n\t\tradixSortHelper(nums, nonNegMinInd + 1, nums.size() - 1);\n\t}\n}\nHeap Sort (Accepted) [T(n) = O(n * lgn)]\nvoid heapifyDown(vector<int> &nums, int size, int rootInd, bool isMin=false) {\n\tif (size <= 1 or rootInd < 0 or rootInd >= size - 1) return;\n\tint keyInd = rootInd, leftChildInd = 2 * rootInd + 1, rightChildInd = 2 * rootInd + 2;\n\tif (leftChildInd < size and (isMin ? nums[leftChildInd] < nums[keyInd] : nums[leftChildInd] > nums[keyInd]))\n\t\tkeyInd = leftChildInd;\n\tif (rightChildInd < size and (isMin ? nums[rightChildInd] < nums[keyInd] : nums[rightChildInd] > nums[keyInd]))\n\t\tkeyInd = rightChildInd;\n\tif (nums[keyInd] != nums[rootInd]) {\n\t\tswap(nums[rootInd], nums[keyInd]);\n\t\theapifyDown(nums, size, keyInd, isMin);\n\t}\n}\n\nvoid heapifyArray(vector<int> &nums, bool isMin=false) {\n\tint size = nums.size();\n\tif (size <= 1) return;\n\tint tailRootInd = (size >> 1) - 1;\n\tfor (int rootInd = tailRootInd; rootInd >= 0; rootInd--)\n\t\theapifyDown(nums, size, rootInd, isMin);\n}\n\nvoid heapSort(vector<int> &nums) {\n\tif (nums.size() <= 1) return;\n\theapifyArray(nums);\n\tfor (int size = nums.size() - 1; size; size--) {\n\t\tswap(nums[size], nums[0]);\n\t\theapifyDown(nums, size, 0);\n\t}\n}\nBucket Sort\nBucket sort\'s performance depends upon the uniformity (distribution) of the input data. Hence, I am not discussing it here (I have not submitted it as well for given constraints). For more info on this Algo, you can google it.\n\nAmong above, Counting Sort was fastest in Leetcode OJ.\n``` | 24 | 0 | ['Recursion', 'C', 'Sorting', 'Heap (Priority Queue)', 'Merge Sort', 'Iterator'] | 3 |
sort-an-array | Python clean Quicksort | python-clean-quicksort-by-bindloss-7qtd | \nclass Solution(object):\n def sortArray(self, nums):\n self.quickSort(nums, 0, len(nums)-1)\n return nums\n\n def quickSort(self, nums, st | bindloss | NORMAL | 2019-11-15T08:58:11.479201+00:00 | 2021-09-14T11:43:10.095472+00:00 | 5,829 | false | ```\nclass Solution(object):\n def sortArray(self, nums):\n self.quickSort(nums, 0, len(nums)-1)\n return nums\n\n def quickSort(self, nums, start, end):\n if end <= start:\n return\n mid = (start + end) // 2\n nums[start], nums[mid] = nums[mid], nums[start]\n i = start + 1\n j = end\n while i <= j:\n while i <= j and nums[i] <= nums[start]:\n i += 1\n while i <= j and nums[j] >= nums[start]:\n j -= 1\n if i < j:\n nums[i], nums[j] = nums[j], nums[i] \n nums[start], nums[j] = nums[j], nums[start]\n self.quickSort(nums, start, j-1)\n self.quickSort(nums, j+1, end)\n``` | 24 | 1 | ['Python'] | 9 |
sort-an-array | Java | Counting Sort | O(n) time | Clean code | java-counting-sort-on-time-clean-code-by-9xvv | Complexity\n- Time complexity: O(n)\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# Co | judgementdey | NORMAL | 2024-07-25T00:06:10.468241+00:00 | 2024-07-25T00:06:10.468264+00:00 | 4,515 | false | # Complexity\n- Time complexity: $$O(n)$$\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```\nclass Solution {\n public int[] sortArray(int[] nums) {\n var map = new int[100001];\n\n for (var n : nums)\n map[n + 50000]++;\n\n var k = 0;\n for (var i = 0; i < 100001; i++)\n for (var j = 0; j < map[i]; j++)\n nums[k++] = i - 50000;\n\n return nums;\n }\n}\n```\nIf you like my solution, please upvote it! | 22 | 4 | ['Array', 'Sorting', 'Java'] | 14 |
sort-an-array | Java Solution|| Explained || 3 Methods || Hybrid sorting - Insertion, Quick & Merge sort || Fast | java-solution-explained-3-methods-hybrid-54ln | Explanation:\n OOH the question is asking us to sort an array, so simple right? use Arrays.sort(nums) and be done with life, but stop let\'s try not to be lazy | muhsinmansoor_ | NORMAL | 2022-08-25T20:03:08.323578+00:00 | 2022-08-25T20:03:08.323602+00:00 | 3,612 | false | **Explanation:**\n* OOH the question is asking us to sort an array, so simple right? use Arrays.sort(nums) and be done with life, but stop let\'s try not to be lazy today? we are going to solve this using top three basic sorting algorithms -- Insertion sort, Quick sort and Merge sort depending on the size of array.\n1. *Insertion sort* - stable sort and in-place, T: O(N^2) and S: O(1), good for lower size arrays.\n2. *Quick sort* - unstable and in-place, T: O(Nlogn) - average case and S: O(1) (ignorign recursion call stack memory), divide and conquer algorithm. The key part is partioning(Naive, Lomuto and Hoare\'s partition algorithm).\n3. *Merge Sort* - stable sort and not in-place(arguable) , T: O(NlogN) S: O(N) , used in external sorting - for massive data. The key part is mergeFunction - I used two pointer approach.\n\n**Code:**\n\n public int[] sortArray(int[] nums) {\n\t// we can check if our array is sorted or not by O(N) time.\n if (nums.length < 25) {\n insertionSort(nums);\n } else if (nums.length > 25 && nums.length < 1000 ) {\n quickSort(nums, 0, nums.length - 1);\n } else {\n\t\t mergeSort(nums, 0, nums.length - 1);\n }\n return nums;\n }\n static void mergeFun(int[] arr, int l, int m, int r) {\n int n1 = m + 1 - l;\n int n2 = r - m;\n int[] left = new int[n1];\n for (int i = 0; i < n1; i++) {\n left[i] = arr[l + i];\n }\n int[] right = new int[n2];\n for (int i = 0; i < n2; i++) {\n right[i] = arr[m + 1 + i];\n }\n int i = 0, j = 0, k = l;\n while (i < n1 || j < n2) {\n if (j == n2 || i < n1 && left[i] < right[j])\n arr[k++] = left[i++];\n else\n arr[k++] = right[j++];\n }\n }\n\n static void mergeSort(int[] arr, int low, int high) {\n if (low < high) {\n int middle = (high - low) / 2 + low;\n mergeSort(arr, low, middle);\n mergeSort(arr, middle + 1, high);\n mergeFun(arr, low, middle, high);\n }\n }\n\n static int partitionUsingHoare(int[] arr, int l, int h) {\n int pivot = arr[l];\n int i = l - 1;\n int j = h + 1;\n while (true) {\n do {\n i++;\n } while (arr[i] < pivot);\n do {\n j--;\n } while (arr[j] > pivot);\n if (i >= j) return j;\n swap(arr, i, j);\n }\n }\n\n static void swap(int[] arr, int i, int j) {\n int temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n\n static void quickSort(int[] arr, int low, int high) {\n if (low < high) {\n int p = partitionUsingHoare(arr, low, high);\n quickSort(arr, low, p);\n quickSort(arr, p + 1, high);\n }\n }\n\n static void insertionSort(int[] nums) { \n for (int i = 0; i < nums.length; i++) {\n int key = nums[i];\n int j = i - 1;\n while (j >= 0 && nums[j] > key) {\n nums[j + 1] = nums[j];\n j--;\n }\n nums[j + 1] = key;\n }\n }\n\n\n**IMP**: You can also bookmark/ subscribe to this post so as to revise above Sorting Algorithms whenvever you need to.\n\n**NOTE:**\nIf you find this post helpful then *please upvote*. It keeps me motivated to post such helpful solutions. Thanks! | 22 | 0 | ['Sorting', 'Merge Sort', 'Java'] | 5 |
sort-an-array | I will never ever forget merge sort again | i-will-never-ever-forget-merge-sort-agai-m4rs | i learned merge\'s sort from : https://www.youtube.com/watch?v=mB5HXBb_HY8\ncopy paste on youtube if link doesn\'t works\nhe explained really well , i really ap | RohanPrakash | NORMAL | 2020-05-14T18:16:12.922125+00:00 | 2020-05-19T16:58:14.201673+00:00 | 5,657 | false | i learned merge\'s sort from : https://www.youtube.com/watch?v=mB5HXBb_HY8\ncopy paste on youtube if link doesn\'t works\n**he explained really well** , i really appreciate his beirf explanation, watch this and then **come back here if you were not able to code**.\n\n**assuming you still needs help in coding part ( yeah I too needed ), here is the implementation**\n```\nvoid merge(vector<int> &a , int l , int mid , int h) // make sure you passed be reference else changes wont reflect \n {\n vector<int> x(a.begin()+l, a.begin()+mid+1); // making temp array for 1st segment \n vector<int> y(a.begin()+mid+1, a.begin()+h+1); // making temp array for 2nd segment\n \n int n = x.size();\n int m = y.size();\n int i,j,k; i=j=0; k=l;\n \n while(i<n and j<m) // standard merging algo as explained in video\n a[k++] = (x[i]<y[j]) ? x[i++] : y[j++];\n while(i<n)\n a[k++] = x[i++];\n while(j<m)\n a[k++] = y[j++]; \n\t} \n void mergeSort(vector<int> &a , int l , int h) // this function recursively calls itself until segment is greater than 1 length\n {\n if(l<h)\n {\n int mid = l+(h-l)/2;\n mergeSort(a,l,mid);\n mergeSort(a,mid+1,h);\n merge(a,l,mid,h);\n }\n } \n vector<int> sortArray(vector<int>& nums) { \n int n = nums.size();\n mergeSort(nums,0,n-1);\n return nums;\n }\n```\nThanks for reading, please upvote if this was helpful | 21 | 1 | ['Recursion', 'Sorting', 'Merge Sort', 'C++'] | 5 |
sort-an-array | Merge Sort Python3 | merge-sort-python3-by-ganjinaveen-f48u | 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 | GANJINAVEEN | NORMAL | 2023-03-01T11:21:12.527932+00:00 | 2023-03-01T11:21:12.527981+00:00 | 2,982 | 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 sortArray(self, nums: List[int]) -> List[int]:\n def merge(nums):\n if len(nums)>1:\n mid=len(nums)//2\n left_list=nums[:mid]\n right_list=nums[mid:]\n merge(left_list)\n merge(right_list)\n a,b,c=0,0,0\n while a<len(left_list) and b<len(right_list):\n if left_list[a]<right_list[b]:\n nums[c]=left_list[a]\n a+=1\n c+=1\n else:\n nums[c]=right_list[b]\n b+=1\n c+=1\n while a<len(left_list):\n nums[c]=left_list[a]\n a+=1\n c+=1\n while b<len(right_list):\n nums[c]=right_list[b]\n b+=1\n c+=1\n merge(nums)\n return nums\n #----->kindly upvote me if it\'s helpful \n``` | 19 | 0 | ['Python3'] | 3 |
sort-an-array | Python quicksort | python-quicksort-by-littletonconnor-70ra | \n\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n self.quicksort(nums, 0, len(nums) - 1)\n return nums\n \n def | littletonconnor | NORMAL | 2019-08-08T17:56:04.844388+00:00 | 2019-08-08T17:56:04.844430+00:00 | 14,212 | false | \n```\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n self.quicksort(nums, 0, len(nums) - 1)\n return nums\n \n def quicksort(self, nums, lower, upper):\n if lower < upper:\n pivot = self.partition(nums, lower, upper)\n self.quicksort(nums, lower, pivot - 1)\n self.quicksort(nums, pivot + 1, upper)\n else:\n return\n \n def partition(self, nums, lower, upper):\n \n pivot = nums[upper]\n \n i = lower\n \n for j in range(lower, upper):\n if nums[j] < pivot:\n nums[i], nums[j] = nums[j], nums[i]\n i += 1\n \n nums[i], nums[upper] = nums[upper], nums[i]\n \n return i\n``` | 19 | 1 | [] | 6 |
sort-an-array | C++ solution || with explanation || Let's code it💻 | c-solution-with-explanation-lets-code-it-wbt5 | Upvote if you found this solution helpful\uD83D\uDD25\n\n# Approach\nBasically the question is asking us to implement the merge sort algorithm to sort the array | piyusharmap | NORMAL | 2023-03-01T03:24:32.788091+00:00 | 2023-03-01T03:24:32.788142+00:00 | 5,558 | false | # Upvote if you found this solution helpful\uD83D\uDD25\n\n# Approach\nBasically the question is asking us to implement the merge sort algorithm to sort the array in ascending order.\nIn Merge sort we divide the given array into two parts, sort the parts individually and then merge those parts to get a sorted array.\nTo sort the parts we again apply merge sort on them and in this way we recurssively solve the question.\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> sortArray(vector<int>& nums) {\n int n = nums.size();\n mergeSort(nums, n);\n return nums;\n }\n\n //helper function\n void mergeSort(vector<int> &A, int n)\n {\n //if the size of array is less than two, it means it contains only a single element so there is no need of sorting -> simply return\n if (n < 2)\n return;\n //calculate the middle position\n int mid = n / 2;\n\n //initialize two array left and right to store the two parts of array\n vector<int> L;\n vector<int> R;\n\n for (int i = 0; i < n; i++)\n {\n //if the value of pointer is less than middle position push the element in left subarray\n if (i < mid)\n {\n L.push_back(A[i]);\n }\n //else push the element in right subarray\n else\n R.push_back(A[i]);\n }\n\n //sort both left and right subarray individually\n mergeSort(L, L.size());\n mergeSort(R, R.size());\n\n //merge left and right subarray after sorting them\n mergeArrays(A, L, R);\n }\n\n void mergeArrays(vector<int> &A, vector<int> &L, vector<int> &R)\n {\n\n int sizeL = L.size();\n int sizeR = R.size();\n //initialize pointers for each array -> left, right and final\n int i = 0, j = 0, k = 0;\n\n while (i < sizeL && j < sizeR)\n {\n //if element at position i of left array is less than or equal to element at position j of right -> update the position k of final array with left[i]\n if (L[i] <= R[j])\n {\n A[k] = L[i];\n i++;\n }\n //similarlly is element of right is less than element of left -> update the position of final array with element of right\n else\n {\n A[k] = R[j];\n j++;\n }\n k++;\n }\n\n //if still there are remaining element in an array , simply append them into the final array\n while (i < sizeL)\n {\n A[k] = L[i];\n i++;\n k++;\n }\n while (j < sizeR)\n {\n A[k] = R[j];\n j++;\n k++;\n }\n }\n};\n``` | 18 | 0 | ['Array', 'Sorting', 'Merge Sort', 'C++'] | 2 |
sort-an-array | ✅ One Line Solution | one-line-solution-by-mikposp-dyw6 | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)CodeTime complexity: O(n∗log(n)). Space complexity: | MikPosp | NORMAL | 2024-07-25T09:26:17.050273+00:00 | 2025-01-12T10:22:06.951764+00:00 | 1,256 | false | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)
# Code
Time complexity: $$O(n*log(n))$$. Space complexity: $$O(n)$$.
```python3
class Solution:
def sortArray(self, a: List[int]) -> List[int]:
return (f:=lambda a:len(a)==1 and a or merge(f(a[:(m:=len(a)//2)]),f(a[m:])))(a)
```
(Disclaimer 2: code above is just a product of fantasy packed into one line, it is not claimed to be 'true' oneliners - please, remind about drawbacks only if you know how to make it better) | 15 | 0 | ['Array', 'Divide and Conquer', 'Sorting', 'Merge Sort', 'Python', 'Python3'] | 1 |
sort-an-array | Python 3 || a cheat version and a legal version || T/S: 90% / 17% | python-3-a-cheat-version-and-a-legal-ver-fufr | I think the time% and space% on this problem are extremely skewed because of the scofflaws who usedsort(),sortedorheapq, not heeding the admonition on using "bu | Spaulding_ | NORMAL | 2023-03-01T19:55:22.357406+00:00 | 2024-05-31T17:12:24.740305+00:00 | 4,167 | false | I think the time% and space% on this problem are extremely skewed because of the scofflaws who used`sort()`,`sorted`or`heapq`, not heeding the admonition on using "built-in functions.".\n\nUsing `Counter`,`chain`,`max`,or,`mn` techically makes me a scofflaw too, so I included a non-scofflaw version below as well.\n\nMy scofflaw version:\n```\nclass Solution: \n def sortArray(self,nums:list[int]) -> list[int]: # Example: [3,3,1,8,6,5,5,5,5]\n\n ctr = Counter(nums) # ctr = {5:4, 3:2, 1:1, 8:1, 6:1}\n\n return list(chain(*([i]*ctr[i] # return list(chain( *([1]*1, [3]*2, [5]*4, [6]*1, [8]*1) )) \n for i in range(min(ctr), # = list(chain([1], [3,3,3], [5,5,5,5], [6], [8] ))\n max(ctr)+1) if i in ctr))) # = [1, 3,3, 5,5,5,5, 6, 8] \n \n\n```\n\nNon-scofflaw:\n```\nclass Solution:\n def sortArray(self, nums: list[int]) -> list[int]: \n\n ans, nSet, mx, mn = [],set(nums),nums[0],nums[0]\n d = {n:0 for n in nSet}\n\n for n in nums: d[n]+= 1\n\n for n in d:\n if n > mx: mx = n\n if n < mn: mn = n\n\n for i in range(mn, mx+1):\n if i not in d: continue\n ans+= [i]*d[i]\n\n return ans\n```\n[https://leetcode.com/problems/sort-an-array/submissions/1273481894/](https://leetcode.com/problems/sort-an-array/submissions/1273481894/)\n\n\nI could be wrong, but I think for each that time complexity is *O*(*N*) and space complexity is *O*(*N*), in which *N* ~ `len(nums)`. | 15 | 0 | ['Python3'] | 5 |
sort-an-array | Quick Sort & Merge Sort in Python, Easy to Understand, Standard Template! | quick-sort-merge-sort-in-python-easy-to-j1123 | Two Methods:\n1. Quick Sort\n2. Merge Sort\n\n1. Standard Quick Sort Tempate,\n\nIn the while loop, the reason we use "nums[left] < pivot" instead of "nums[left | GeorgePot | NORMAL | 2022-02-19T16:48:37.945168+00:00 | 2022-05-08T14:32:47.489937+00:00 | 3,268 | false | **Two Methods:**\n**1. Quick Sort**\n**2. Merge Sort**\n\n**1. Standard Quick Sort Tempate**,\n\nIn the while loop, the reason we use "**nums[left] < pivot**" instead of "nums[left] <= pivot" is to **avoid falling into forever loop**.\n**For example:**\nnums = [1, 1, 1], pivot will be 1.\nIf we use "nums[left] <= pivot",\nending right index will be 2, ending left index will be 3,\nin the next round, we still have to go through [1, 1, 1], meaning that we fall in to forever loop.\n\n**Time:** on average O(nlgn), worst case O(n^2)\n**Space:** O(lgn), on average the recursion stack\n\n```\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n if not nums:\n return nums\n self.quickSort(0, len(nums) - 1, nums)\n return nums\n \n def quickSort(self, start, end, nums):\n if start >= end:\n return\n \n left, right = start, end\n pivot = nums[(left + right) // 2]\n \n while left <= right:\n while left <= right and nums[left] < pivot:\n left += 1\n while left <= right and nums[right] > pivot:\n right -= 1\n if left <= right:\n nums[left], nums[right] = nums[right], nums[left]\n left += 1\n right -= 1\n\n self.quickSort(start, right, nums)\n self.quickSort(left, end, nums)\n```\n\n**2. Standard Merge Sort Template**\n\nFor merge sort, I will provide **two methods:**\nthe first one with space complexity O(nlgn),\nthe second one with space complexity optimized to O(n).\n\n**Method 2.1: space complexity O(nlgn)**\n\n**Time:** O(nlgn)\n**Space:** O(nlgn)\n\n```\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n if not nums:\n return nums\n self.mergeSort(0, len(nums) - 1, nums)\n return nums\n \n def mergeSort(self, start, end, nums):\n if start >= end:\n return \n \n middle = (start + end) // 2\n \n self.mergeSort(start, middle, nums)\n self.mergeSort(middle + 1, end, nums)\n self.merge(start, end, nums)\n \n def merge(self, start, end, nums):\n tmp = [0] * (end - start + 1)\n \n middle = (start + end) // 2\n left = start\n right = middle + 1\n index = 0\n \n while left <= middle and right <= end:\n if nums[left] <= nums[right]:\n tmp[index] = nums[left]\n left += 1\n index += 1\n else:\n tmp[index] = nums[right]\n right += 1\n index += 1\n \n while left <= middle:\n tmp[index] = nums[left]\n left += 1\n index += 1\n \n while right <= end:\n tmp[index] = nums[right]\n right += 1\n index += 1\n \n for i in range(end - start + 1):\n nums[i + start] = tmp[i]\n```\n\n**Method 2.2: space complexity O(n)**\n\n**Time:** O(nlgn)\n**Space:** O(n)\n\n```\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n if not nums:\n return nums\n tmp = [0] * len(nums)\n self.mergeSort(0, len(nums) - 1, nums, tmp)\n return nums\n \n def mergeSort(self, start, end, nums, tmp):\n if start >= end:\n return \n \n middle = (start + end) // 2\n \n self.mergeSort(start, middle, nums, tmp)\n self.mergeSort(middle + 1, end, nums, tmp)\n self.merge(start, end, nums, tmp)\n \n def merge(self, start, end, nums, tmp):\n \n middle = (start + end) // 2\n left = start\n right = middle + 1\n index = start\n \n while left <= middle and right <= end:\n if nums[left] <= nums[right]:\n tmp[index] = nums[left]\n left += 1\n index += 1\n else:\n tmp[index] = nums[right]\n right += 1\n index += 1\n \n while left <= middle:\n tmp[index] = nums[left]\n left += 1\n index += 1\n \n while right <= end:\n tmp[index] = nums[right]\n right += 1\n index += 1\n \n for i in range(start, end + 1):\n nums[i] = tmp[i]\n``` | 14 | 0 | ['Sorting', 'Merge Sort', 'Python'] | 1 |
sort-an-array | mergesort in python3 | mergesort-in-python3-by-dqdwsdlws-vjm8 | \nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n #mergesort\n if len(nums) <= 1:\n return nums\n midd | dqdwsdlws | NORMAL | 2020-10-22T15:08:44.555362+00:00 | 2020-10-22T15:08:44.555409+00:00 | 1,494 | false | ```\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n #mergesort\n if len(nums) <= 1:\n return nums\n middle = len(nums) // 2\n left = self.sortArray(nums[:middle])\n right = self.sortArray(nums[middle:])\n merged = []\n while left and right:\n if left[0] <= right [0]:\n merged.append(left.pop(0))\n else:\n merged.append(right.pop(0))\n merged.extend(right if right else left)\n return merged\n``` | 14 | 0 | ['Merge Sort', 'Python3'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.