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
diagonal-traverse-ii
[Python, Rust] Elegant & Short | O(n) | Ordered Map
python-rust-elegant-short-on-ordered-map-s097
Complexity\n- Time complexity: O(n)\n- Space complexity: O(n)\n\n# Code\n\npython []\nfrom collections import defaultdict, deque\n\nclass Solution:\n def fin
Kyrylo-Ktl
NORMAL
2023-11-22T10:43:20.235085+00:00
2023-11-22T10:43:20.235114+00:00
124
false
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n\n```python []\nfrom collections import defaultdict, deque\n\nclass Solution:\n def findDiagonalOrder(self, matrix: list[list[int]]) -> list[int]:\n diagonals = defaultdict(deque)\n\n for i, row in enumerate(matrix):\n for j, num in enumerate(row):\n diagonals[i + j].appendleft(num)\n\n return [num for diag in diagonals.values() for num in diag]\n```\n```rust []\nuse std::collections::{BTreeMap, VecDeque};\n\nimpl Solution {\n pub fn find_diagonal_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {\n let mut diagonals: BTreeMap<usize, VecDeque<i32>> = BTreeMap::new();\n\n for (i, row) in matrix.iter().enumerate() {\n for (j, &num) in row.iter().enumerate() {\n diagonals.entry(i + j).or_insert_with(VecDeque::new).push_front(num);\n }\n }\n\n diagonals.values().flat_map(|diag| diag.iter().cloned()).collect()\n }\n}\n```\n
3
0
['Python', 'Python3', 'Rust']
1
diagonal-traverse-ii
Heheheheheheeh O(n2)
heheheheheheeh-on2-by-ravishankar03-bkk7
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
ravishankar03
NORMAL
2023-11-22T09:40:56.100914+00:00
2023-11-22T09:40:56.100946+00:00
8
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& mat) {\n vector<int> ans;\n int n=mat.size();\n int m = 0;\n for(const auto& row : mat){\n m=max(m, static_cast<int>(row.size()));\n }\n vector<vector<int>> ref(m+n-1);\n int t=0,z;\n for(int i=0;i<n;i++){\n z=t+1;\n for(int j=0;j<mat[i].size();j++){\n ref[t++].push_back(mat[i][j]);\n }t=z;\n }int p,q;\n for(int i=0;i<ref.size();i++){\n if(ref[i].size()<1)break;\n p=ref[i].size()-1;\n q=-1;\n for(;p>q;p--)ans.push_back(ref[i][p]);\n }return ans;\n }\n};\n```
3
0
['C++']
0
diagonal-traverse-ii
Intuitive Double Loop Solution
intuitive-double-loop-solution-by-clutch-l6ge
Code\n\n/**\n * @param {number[][]} nums\n * @return {number[]}\n */\nvar findDiagonalOrder = function (nums) {\n if (!nums || nums.length === 0 || nums[0].
clutchMaster
NORMAL
2023-11-22T08:07:48.789895+00:00
2023-11-22T08:07:48.789949+00:00
332
false
# Code\n```\n/**\n * @param {number[][]} nums\n * @return {number[]}\n */\nvar findDiagonalOrder = function (nums) {\n if (!nums || nums.length === 0 || nums[0].length === 0) {\n return [];\n }\n\n const rows = nums.length;\n const cols = Math.max(...nums.map(row => row.length)); \n const result = [];\n\n for (let sum = 0; sum <= rows + cols - 2; sum++) {\n for (let row = Math.min(sum, rows - 1); row >= 0 && sum - row < cols; row--) {\n if (nums[row][sum - row] !== undefined) {\n result.push(nums[row][sum - row]);\n }\n }\n }\n\n return result;\n};\n```
3
0
['JavaScript']
0
diagonal-traverse-ii
🔥💥 C++ SHORT AND SIMPLE SOLUTION 💥🔥 USING MAPS 💥🔥 EASY TO UNDERSTAND 💥🔥
c-short-and-simple-solution-using-maps-e-apwb
APPROACH\n- STORED THE ELEMENTS OF THE MATRIX IN MAP w.r.t TO THE SUM OF THEIR INDEXES(i, j) \n- THEN STORING THE ELEMENTS IN THE ANS VECTOR IN THE REVERSE ORDE
anandakash2503
NORMAL
2023-11-22T03:42:16.765570+00:00
2023-11-27T06:24:16.786747+00:00
263
false
# APPROACH\n- STORED THE ELEMENTS OF THE MATRIX IN MAP w.r.t TO THE SUM OF THEIR INDEXES(i, j) \n- THEN STORING THE ELEMENTS IN THE ANS VECTOR IN THE REVERSE ORDER i.e. DESCENDING ORDER\n# Complexity\n- Time complexity: O(nlogn) [No. of elements anf logn for inserting in map]\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n\n# Code\n```\n#pragma GCC optimize("Ofast","inline","-ffast-math")\n#pragma GCC target("avx,mmx,sse2,sse3,sse4")\nstatic const int _ = []() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return 0; }();\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) \n {\n// STORED THE ELEMENTS OF THE MATRIX IN MAP w.r.t TO THE SUM OF THEIR INDEXES(i, j) \n map<int, vector<int>> mp;\n for(int i = 0; i < nums.size(); i++)\n {\n for(int j = 0; j < nums[i].size(); j++)\n {\n int x = i+j;\n mp[x].push_back(nums[i][j]);\n }\n }\n// THEN STORING THE ELEMENTS IN THE ANS VECTOR IN THE REVERSE ORDER i.e. DESCENDING ORDER\n vector<int> ans;\n for(auto it: mp)\n {\n for(int i = it.second.size()-1; i >= 0; i--) ans.push_back(it.second[i]);\n }\n return ans;\n }\n};\n```
3
0
['C++']
3
diagonal-traverse-ii
🔥💥 Easy C++ Solution Using HashMap💥🔥
easy-c-solution-using-hashmap-by-eknath_-304p
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires traversing a 2D array in a diagonal order and returning the elemen
eknath_mali_002
NORMAL
2023-11-22T01:36:46.278481+00:00
2023-11-22T01:36:46.278506+00:00
831
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires traversing a 2D array in a diagonal order and returning the elements. One way to approach this is to `simulate the diagonal traversal by using a map to store elements in diagonal order based on their positions`.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize an unordered map `mp` where the `keys represent the diagonal positions` and the values are vectors containing `elements on each diagonal`.\n2. Traverse the 2D array nums.\n - For each row in nums:\n - Initialize a counter `r_cnt` starting from 1 to track diagonal positions.\n - For each element in the row:\n - Insert the element into the map at the respective diagonal position.\n - Increment the diagonal position counter.\n - Increment the row counter `r_cnt`.\n3. `Reverse` the elements in each vector stored in the map to ensure the `correct order of elements in diagonal traversal`.\n4. Iterate through the map to retrieve elements in diagonal order and store them in the ans vector.\n5. Return the `ans` vector containing elements in diagonal order.\n# Complexity\n- Time complexity:$$O(n*m)$$\n - where `m` is the number of rows and `n` is the number of columns in the nums array. The traversal of the array. \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n*m)$$\n - `mp` map and $$O(n*m)$$ for the `ans` vector\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Code\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n unordered_map<int,vector<int>>mp;\n int r_cnt = 1;\n for(int i =0; i<nums.size(); i++){\n int c_cnt = r_cnt; // current diagonal number\n for(int j = 0; j<nums[i].size(); j++){\n mp[c_cnt].push_back(nums[i][j]);\n c_cnt++;\n }\n r_cnt++;\n }\n\n vector<int>ans;\n for(int i=1;i<=mp.size();i++) reverse(mp[i].begin(), mp[i].end());\n for(int i=1;i<=mp.size(); i++){\n for(auto it:mp[i]) ans.push_back(it);\n }\n return ans;\n }\n};\n````
3
0
['Hash Table', 'Matrix', 'C++']
0
diagonal-traverse-ii
using priority_queue with comparator function
using-priority_queue-with-comparator-fun-izww
\nclass Solution {\npublic:\n struct comp{\n bool operator()(pair<int,int>& x,pair<int,int>& y){\n if(x.first+x.second == y.first +y.second)\n
ng6
NORMAL
2023-01-10T17:36:59.693480+00:00
2023-05-02T09:43:11.950612+00:00
253
false
```\nclass Solution {\npublic:\n struct comp{\n bool operator()(pair<int,int>& x,pair<int,int>& y){\n if(x.first+x.second == y.first +y.second)\n return x.first<y.first;\n return x.first+x.second > y.first +y.second;\n } \n };\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n vector<int>ans;\n priority_queue<pair<int,int>,vector<pair<int,int>>,comp>pq;\n int n=nums.size();\n for(int i=0;i<n;i++)\n {\n int m=nums[i].size();\n for(int j=0;j<m;j++)\n {\n pq.push({i,j});\n }\n }\n while(!pq.empty())\n {\n ans.push_back(nums[pq.top().first][pq.top().second]);\n pq.pop();\n }\n return ans;\n }\n};\n```\n
3
0
['Heap (Priority Queue)', 'C++']
0
diagonal-traverse-ii
🔥 Javascript 2 Solution - BFS and Smart Sort
javascript-2-solution-bfs-and-smart-sort-cdbg
Solution 1\n\n\nfunction findDiagonalOrder(A, ans = []) {\n // set queue\n let q = [[0, 0]]\n \n // loop\n while (q.length !== 0) {\n // g
joenix
NORMAL
2022-06-23T13:51:43.434682+00:00
2022-06-23T13:51:43.434728+00:00
274
false
***Solution 1***\n\n```\nfunction findDiagonalOrder(A, ans = []) {\n // set queue\n let q = [[0, 0]]\n \n // loop\n while (q.length !== 0) {\n // get current value\n let a = q.pop()\n \n // y\n if(a[1] === 0 && a[0] + 1 < A.length) {\n q.unshift([a[0] + 1, a[1]])\n }\n \n // x\n if(a[1] + 1 < A[a[0]].length) {\n q.unshift([a[0], a[1] + 1])\n }\n \n // insert\n ans.push(A[a[0]][a[1]])\n }\n\n // result\n return ans\n}\n```\n\n***Solution 2***\n\n```\nfunction findDiagonalOrder(A, ans = []) {\n // deep 1\n for (var i = 0; i < A.length; i++) {\n // deep 2\n for (var j = 0; j < A[i].length; j++) {\n // init\n ans.push([i, j, A[i][j]])\n }\n }\n // result by sort :p\n return ans.sort((a, b) => a[0] + a[1] === b[0] + b[1] ? a[1] - b[1] : (a[0] + a[1]) - (b[0] + b[1])).map(r => r[2])\n}\n```
3
0
['JavaScript']
1
diagonal-traverse-ii
c++ solution using hashmap
c-solution-using-hashmap-by-ayush479-dcwh
\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& mat) {\n int m=mat.size(),n=mat[0].size();\n vector<int>res;\n
Ayush479
NORMAL
2022-02-15T08:24:28.275380+00:00
2022-02-15T08:24:28.275423+00:00
177
false
```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& mat) {\n int m=mat.size(),n=mat[0].size();\n vector<int>res;\n map<int,vector<int>>mp;\n for(int i=0;i<m;i++){\n for(int j=0;j<mat[i].size();j++){\n mp[i+j].push_back(mat[i][j]);\n }\n }\n for(auto x:mp){\n \n reverse(x.second.begin(),x.second.end());\n\n for(auto i:x.second){\n res.push_back(i);\n }\n }\n\n return res;\n }\n};\n\nPls upvote if you like it\n```
3
1
['C']
0
diagonal-traverse-ii
[Java] Sorting the positions
java-sorting-the-positions-by-bigfield-5fj6
Besides the popular HashMap based solution, here I wanted to share the sorting based solution just for reference.\n```\n public int[] findDiagonalOrder(List>
bigfield
NORMAL
2022-02-03T06:10:42.531418+00:00
2022-02-03T06:12:17.479190+00:00
340
false
Besides the popular HashMap based solution, here I wanted to share the sorting based solution just for reference.\n```\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n List<int[]> positions = new ArrayList();\n for (int r = 0; r < nums.size(); r++) {\n for (int c = 0; c < nums.get(r).size(); c++) {\n positions.add(new int[]{r, c});\n }\n }\n Collections.sort(positions, (a, b) -> (a[0] + a[1] == b[0] + b[1] ? b[0] - a[0] : (a[0] + a[1] - b[0] - b[1])));\n int[] res = new int[positions.size()];\n int i = 0;\n for (int[] pos : positions)\n res[i++] = nums.get(pos[0]).get(pos[1]);\n return res;\n }
3
0
['Sorting', 'Java']
1
diagonal-traverse-ii
Java || Easy Approach With Explanation || HashMap || ArrayDeque
java-easy-approach-with-explanation-hash-5d3j
\nclass Solution\n{//T-> O(M x N) S -> O(N)\n public int[] findDiagonalOrder(List<List<Integer>> nums)\n {\n Map<Integer, ArrayDeque<Integer>> map
swapnilGhosh
NORMAL
2021-08-06T17:49:50.187599+00:00
2021-08-06T17:49:50.187637+00:00
355
false
```\nclass Solution\n{//T-> O(M x N) S -> O(N)\n public int[] findDiagonalOrder(List<List<Integer>> nums)\n {\n Map<Integer, ArrayDeque<Integer>> map= new HashMap<>();//diagonal -- element associated with it \n \n int maxD= 0, sizeR= 0, index= 0;\n \n for(int i= 0; i< nums.size(); i++)//traversing the row in the 2 D array \n {\n sizeR+= nums.get(i).size();//calculating the number of element in the 2D Array \n \n for(int j= 0; j< nums.get(i).size(); j++)//traversing inside the row in the 2 D array \n {\n int diagonal= i+j;//diagonal we are currently dealing with \n \n map.putIfAbsent(diagonal, new ArrayDeque<Integer>());//if the diagonal is not present in the HashMap, then creating a entry with that diagonal\n \n map.get(diagonal).addFirst(nums.get(i).get(j));//Insertion order is Maintained by ArrayDeque//putting into the Array \n \n maxD= Math.max(maxD, diagonal);//calculating the maximum diagonal at every instant \n }\n }\n \n int[] res= new int[sizeR];//rresultant array containing the diagonal order traversal elements\n \n for(int i= 0; i<= maxD; i++)//every diagonal is associated with number of elements\n {\n while(!map.get(i).isEmpty())\n {\n res[index]= map.get(i).poll();//retring the elements associated witheach diagonal, sequentially \n index+= 1;//for moving fro one index to another index in the resultant Array \n }\n }\n return res;//returning the resultant Array\n }\n}//please do upvote, it helps a lot\n```
3
1
['Queue', 'Java']
0
diagonal-traverse-ii
My Python solution
my-python-solution-by-vrohith-i3uc
\n"""\nIf we pass \u2018list\u2019 (without the quotes) to the defaultdict() Pytohn function, we can group a sequence of key-value pairs into a dictionary of li
vrohith
NORMAL
2020-10-02T11:50:01.612411+00:00
2020-10-02T11:50:01.612444+00:00
578
false
```\n"""\nIf we pass \u2018list\u2019 (without the quotes) to the defaultdict() Pytohn function, we can group a sequence of key-value pairs into a dictionary of lists. We can do this to more types as well. We\u2019ll see another in the next section.\n\n>>> a=[(\'a\',1),(\'b\',2),(\'c\',3)]\n>>> b=defaultdict(list)\n>>> for i,j in a:\n b[i].append(j) \n>>> b\ndefaultdict(<class \u2018list\u2019>, {\u2018a\u2019: [1], \u2018b\u2019: [2], \u2018c\u2019: [3]})\n"""\n\nclass Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n dictionary = defaultdict(list)\n for i in range(len(nums)):\n for j in range(len(nums[i])):\n dictionary[i+j].append(nums[i][j])\n return [v for k in dictionary.keys() for v in reversed(dictionary[k])]\n```
3
0
['Python', 'Python3']
2
diagonal-traverse-ii
C++
c-by-diveyk-xmrw
Based on the fact that sum of index (i & j) are equal for diagnol elements\n```\nclass Solution {\npublic:\nvector findDiagonalOrder(vector>& nums) {\n\tmap> m;
diveyk
NORMAL
2020-06-03T16:39:12.560284+00:00
2020-06-03T16:39:12.560336+00:00
175
false
Based on the fact that sum of index (i & j) are equal for diagnol elements\n```\nclass Solution {\npublic:\nvector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n\tmap<int,list<int>> m;\n\tvector<int> res;\n\t\n for(int i=0;i<nums.size();i++){\n for(int j=0;j<nums[i].size();j++){\n m[i+j].push_front(nums[i][j]);\t\n }\t\t\n }\n\t\n for(auto x:m){\n for(auto val:x.second){\n res.push_back(val);\n }\n }\n return res;\n}\n};
3
1
[]
0
diagonal-traverse-ii
Python 3 Dict Mem beats 100%
python-3-dict-mem-beats-100-by-clairelee-wv43
\nclass Solution(object):\n def findDiagonalOrder(self, nums):\n """\n :type nums: List[List[int]]\n :rtype: List[int]\n """\n
clairelee
NORMAL
2020-06-03T05:43:32.914568+00:00
2020-06-03T05:43:32.914608+00:00
233
false
```\nclass Solution(object):\n def findDiagonalOrder(self, nums):\n """\n :type nums: List[List[int]]\n :rtype: List[int]\n """\n dic = {}\n for i in range(len(nums)):\n for j in range(len(nums[i])):\n dic[i+j] = dic.get((i+j), []) + [nums[i][j]]\n res = []\n for key in sorted(dic.keys()):\n res.extend(reversed(dic[key]))\n return res\n```
3
0
[]
1
diagonal-traverse-ii
[Java] HashMap with LinkedList O(n)
java-hashmap-with-linkedlist-on-by-mausa-ntyq
```\nvisit link https://leetcode.com/problems/diagonal-traverse-ii/discuss/597741/Clean-Simple-Easiest-Explanation-with-a-picture-and-code-with-comments for cle
mausami
NORMAL
2020-04-26T07:50:54.582250+00:00
2020-04-26T07:50:54.582304+00:00
364
false
```\nvisit link https://leetcode.com/problems/diagonal-traverse-ii/discuss/597741/Clean-Simple-Easiest-Explanation-with-a-picture-and-code-with-comments for clear explaination, my idea is same as this one.\n\nNote : Use link list instead of array list while key -> value mapping to reduce compelxity,\nif you use array list you will need to reverse list after adding element because elements were added top row to bottom row but we will need to show bottom to top elements as diagonally.\n\n\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n int size = 0;\n Map<Integer, LinkedList<Integer>> map = new HashMap<>(); \n for(int i=0; i<nums.size(); i++) {\n List<Integer> numList = nums.get(i);\n for(int j=0; j<numList.size(); j++) {\n int index = i+j;\n LinkedList<Integer> list = map.get(index);\n if(list == null) {\n list = new LinkedList<>();\n }\n list.addFirst(numList.get(j));\n map.put(index, list);\n size++;\n }\n }\n\n int maxLen = Collections.max(map.keySet());\n List<Integer> resultList = new ArrayList<Integer>();\n for(int i = 0; i <= maxLen; i++) {\n List<Integer> diagValue = map.get(i);\n resultList.addAll(diagValue);\n }\n \n int[] res = new int[resultList.size()];\n for(int i = 0; i < res.length; i++) {\n res[i] = resultList.get(i); \n }\n \n return res; \n }
3
1
[]
1
diagonal-traverse-ii
Maps Python
maps-python-by-aj_to_rescue-9r6j
\nclass Solution:\n def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:\n result = [ ]\n dd = collections.defaultdict(list)\n
aj_to_rescue
NORMAL
2020-04-26T04:13:47.924545+00:00
2020-04-26T04:13:47.924578+00:00
365
false
```\nclass Solution:\n def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:\n result = [ ]\n dd = collections.defaultdict(list)\n if not matrix: return result\n for i in range(0, len(matrix)):\n for j in range(0, len(matrix[i])):\n dd[i+j+1].append(matrix[i][j])\n for _, value in dd.items():\n result += (value[::-1])\n return result\n```
3
0
['Python', 'Python3']
0
diagonal-traverse-ii
C# PriorityQueue & Queue
c-priorityqueue-queue-by-leoooooo-4aae
PriorityQueue:\n\n\npublic class Solution\n{\n public int[] FindDiagonalOrder(IList<IList<int>> nums)\n {\n var pq = new SortedSet<(int Weight, int
leoooooo
NORMAL
2020-04-26T04:11:15.463868+00:00
2020-04-26T04:30:08.722404+00:00
186
false
PriorityQueue:\n\n```\npublic class Solution\n{\n public int[] FindDiagonalOrder(IList<IList<int>> nums)\n {\n var pq = new SortedSet<(int Weight, int Row, int Value)>();\n\n for (int row = nums.Count - 1; row >= 0; row--)\n {\n for (int index = 0; index < nums[row].Count; index++)\n {\n pq.Add((row + index, nums.Count - row, nums[row][index]));\n }\n }\n\n return pq.Select(x => x.Value).ToArray();\n }\n}\n```\n\n\nQueue:\n```\npublic class Solution\n{\n public int[] FindDiagonalOrder(IList<IList<int>> nums)\n {\n var res = new List<int>();\n var q = new Queue<(int Row, int Col)>();\n q.Enqueue((0,0));\n while(q.Count > 0)\n {\n var cur = q.Dequeue();\n int row = cur.Row;\n int col = cur.Col;\n res.Add(nums[row][col]);\n if(col == 0 && row < nums.Count - 1)\n q.Enqueue((row + 1, col));\n if(col < nums[row].Count - 1)\n q.Enqueue((row, col + 1));\n }\n \n return res.ToArray();\n }\n}\n```
3
0
[]
0
diagonal-traverse-ii
Using Map💡💡💡
using-map-by-vishalkumar00-469m
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
vishalkumar00
NORMAL
2023-11-22T17:26:36.126244+00:00
2023-11-22T17:26:36.126273+00:00
108
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n vector<int>ans;\n map<int,vector<int>>m;\n for(int i=0;i<nums.size();i++){\n for(int j=0;j<nums[i].size();j++){\n int sum=i+j;\n m[sum].push_back(nums[i][j]);\n }\n }\n for(auto x:m){\n reverse(x.second.begin(),x.second.end());\n for(auto i:x.second){\n ans.push_back(i);\n }\n }\n return ans;\n }\n};\n```
2
0
['C++']
0
diagonal-traverse-ii
80%beats
80beats-by-krishna170902-nl67
\n\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n int n=nums.size();\n vector<pair<int,pair<int,int>
krishna170902
NORMAL
2023-11-22T17:12:51.556676+00:00
2023-11-22T17:12:51.556702+00:00
6
false
\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n int n=nums.size();\n vector<pair<int,pair<int,int>>>res;\n for(int i=0;i<n;i++)\n {\n int size=nums[i].size();\n for(int j=0;j<size;j++)\n {\n res.push_back({i+j,{j,nums[i][j]}});\n }\n }\n sort(res.begin(),res.end());\n vector<int>ans;\n for(int i=0;i<res.size();i++)\n ans.push_back(res[i].second.second);\n return ans;\n }\n};\n```
2
0
['C++']
0
diagonal-traverse-ii
[C++] Queue (BFS)
c-queue-bfs-by-awesome-bug-d9eb
Intuition\n Describe your first thoughts on how to solve this problem. \n- Simulate the iterator for each row\n\n# Approach\n Describe your approach to solving
pepe-the-frog
NORMAL
2023-11-22T14:22:13.031577+00:00
2023-11-22T14:22:13.031604+00:00
129
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Simulate the iterator for each row\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Use BFS (Breadth-First Search)\n - handle the current element\n - insert the next row (if exists)\n - insert the next column in the same row (if exists)\n\n# Complexity\n- Time complexity: $$O(sum(nums[i].length))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(nums.length)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n // time/space: O(sum(nums[i].length))/O(nums.length)\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n queue<pair<int, int>> q; // {row, column}\n q.push({0, 0});\n\n // BFS (Breadth-First Search)\n vector<int> result;\n while (!q.empty()) {\n int size = q.size();\n for (int i = 0; i < size; i++) {\n // handle the current element\n auto [r, c] = q.front();\n q.pop();\n result.push_back(nums[r][c]);\n // insert the next row\n if (((r + 1) < nums.size()) && (c == 0)) q.push({r + 1, 0});\n // insert the next column in the same row\n if ((c + 1) < nums[r].size()) q.push({r, c + 1});\n }\n }\n return result;\n }\n};\n```
2
0
['Breadth-First Search', 'Queue', 'Simulation', 'C++']
0
diagonal-traverse-ii
Swift solution
swift-solution-by-azm819-hips
Complexity\n- Time complexity: O(n * log(n)) \n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n
azm819
NORMAL
2023-11-22T11:30:03.316103+00:00
2023-11-22T11:30:03.316122+00:00
23
false
# Complexity\n- Time complexity: $$O(n * log(n))$$ \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n func findDiagonalOrder(_ nums: [[Int]]) -> [Int] {\n var elements = [(i: Int, indSum: Int, num: Int)]()\n for i in 0 ..< nums.count {\n for j in 0 ..< nums[i].count {\n elements.append((i, i + j, nums[i][j]))\n }\n }\n elements.sort { lhs, rhs in\n lhs.indSum < rhs.indSum ||\n lhs.indSum == rhs.indSum && lhs.i > rhs.i\n }\n return elements.map(\\.num)\n }\n}\n```
2
0
['Array', 'Swift', 'Sorting', 'Heap (Priority Queue)']
0
diagonal-traverse-ii
Sorting
sorting-by-amoi_ty-kmbm
Intuition & Approach\n Describe your first thoughts on how to solve this problem. \n##### Sort with the custom comparator function, which gives row priority if
amoi_ty
NORMAL
2023-11-22T08:57:44.232672+00:00
2023-11-22T08:57:44.232706+00:00
10
false
# Intuition & Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\n##### Sort with the custom comparator function, which gives row priority if sum of indexes are equal, and else the one with lower sum of indexes.\n\n# Complexity\n$$k : total\\_number\\_of\\_elements$$\n- Time complexity: **$$O(klogk)$$**\n\n- Space complexity: **$$O(k)$$**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n int n=nums.size();\n vector<pair<int,pair<int,int>>> v;\n for(int i=0; i<n; i++) {\n int m=nums[i].size();\n for(int j=0; j<m; j++) {\n v.push_back({nums[i][j],{i,j}});\n }\n }\n sort(v.begin(),v.end(),[&](auto a, auto b) {\n int i1=a.second.first, j1=a.second.second;\n int i2=b.second.first, j2=b.second.second;\n if(i1+j1==i2+j2) return i1>i2;\n return i1+j1<i2+j2;\n });\n vector<int> ans;\n for(auto &it: v) ans.push_back(it.first);\n return ans;\n }\n};\n```
2
0
['C++']
0
diagonal-traverse-ii
😎🚀 Easy To Understand | 10 Lines 🦅 | C++ | JAVA | PYTHON 🚀
easy-to-understand-10-lines-c-java-pytho-pefl
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
The_Eternal_Soul
NORMAL
2023-11-22T08:06:27.561874+00:00
2023-11-22T08:06:27.561908+00:00
356
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n \n int n = nums.size();\n vector<vector<int>> arr; // row+col,col,nums[row][col]\n\n for(int i = 0; i < n; i++)\n {\n for(int j = 0; j < nums[i].size(); j++)\n {\n arr.push_back({i+j,j,nums[i][j]});\n }\n }\n sort(arr.begin(),arr.end());\n vector<int> ans;\n for(auto x : arr)\n {\n ans.push_back(x[2]);\n }\n return ans;\n }\n};\n```
2
0
['Array', 'Sorting', 'Python', 'C++', 'Java', 'JavaScript']
1
diagonal-traverse-ii
C++ array of deque->2D array
c-array-of-deque-2d-array-by-ankita2905-jjwh
Intuition\nUse array of deque diag to store the numbers on diagonal.\n\n# Approach\nIterate the nums. Push front nums[i][j] on the deque diag[i+j].\n\n# Complex
Ankita2905
NORMAL
2023-11-22T06:29:05.657785+00:00
2023-11-22T06:29:05.657807+00:00
23
false
# Intuition\nUse array of deque diag to store the numbers on diagonal.\n\n# Approach\nIterate the nums. Push front nums[i][j] on the deque diag[i+j].\n\n# Complexity\n- Time complexity:\nO(sz)\n\n- Space complexity:\nO(sz)\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n int n=nums.size(), M=0, sz;\n \n for(int i=0; i<n; i++){\n M=max(M, i+(int)nums[i].size());// Find max index for diag\n sz+=nums[i].size();// Compute the real size sz for nums\n }\n vector<deque<int>> diag(M+1);\n\n \n for(int i=0; i<n; i++){\n int col=nums[i].size();\n \n for(int j=0; j<col; j++){\n //Push front keeps the order\n diag[i+j].push_front(nums[i][j]); \n }\n }\n vector<int> ans(sz);\n int idx=0;\n \n for(int i=0; i<=M; i++){\n for(int x: diag[i])\n ans[idx++]=x; // Put into ans array\n }\n return ans;\n }\n};\n```
2
0
['C++']
1
diagonal-traverse-ii
Video Solution | Explanation With Drawings | In Depth | Java | C++
video-solution-explanation-with-drawings-grfh
Intuition, approach, and complexity dicussed in video solution in detail.\n\n# Code\nC++\n\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<
Fly_ing__Rhi_no
NORMAL
2023-11-22T05:26:31.160804+00:00
2023-11-22T05:26:31.160832+00:00
397
false
# Intuition, approach, and complexity dicussed in video solution in detail.\n\n# Code\nC++\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n deque<pair<int, int>> queue;\n int rows = nums.size(), cols = nums[0].size();\n int indx = 0;\n vector<int> result;\n result.push_back(nums[0][0]);\n queue.push_back(make_pair(0, 0));\n while(!queue.empty()){\n int sz = queue.size();\n while(sz-- > 0){\n auto currCell = queue.front();\n queue.pop_front();\n int currentRow = currCell.first, currentCell = currCell.second;\n if(currentRow + 1 < rows && currentCell < nums[currentRow + 1].size() && nums[currentRow + 1][currentCell] != -1){\n queue.push_back(make_pair(currentRow + 1, currentCell));\n result.push_back(nums[currentRow + 1][currentCell]);\n nums[currentRow + 1][currentCell] = -1;\n }\n if(currentCell + 1 < nums[currentRow].size() && nums[currentRow][currentCell + 1] != -1){\n queue.push_back(make_pair(currentRow, currentCell + 1));\n result.push_back(nums[currentRow][currentCell + 1]);\n nums[currentRow][currentCell + 1] = -1;\n }\n }\n }\n return result;\n }\n};\n```\nJava\n```\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n Deque<Pair<Integer, Integer>> queue = new ArrayDeque<>();\n int rows = nums.size();\n int indx = 0;\n List<Integer> result = new ArrayList<>();\n result.add(nums.get(0).get(0));\n queue.offerLast(new Pair<Integer, Integer>(0, 0));\n while(!queue.isEmpty()){\n int sz = queue.size();\n while(sz-->0){\n var currCell = queue.pollFirst();\n int currentRow = currCell.getKey(), currentCol = currCell.getValue(); \n if(currentRow + 1 < rows && currentCol < nums.get(currentRow + 1).size() && nums.get(currentRow + 1).get(currentCol) != -1){\n queue.offerLast(new Pair<Integer, Integer> (currentRow + 1, currentCol));\n result.add(nums.get(currentRow+1).get(currentCol));\n nums.get(currentRow + 1).set(currentCol, -1);\n }\n if(currentCol + 1 < nums.get(currentRow).size() && nums.get(currentRow).get(currentCol + 1) != -1){\n queue.offerLast(new Pair<Integer, Integer>(currentRow, currentCol + 1));\n result.add(nums.get(currentRow).get(currentCol + 1));\n nums.get(currentRow).set(currentCol+1, -1);\n }\n }\n }\n return result.stream().mapToInt(x->x).toArray();\n }\n}\n```
2
0
['C++', 'Java']
1
diagonal-traverse-ii
C++ Solution
c-solution-by-pranto1209-x44d
Approach\n Describe your approach to solving the problem. \n BFS\n\n# Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \n O(N)\n\
pranto1209
NORMAL
2023-11-22T05:24:52.722895+00:00
2023-11-22T05:24:52.722925+00:00
7
false
# Approach\n<!-- Describe your approach to solving the problem. -->\n BFS\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(sqrt(N))\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n queue<pair<int, int>> q;\n q.push({0, 0});\n vector<int> ans;\n while (!q.empty()) {\n auto [row, col] = q.front();\n q.pop();\n ans.push_back(nums[row][col]);\n if (col == 0 && row + 1 < nums.size()) {\n q.push({row + 1, col});\n }\n if (col + 1 < nums[row].size()) {\n q.push({row, col + 1});\n }\n }\n return ans;\n }\n};\n```
2
0
['C++']
0
diagonal-traverse-ii
✅ Beats 100% of users with Java in Runtime & 98.94% in Memory || Map+ Sum || TC= 0(n+m) SC= 0(n)🔥✅
beats-100-of-users-with-java-in-runtime-9d4zt
Example Explanation\n## Example:\n### Input: nums = [[1,2,3],[4,5,6],[7,8,9]]\n### Step 1: Initializing Variables\n- Let\'s start by initializing some variables
maheshkumarofficial
NORMAL
2023-11-22T04:40:38.506392+00:00
2023-11-22T04:40:38.506419+00:00
496
false
# Example Explanation\n## Example:\n### Input: nums = [[1,2,3],[4,5,6],[7,8,9]]\n### Step 1: Initializing Variables\n- Let\'s start by initializing some variables:\n- Number of rows (3 in this case)\n- maxSum: Maximum sum of row and column indices (initialized to 0)\n- size: Total number of elements in nums (initialized to 0)\n- index: Current index in the result array (initialized to 0)\n### Step 2: Creating the Map\n- Next, we create a map to store elements based on their diagonal positions.\n- We also update size and maxSum as we iterate through the elements of nums.\n# Intuition\nThe problem involves traversing a 2D array diagonally and returning the elements in diagonal order. To achieve this, we can create a mapping of the diagonal sums and store the elements belonging to each sum. Finally, we\'ll extract the elements from the mapping in reverse order to get the diagonal order.\n\n# Approach\n* Create an array map of ArrayList to store elements based on their diagonal sum.\n* Traverse the given 2D array nums and populate the map with elements based on their diagonal sum.\n* Determine the maximum diagonal sum encountered (maxSum).\n* Initialize an array res to store the final result.\n* Traverse the map from 0 to maxSum and for each diagonal sum, retrieve the elements in reverse order and add them to res.\n* Return the resulting array res.\n# Complexity\n### Time Complexity:\nThe time complexity is O(N + M), where N is the total number of elements in the 2D array and M is the maximum diagonal sum.\n### Space Complexity:\nThe space complexity is O(N) to store the mapping.\n\n# My Codes\n### Java\n```\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n int m = nums.size(), maxSum = 0, size = 0, index = 0;\n List<Integer>[] map = new ArrayList[100001];\n for (int i = 0; i < m; i++) {\n size += nums.get(i).size();\n for (int j = 0; j < nums.get(i).size(); j++) {\n int sum = i + j;\n if (map[sum] == null) map[sum] = new ArrayList<>();\n map[sum].add(nums.get(i).get(j));\n maxSum = Math.max(maxSum, sum);\n }\n }\n int[] res = new int[size];\n for (int i = 0; i <= maxSum; i++) {\n List<Integer> cur = map[i];\n for (int j = cur.size() - 1; j >= 0; j--) {\n res[index++] = cur.get(j);\n }\n }\n return res;\n }\n}\n```\n### C++\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n int m = nums.size(), maxSum = 0, size = 0, index = 0;\n std::vector<std::vector<int>> map(100001);\n \n for (int i = 0; i < m; i++) {\n size += nums[i].size();\n for (int j = 0; j < nums[i].size(); j++) {\n int sum = i + j;\n map[sum].push_back(nums[i][j]);\n maxSum = std::max(maxSum, sum);\n }\n }\n \n std::vector<int> res(size);\n for (int i = 0; i <= maxSum; i++) {\n std::vector<int>& cur = map[i];\n for (int j = cur.size() - 1; j >= 0; j--) {\n res[index++] = cur[j];\n }\n }\n \n return res;\n }\n};\n```\n### Python\n```\nclass Solution(object):\n def findDiagonalOrder(self, nums):\n m = len(nums)\n maxSum, size, index = 0, 0, 0\n map = [[] for _ in range(100001)]\n \n for i in range(m):\n size += len(nums[i])\n for j in range(len(nums[i])):\n _sum = i + j\n map[_sum].append(nums[i][j])\n maxSum = max(maxSum, _sum)\n \n res = [0] * size\n for i in range(maxSum + 1):\n cur = map[i]\n for j in range(len(cur) - 1, -1, -1):\n res[index] = cur[j]\n index += 1\n \n return res\n \n```\n### JavaScript\n\n```\nvar findDiagonalOrder = function(nums) {\n let m = nums.length;\n let maxSum = 0, size = 0, index = 0;\n let map = new Array(100001);\n \n for (let i = 0; i < m; i++) {\n size += nums[i].length;\n for (let j = 0; j < nums[i].length; j++) {\n let sum = i + j;\n if (!map[sum]) map[sum] = [];\n map[sum].push(nums[i][j]);\n maxSum = Math.max(maxSum, sum);\n }\n }\n \n let res = new Array(size);\n for (let i = 0; i <= maxSum; i++) {\n let cur = map[i];\n for (let j = cur.length - 1; j >= 0; j--) {\n res[index++] = cur[j];\n }\n }\n \n return res;\n};\n```\n![Upvotes.jpeg](https://assets.leetcode.com/users/images/8bbf7750-0632-4c13-859d-601834945646_1700627980.4229007.jpeg)\n
2
0
['Python', 'C++', 'Java', 'JavaScript']
2
diagonal-traverse-ii
DFS solution
dfs-solution-by-tranquoctoan1996-tq5i
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
TranQuocToan1996
NORMAL
2023-11-22T04:12:54.228198+00:00
2023-11-22T04:12:54.228221+00:00
112
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```\ntype findDiagonalOrderDFS struct {\n\tx, y int\n}\n\nfunc findDiagonalOrder(nums [][]int) []int {\n\tconst cap = 1 << 13\n\tres := make([]int, 0, cap)\n\tqueue := []findDiagonalOrderDFS{{0, 0}}\n\tfor len(queue) > 0 {\n\t\tnode := queue[0]\n\t\tqueue = queue[1:]\n\t\tif node.x >= len(nums) || node.y >= len(nums[node.x]) {\n\t\t\tcontinue\n\t\t}\n\t\tres = append(res, nums[node.x][node.y])\n\t\tif node.y == 0 {\n\t\t\tqueue = append(queue, findDiagonalOrderDFS{node.x + 1, node.y})\n\t\t}\n\t\tqueue = append(queue, findDiagonalOrderDFS{node.x, node.y + 1})\n\t}\n\n\treturn res\n}\n```
2
0
['Go']
0
diagonal-traverse-ii
Traversal || Hashmap || Diagonal || LC Daily || Nov 22
traversal-hashmap-diagonal-lc-daily-nov-1iff6
Code\n\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n vector<int>res;\n map<int,vector<int>>mp;\n
kushagra_2k24
NORMAL
2023-11-22T04:11:37.380815+00:00
2023-11-22T04:11:37.380840+00:00
155
false
# Code\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n vector<int>res;\n map<int,vector<int>>mp;\n for(int i=0;i<nums.size();i++)\n {\n for(int j=0;j<nums[i].size();j++)\n mp[i+j].push_back(nums[i][j]);\n }\n for(auto it:mp)\n {\n reverse(it.second.begin(),it.second.end());\n for(auto itr:it.second)\n res.push_back(itr);\n }\n return res;\n }\n};\n```
2
0
['Array', 'Hash Table', 'Sorting', 'Heap (Priority Queue)', 'C++']
0
diagonal-traverse-ii
Very Easy C++ Solution || Sorting || 2-pass
very-easy-c-solution-sorting-2-pass-by-f-79o2
Intuition\nElements which are part of same diagonal have same {i+j} values where i and j are row and column indices. \n\n# Approach\nTraverse the whole nums arr
fenwick-tree
NORMAL
2023-11-22T03:45:58.073101+00:00
2023-11-22T03:45:58.073131+00:00
84
false
# Intuition\nElements which are part of same diagonal have same {i+j} values where i and j are row and column indices. \n\n# Approach\nTraverse the whole nums array and store every element\'s {i+j},i & j values and sort them in ascending order. If elements belong to same diagonal then the one having larger \'i\'(row number) should come first. To achieve this you can declare your own comparator.\n\n# Complexity\n- Time complexity:\nO(n*m) + O((n*m)*log(n*m))\n- Space complexity:\nO(nm)\n\n# Code\n```\nclass Solution {\npublic:\n static bool comp(const pair<int, pair<int, int>>& p1, const pair<int, pair<int, int>>& p2){\n if(p1.first != p2.first){\n return p1.first < p2.first;\n }else{\n return p1.second.first > p2.second.first;\n }\n\n }\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n\n vector<pair<int, pair<int, int>>> idx;\n for(int i=0; i<nums.size(); i++){\n for(int j=0; j<nums[i].size(); j++){\n idx.push_back({i+j, {i, j}});\n }\n }\n\n sort(idx.begin(), idx.end(), comp);\n\n vector<int> ans;\n for(auto it : idx){\n int x = it.second.first;\n int y = it.second.second;\n ans.push_back(nums[x][y]);\n }\n\n return ans;\n \n }\n};\n```
2
0
['C++']
1
diagonal-traverse-ii
C++ Magic
c-magic-by-rohan80_80-qlf6
Intuition \n Describe your first thoughts on how to solve this problem. \nBy obsering the positions of diagonal elements we get an pattern where\nsum of the pos
Rohan80_80
NORMAL
2023-11-22T03:01:11.353023+00:00
2023-11-22T03:01:11.353057+00:00
45
false
# Intuition \n<!-- Describe your first thoughts on how to solve this problem. -->\nBy obsering the positions of diagonal elements we get an pattern where\nsum of the positions i\'th index and j\'th index is same for given particular digonal .\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nApproch is very simple take and map of <int,vector<int>> where for particular digonal you push one by one diagonal elements but in solution they wan\'t ***reverse*** order of each digonal element then by using for each loop just reverse the all digonal elements .\nstore the answer in vector format and return the answer .\n\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```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n map<int,vector<int>>mp;\n for(int i=0;i<nums.size();i++){\n for(int j=0;j<nums[i].size();j++){\n mp[i+j].push_back(nums[i][j]);\n }\n }\n for(auto &it:mp){\n reverse(it.second.begin(),it.second.end());\n }\n vector<int>ans;\n \n for(auto it:mp){\n for(auto it2:it.second){\n ans.push_back(it2);\n }\n cout<<endl;\n }\n return ans;\n }\n};\n```
2
0
['C++']
1
diagonal-traverse-ii
Priority_Queue|| very simple || Unique || beats 80%
priority_queue-very-simple-unique-beats-qvuii
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
ASPII
NORMAL
2023-11-22T01:40:52.177166+00:00
2023-11-22T01:40:52.177182+00:00
29
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- total number of elements in matrix\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n\n priority_queue<\n std::pair<int, std::pair<int, int>>,\n std::vector<std::pair<int, std::pair<int, int>>>,\n std::greater<std::pair<int, std::pair<int, int>>>\n > pq;\n int i,j;\n for(i=0;i<nums.size();i++)\n {\n for(j=0;j<nums[i].size();j++)\n {\n \n pq.push({i+j,{j,nums[i][j]}});\n }\n }\n vector<int>ans;\n while(pq.size())\n {\n int p=pq.top().second.second;\n ans.push_back(p);\n pq.pop();\n }\n return ans;\n }\n};\n```
2
0
['Heap (Priority Queue)', 'C++']
0
diagonal-traverse-ii
[Java] Simple and intuitive - beats 95%
java-simple-and-intuitive-beats-95-by-w-1ya2g
Intuition\n Describe your first thoughts on how to solve this problem. \nWe need to break down the numbers into lists based on the diagonal they belong to. To d
w-s
NORMAL
2023-04-21T16:19:39.013334+00:00
2023-04-21T16:19:39.013378+00:00
578
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to break down the numbers into lists based on the diagonal they belong to. To do this we need to first find the number of diagonals and then put each number into the relevant diagonal. \n\nNumbers in the first list will start from the 1st diagonal, 2nd list the 2nd diagonal, and so on as you move down the list of lists.\n\nAs you move along each list, the diagonal at which the number belongs to is simply the starting diagonal + the index of the current element.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst, we need to find the number of diagonals in our output. This is simply the maximum value of the index + size of each list.\n\nThen, we need to add numbers into our individual diagonals/buckets. The bucket at which each number belongs to is the index of the list + the current index of the element within the list.\n\nOnce we have done that, we have our output as a list of diagonals. Since the order of each diagonal should be from bottom left to top right, the elements in our diagonal are stored in reversed order. We have to iterate over our buckets again and place them in the output in the correct order. \n\nWe can do this by simply adding to our output starting from the end of each bucket, and iterating backwards.\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```\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n\n //finding number of diagonals/buckets.\n int diagonals = 0;\n int arrSize = 0;\n for(int i=0; i<nums.size(); i++){\n diagonals = Math.max(i + nums.get(i).size(), diagonals);\n arrSize += nums.get(i).size();\n }\n\n //create a list of diagonals\n List<List<Integer>> buckets = new ArrayList<>();\n for(int i=0; i<diagonals; i++){\n buckets.add(new ArrayList<Integer>());\n }\n\n //adding numbers to relevant diagonals\n int bucketIndex = 0;\n for(List<Integer> ls : nums){\n int index = bucketIndex;\n for(int n : ls){\n buckets.get(index).add(n);\n index++;\n }\n bucketIndex++;\n }\n\n //putting numbers in output\n int[] output = new int[arrSize];\n int i = 0;\n for(List<Integer> ls : buckets){\n for(int j=ls.size()-1; j>= 0; j--){\n output[i] = ls.get(j);\n i++;\n }\n }\n return output;\n }\n}\n```
2
0
['Java']
1
diagonal-traverse-ii
scala oneliner
scala-oneliner-by-vititov-zil5
\n# Code\n\n// sort by coordinates sum\nobject Solution {\n def findDiagonalOrder: List[List[Int]] => Array[Int] =\n _.zipWithIndex.flatMap{case (l,i) => l.
vititov
NORMAL
2023-02-06T21:37:16.793818+00:00
2023-02-06T21:37:16.793851+00:00
32
false
\n# Code\n```\n// sort by coordinates sum\nobject Solution {\n def findDiagonalOrder: List[List[Int]] => Array[Int] =\n _.zipWithIndex.flatMap{case (l,i) => l.zipWithIndex.map{case (x,j) => (i+j,i,j,x)}}\n .sortWith{case (a,b) => (a._1 < b._1) || (a._1 == b._1) && (a._3 < b._3)}.map(_._4).toArray\n}\n```
2
0
['Sorting', 'Scala']
2
diagonal-traverse-ii
C++ | Hash Map | Most Simple Code | 70% Faster
c-hash-map-most-simple-code-70-faster-by-xpvp
Please Upvote :)\n\n\nclass Solution {\npublic:\n map<int,vector<int>> m;\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n int n=nums
ankit4601
NORMAL
2022-07-08T19:46:29.788092+00:00
2022-07-08T19:47:05.664677+00:00
288
false
Please Upvote :)\n\n```\nclass Solution {\npublic:\n map<int,vector<int>> m;\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n int n=nums.size();\n for(int i=nums.size()-1;i>=0;i--) // storing from bottom to top diagonally( i+j )\n {\n for(int j=0;j<nums[i].size();j++)\n {\n\t\t\t\t// same i+j value elements will lie on same diagonal ( Same as in N-Queens ) \n m[i+j].push_back(nums[i][j]);\n }\n }\n vector<int> res;\n for(auto x:m)\n {\n for(auto y:x.second)\n res.push_back(y);\n }\n return res;\n }\n};\n```
2
0
['C']
0
diagonal-traverse-ii
Easy Simple O(n) C++ Solution
easy-simple-on-c-solution-by-viv_shubham-ugta
\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n queue<vector<int>> q;\n q.push({0, 0});\n vec
viv_shubham
NORMAL
2022-05-02T18:29:57.299309+00:00
2022-05-02T18:29:57.299345+00:00
202
false
```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n queue<vector<int>> q;\n q.push({0, 0});\n vector<int> ans;\n while(!q.empty()){\n int row = q.front()[0], col = q.front()[1];\n q.pop();\n ans.push_back(nums[row][col]);\n if(row + 1 < nums.size() && col == 0)q.push({row+1, col});\n if(col + 1 < nums[row].size())q.push({row, col+1});\n }\n return ans;\n }\n};\n```
2
0
[]
1
diagonal-traverse-ii
Java | Clean & Easy to Understand | Priority Queue With Custom Sorting
java-clean-easy-to-understand-priority-q-rjl6
\n// Tuple to store sum, row and val for each element\nclass Pair{\n int sum;\n int row;\n int val;\n\n public Pair(int sum, int row, int val) {\n
thedeepanshumourya
NORMAL
2022-03-25T16:48:04.198603+00:00
2022-03-25T16:48:04.198654+00:00
305
false
```\n// Tuple to store sum, row and val for each element\nclass Pair{\n int sum;\n int row;\n int val;\n\n public Pair(int sum, int row, int val) {\n this.sum = sum;\n this.row = row;\n this.val = val;\n }\n}\n\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n\t\t/**\n\t\t* Priority Queue which will sort elements in increasing order of sum and \n\t\t* if sum is same then it will sort them in order of row number\n\t\t*/\n PriorityQueue<Pair> pq = new PriorityQueue<>((a,b)->{\n if(a.sum != b.sum) \n return a.sum-b.sum;\n \n return b.row-a.row;\n });\n \n int size = 0;\n \n for(int i = 0; i < nums.size(); i++) {\n size += nums.get(i).size();\n for(int j = 0; j < nums.get(i).size(); j++) {\n int sum = i+j;\n \n Pair pair = new Pair(sum, i, nums.get(i).get(j));\n \n pq.add(pair);\n }\n }\n \n int res[] = new int[size];\n int index = 0;\n \n\t\t/* We\'ll poll each element and store them in resultant array */\n while(!pq.isEmpty()) {\n res[index++] = pq.poll().val;\n }\n \n return res;\n }\n}\n```
2
0
['Sorting', 'Heap (Priority Queue)', 'Java']
2
diagonal-traverse-ii
Simple Python with deque
simple-python-with-deque-by-totoslg-sn3u
Time Complexity - O(N) runtime, O(N) space where N is the number of cells\n```\nclass Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[
totoslg
NORMAL
2022-01-29T23:09:14.307479+00:00
2022-01-29T23:09:14.307522+00:00
201
false
Time Complexity - O(N) runtime, O(N) space where N is the number of cells\n```\nclass Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n m, n = len(nums), len(nums[0])\n resDict = defaultdict(deque)\n maxVal = 0\n \n for r, lst in enumerate(nums):\n for c, val in enumerate(lst):\n maxVal = max(maxVal, r+c)\n resDict[r+c].appendleft(val)\n \n return [x for colLst in range(maxVal+1) for x in resDict[colLst]]
2
0
['Queue', 'Python']
2
diagonal-traverse-ii
[C++ ,BFS, Clear Explanation] Simple and Single Pass Solution
c-bfs-clear-explanation-simple-and-singl-blc2
Note: Here only matters is the Traversing idea. How to add an elements in Queue?\n1. If we are at the first column add element in the Queue below it,if exists.(
prajha
NORMAL
2021-08-28T09:47:45.305310+00:00
2021-09-14T08:51:51.779373+00:00
148
false
**Note:** Here only matters is the Traversing idea. How to add an elements in Queue?\n1. If we are at the first column add element in the Queue below it,if exists.(So that we won\'t add repeatedly same elements and hence preventing TLE).\n2. Add element at right (next column) in the queue,if exists.\n3. Hence we are traversing as required (Level-wise / Diagonally).\n**For any queries please do comment and please upvote if you liked this idea.**\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n vector<int>ans;\n int n=nums.size(); //# rows\n queue<pair<int,int>>q;\n q.push({0,0});\n while(!q.empty()){\n int sz=q.size();\n for(int z=0;z<sz;z++){ //Level order Traversal (BFS)\n int r=q.front().first;\n int c=q.front().second;\n q.pop();\n ans.push_back(nums[r][c]);\n if(r+1<n && c==0)q.push({r+1,c}); // if element is at the first column, add the new element below it.\n if(c+1<nums[r].size()) q.push({r,c+1});\n }\n }\n return ans;\n }\n};\n```
2
0
[]
2
diagonal-traverse-ii
Golang solution with image for explanation
golang-solution-with-image-for-explanati-rago
I think that the idea of this solution can be shown using an image:\n\n\n\n\ngo\nfunc findDiagonalOrder(nums [][]int) []int {\n arr := [][]int{}\n res :=
nathannaveen
NORMAL
2021-08-19T15:57:33.829780+00:00
2021-08-19T15:57:49.301944+00:00
93
false
I think that the idea of this solution can be shown using an image:\n\n![image](https://assets.leetcode.com/users/images/2182030d-56bf-459c-aa32-e6ef65cc38d5_1629388666.8130157.png)\n\n\n``` go\nfunc findDiagonalOrder(nums [][]int) []int {\n arr := [][]int{}\n res := []int{}\n \n for i := 0; i < len(nums); i++ {\n for j := 0; j < len(nums[i]); j++ {\n if len(arr) <= i + j {\n arr = append(arr, []int{})\n }\n arr[i + j] = append(arr[i + j][:0], append([]int{nums[i][j]}, arr[i + j][0:]...)...)\n }\n }\n \n for i := 0; i < len(arr); i++ {\n res = append(res, arr[i]...)\n }\n \n return res\n}\n```
2
0
['Go']
1
diagonal-traverse-ii
Easy java map soln.
easy-java-map-soln-by-harsh-singh-xc1a
\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n int count=0;\n for(int i=0;i<nums.size();i++){\n co
harsh-singh
NORMAL
2021-06-12T19:49:42.282291+00:00
2021-06-12T19:49:42.282336+00:00
105
false
```\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n int count=0;\n for(int i=0;i<nums.size();i++){\n count+=nums.get(i).size();\n }\n \n int ans[] = new int[count];\n TreeMap<Integer,List<Integer>> res = new TreeMap<>();\n for(int i=0;i<nums.size();i++){\n for(int j=0;j<nums.get(i).size();j++){\n int s = i+j;\n int e = nums.get(i).get(j);\n if(res.containsKey(s)){\n List<Integer> kk = res.get(s);\n kk.add(e);\n res.put(s,kk);\n } else {\n List<Integer> kk = new ArrayList<>();\n kk.add(e);\n res.put(s,kk);\n }\n }\n }\n \n int ind = 0;\n for(Map.Entry<Integer,List<Integer>> kk : res.entrySet()){\n List<Integer> oo = kk.getValue();\n for(int i=oo.size()-1;i>=0;i--){\n ans[ind++] = oo.get(i);\n }\n }\n return ans;\n }\n}\n```
2
1
[]
0
diagonal-traverse-ii
Simple C++ Solution (using level order traversal)
simple-c-solution-using-level-order-trav-o5d7
\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) \n {\n vector<vector<int> >dp=nums;\n vector<int>ans;\n
Four901
NORMAL
2021-06-02T18:03:44.251682+00:00
2021-06-02T18:03:44.251713+00:00
122
false
```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) \n {\n vector<vector<int> >dp=nums;\n vector<int>ans;\n queue< pair<int,int> >qq;\n qq.push(make_pair(0,0));\n dp[0][0]=-1;\n while(qq.size()>0)\n {\n int size=qq.size();\n for(int i=0;i<size;i++)\n { \n int x=qq.front().first;\n int y=qq.front().second;\n // cout<<x<<" "<<y<<endl;\n qq.pop();\n ans.push_back(nums[x][y]);\n if(x+1<nums.size())\n {\n if(y<nums[x+1].size())\n {\n if(dp[x+1][y]!=-1)\n {\n dp[x+1][y]=-1;\n qq.push(make_pair(x+1,y));\n }\n }\n }\n if(y+1<nums[x].size())\n {\n \n if(dp[x][y+1]!=-1)\n {\n dp[x][y+1]=-1;\n qq.push(make_pair(x,y+1));\n }\n }\n }\n }\n return ans;\n }\n};\n```
2
0
[]
0
diagonal-traverse-ii
Java || Matrix + List || beats 94% || 17ms || T.C - O(R*C) S.C - O(R*C)
java-matrix-list-beats-94-17ms-tc-orc-sc-qzei
\n // O(nums.lengthnums[i].length) O(nums.lengthnums[i].length)\n\t// HashMap/List Approach\n\tpublic int[] findDiagonalOrder(List> nums) {\n\n\t\tint idx =
LegendaryCoder
NORMAL
2021-05-01T11:35:54.222873+00:00
2021-05-01T11:35:54.222912+00:00
93
false
\n // O(nums.length*nums[i].length) O(nums.length*nums[i].length)\n\t// HashMap/List Approach\n\tpublic int[] findDiagonalOrder(List<List<Integer>> nums) {\n\n\t\tint idx = 0, size = 0, max = 0, m = nums.size();\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tsize += nums.get(i).size();\n\t\t\tif (i + size - 1 > max)\n\t\t\t\tmax = i + size - 1;\n\t\t}\n\n\t\tint[] ans = new int[size];\n\n\t\tList<Integer>[] map = new ArrayList[max + 1];\n\t\tfor (int i = 0; i <= max; i++)\n\t\t\tmap[i] = new ArrayList<>();\n\n\t\tfor (int i = m - 1; i >= 0; i--) {\n\t\t\tList<Integer> num = nums.get(i);\n\t\t\tint len = num.size();\n\t\t\tfor (int j = len - 1; j >= 0; j--) {\n\t\t\t\tint sum = i + j;\n\t\t\t\tmap[sum].add(num.get(j));\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = 0; i <= max; i++) {\n\t\t\tList<Integer> num = map[i];\n\t\t\tfor (int temp : num)\n\t\t\t\tans[idx++] = temp;\n\t\t}\n\n\t\treturn ans;\n\t}\n
2
1
[]
0
diagonal-traverse-ii
Sorting based on Diagonal Positions
sorting-based-on-diagonal-positions-by-d-a0dx
Just Sort Value items based on sum of row and column index and row positions.\nthen just return simple value array..\n\n\npublic int[] findDiagonalOrder(List<Li
darkrwe
NORMAL
2021-01-01T15:17:10.626682+00:00
2021-01-01T15:19:01.656460+00:00
216
false
Just Sort Value items based on sum of row and column index and row positions.\nthen just return simple value array..\n\n```\npublic int[] findDiagonalOrder(List<List<Integer>> nums) {\n \n int totalRowNum = nums.size();\n List<Value> values = new ArrayList<Value>();\n\n for(int i = 0; i < totalRowNum; i++) {\n if(nums.get(i).size() != 0){\n for(int j = 0; j < nums.get(i).size(); j++)\n values.add(new Value(nums.get(i).get(j), i , j));\n }\n }\n Collections.sort(values);\n int[] result = new int[values.size()];\n \n for(int i = 0 ; i < values.size(); i++)\n result[i] = values.get(i).getValue();\n \n return result;\n }\n \n public class Value implements Comparable<Value>{\n int val;\n int column;\n int row;\n int sum;\n \n public Value(int val, int row, int column){\n this.sum = column + row;\n this.val = val;\n this.row = row;\n this.column = column;\n }\n \n public int getValue(){\n return this.val;\n }\n \n public int getSum(){\n return this.sum;\n }\n \n @Override\n public int compareTo(Value v) {\n if(this.sum < v.sum)\n return -1;\n else if(this.sum > v.sum)\n return 1;\n else {\n if(this.row > v.row)\n return -1;\n else if(this.row < v.row)\n return 1;\n else\n return 0;\n }\n }\n }\n```
2
0
['Sorting', 'Java']
0
diagonal-traverse-ii
[Java] | Using Coordinate Jeo + Map | With Complete Walkthrough & Pictures
java-using-coordinate-jeo-map-with-compl-ehnq
\n\nThought Process\n\t\n\tIf given matrix is of size 4 x 4.\n\tThen i want all the points that are lies\n\twithin 4 x 4 cartesian plane.\n\t\n\tY axis\n\t\n\t|
_LearnToCode_
NORMAL
2020-12-02T15:14:47.045853+00:00
2020-12-02T15:20:41.142319+00:00
106
false
![image](https://assets.leetcode.com/users/images/e68bbaab-99c7-414d-871a-ff2405cb90bb_1606921612.58485.png)\n\n**Thought Process**\n\t\n\tIf given matrix is of size 4 x 4.\n\tThen i want all the points that are lies\n\twithin 4 x 4 cartesian plane.\n\t\n\tY axis\n\t\n\t|_ 4\n\t|_ 3\n\t|_ 2\n\t|_ 1\n\t|__|__|__|__|___ X axis\n 0 1 2 3 4\t\n\n\t**You can leave all the points of type (4, y) & (0, 4), \n\tthese points are not part of 4 x 4 matrix.**\n\t\n NOTE: If we look at all the diagonals in the matrix, we\'ll find that these diagonals are\n\t nothing but straight lines.\n\t \n Each straight line -> is a valid diagonal\n\t \n\t Of type -> y = mx + C or y = mx - C where m is always 1. \n\t and C is the constant which is always >= 0.\n\t \n\t C -> intersecting point on y - axis by a line.\n\t \n\t We can calculate C as:\n\t\t\t\t(y - x) for a line of type y = x + C\n\t\t\t\t-(y - x) for a line of type y = x - C\n\t \n\t Those points that are belongs to the same diagonal must satisfy\n\t the line corresponding to that diagonal.\n\t \n\t Here for each point -> we\'ve corresponding element in matrix.\n\t \n**Q & A**\n\t\n\tQ : How did we know that which point is belongs to which diagonal?\n\t\n\tA : The important point is needs to consider that if we closely\n\t\tlook at the above lines, we found a unique point about them.\n\t\t\n\t\tQ.1 What is that point?\n\t\tA.1 Yes, you gussed right. The value of C is unique for each diagonal/line.\n\t\t\n\tNOTE: Remember C is going to be our key in map.\n\t\t \n\t\t If two or more points have the same value of C that means\n\t\t those points are belongs to the same diagonal and We\'ve to put\n\t\t corresponding elements(in matrix) to those points in the\n\t\t diagonal associated with C.\n\t\t \n\t-----------------------------------------------------------------------\n\t\n\tOur map will internally look like:\n\t\t\t\n\t\t\tkey ---> diagonal\n\t\t\tC ---> [](a list representing a diagonal for each C)\n\t\n\tFor example:\n\t-----------\n\t\tmat: [\n\t\t\t\t[1,2,3],\n\t\t\t\t[4,5,6],\n\t\t\t\t[7,8,9]\n\t\t\t ]\n\t\t\t \n\t\tAfter processing all the points & corresponding elements in matrix.\n\t\tour map content is:\n\t\t\n\t\tC(key) diagonal(list)\n\t\t\n\t\t 2 ----> [1]\n\t\t 1 ----> [4,2]\n\t\t 0 ----> [7,5,3]\n\t\t -1 ----> [8,6]\n\t\t -2 ----> [9]\n\t\t\n\t\tNOTE:\n\t\t----\n\t\tHere keys are stored in descending order of their values. -> In our map.\n\t\tbecause we want topmost diagonal first and then second and so on.\n\t\t\n\t\tFor the above purpose i used TreeMap in Java by passing Custom Comparator.\n\t\tyou can use map<int, vector<int>, greater<int>> in C++.\n\t\t--------------------------------------------------------------------------\n\t\t\n\t\tGrab the all the lists associated with each key and return them as answer.\n```\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> mat) {\n List<List<Integer>> diags = new ArrayList<>();\n\t\tint N = mat.size();\n\t\t\n\t\t//Sorting will be performed based on dereasing order or keys\n\t\tMap<Integer, List<Integer>> tm = new TreeMap<>((a, b) -> b - a);\n\t\t\n\t\tint lst_row_index = N - 1;\n int size = 0;\n \n //Here i\'m traversing entire matrix from bottom top top\n //first last row is accessed -> from left to right and then second last row and so on.\n //as i\'ve discussed in my thought process.\n\t\tfor(int i = 0; i < N; i += 1) {\n\t\t\tfor(int j = 0; j < mat.get(lst_row_index - i).size(); j += 1) {\n\t\t\t\t//Calculating C for lines either of type -> y = x + C or y = x - C\n\t\t\t\t//This is going to be -> key in map -> for a diagonal\n\t\t\t\tint C = (i - j);\n\t\t\t\tList<Integer> diag = tm.getOrDefault(C, new ArrayList<>());\n\t\t\t\tdiag.add(mat.get(lst_row_index - i).get(j));\n\t\t\t\ttm.put(C, diag);\n size += 1;\n\t\t\t}\n\t\t}\n \n\t\tint[] result = new int[size];\n int i = 0;\n\t\tfor(Integer key : tm.keySet()) {\n\t\t\tfor(Integer ele : tm.get(key)) {\n result[i] = ele;\n i += 1;\n }\n\t\t}\n\t\t\n\t\treturn result;\n }\n}\n```\n\n**I hope, whatever i\'ve discussed above was helpful, and you enjoyed it.**\n\t\t\n**Happy Coding \u263A**\n
2
0
['Sorting']
0
diagonal-traverse-ii
JAVA | BFS | 92% |
java-bfs-92-by-idbasketball08-e2n8
```\nclass Solution {\n public int[] findDiagonalOrder(List> nums) {\n //strategy: BFS\n //find length of our array\n int sum = 0;\n
idbasketball08
NORMAL
2020-11-21T03:48:42.687570+00:00
2020-11-21T03:48:42.687599+00:00
129
false
```\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n //strategy: BFS\n //find length of our array\n int sum = 0;\n for (List<Integer> num : nums) {\n sum += num.size();\n }\n int[] answer = new int[sum];\n int index = 0;\n Queue<int[]> q = new LinkedList<>();\n //add starting node\n q.add(new int[]{0, 0});\n while (!q.isEmpty()) {\n //pull out level by level\n int size = q.size();\n while (--size >= 0) {\n int[] curr = q.poll();\n int x = curr[0], y = curr[1];\n //add current\n answer[index++] = (nums.get(x).get(y));\n //can only move down if the cell is in the first col\n //make sure it is in bounds\n if (y == 0 && x + 1 < nums.size()) {\n q.add(new int[]{x + 1, y});\n }\n //every cell can move to the right\n //make sure it is in bounds\n if (y + 1 < nums.get(x).size()) {\n q.add(new int[]{x, y + 1});\n }\n }\n }\n return answer;\n }\n}
2
1
[]
1
diagonal-traverse-ii
[C++] 9lines
c-9lines-by-kesnero-6e57
\nbool cmp(const pair<int, int> &a, const pair<int, int> &b) {\n if (a.first+a.second != b.first+b.second)\n return a.first+a.second < b.first+b.secon
kesnero
NORMAL
2020-08-11T04:28:14.930789+00:00
2020-08-11T04:28:14.930839+00:00
125
false
```\nbool cmp(const pair<int, int> &a, const pair<int, int> &b) {\n if (a.first+a.second != b.first+b.second)\n return a.first+a.second < b.first+b.second;\n if (a.first != b.first)\n return a.first > b.first;\n return a.second < b.second;\n}\n\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n vector<pair<int, int>> seq;\n vector<int> ans;\n for (int i = 0; i < nums.size(); i++)\n for (int j = 0; j < nums[i].size(); j++)\n seq.push_back(make_pair(i, j));\n sort(seq.begin(), seq.end(), cmp);\n for (auto s : seq)\n ans.push_back(nums[s.first][s.second]);\n return ans;\n }\n};\n```
2
0
[]
0
diagonal-traverse-ii
row + col buckets
row-col-buckets-by-ffbit-hbwf
\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n List<List<Integer>> diagonals = new ArrayList<>();\n int coun
ffbit
NORMAL
2020-06-26T10:30:23.147296+00:00
2020-06-26T10:30:23.147338+00:00
162
false
```\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n List<List<Integer>> diagonals = new ArrayList<>();\n int count = 0;\n for (int row = 0; row < nums.size(); row++) {\n for (int col = 0; col < nums.get(row).size(); col++) {\n int diagonalIdx = row + col;\n if (diagonals.size() == diagonalIdx) {\n diagonals.add(new ArrayList<>());\n }\n diagonals.get(diagonalIdx).add(nums.get(row).get(col));\n count++;\n }\n }\n \n int[] order = new int[count];\n int writeIdx = 0;\n for (List<Integer> diagonal : diagonals) {\n Collections.reverse(diagonal);\n for (int v : diagonal) {\n order[writeIdx++] = v;\n }\n }\n return order;\n }\n}\n```
2
0
['Java']
0
diagonal-traverse-ii
Simple Java solution with Detail Explanation O( rows*cols)
simple-java-solution-with-detail-explana-pv8r
\n \n /**\n 1. Create the Map key as row+column as sum and stack as value( because we need to show from last to first element), since all elements be
user5958h
NORMAL
2020-06-17T14:41:15.350326+00:00
2020-06-17T20:19:31.139285+00:00
269
false
```\n \n /**\n 1. Create the Map key as row+column as sum and stack as value( because we need to show from last to first element), since all elements belong to same diagonal will have same sum .\n 2. Since the Matrix is inconsistent , then first find the maximum ( or last diagonal element) which we captured as part of map. So get the maximum key of a map.\n 3. Then simply iterate the loop from 0 to maximum key of Map and pop the result from stack in out put list.\n \n **/\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n \n int rows = nums.size();\n Map<Integer,Stack<Integer>> map = new HashMap<>();\n \n //1. Create the Map key as row+column as sum and stack as value( because we need to show from lat to first element), since all elemnst belongs to same diagonal will have same sum .\n for( int row =0; row < rows ; row++){\n List<Integer> cols = nums.get(row);\n for( int col=0; col<cols.size() ; col++){\n if(!map.containsKey(row+col)){\n map.put(row+col,new Stack<>());\n }\n map.get(row+col).push(cols.get(col));\n }\n }\n \n int max = Integer.MIN_VALUE;\n \n //2. Since the Matrix is inconsistent , then first find the maximum ( or last diagonal element) which we captured as part of map. So get the maximum key of a map.\n for(Integer dt : map.keySet()){\n max = Math.max(max,dt);\n }\n \n \n List<Integer> retValue = new ArrayList<>();\n //3. Then simply iterate the loop from 0 to maximum key of Map and pop the result from stack in out put list.\n for( int diag=0; diag <=max ; diag++){\n Stack<Integer> st = map.get(diag) ;\n while(!st.isEmpty()){\n retValue.add(st.pop()); \n }\n }\n int[] retArr = new int[retValue.size()];\n for( int i=0; i<retValue.size(); i++ ){\n retArr[i] = retValue.get(i);\n }\n return retArr;\n \n }\n```
2
0
['Java']
1
reveal-cards-in-increasing-order
Java Queue Simulation, Step by Step Explanation
java-queue-simulation-step-by-step-expla-s68t
Simulate the process with a queue.\n1. Sort the deck, it is actually the "final sequence" we want to get according to the question.\n2. Then put it back to the
caraxin
NORMAL
2018-12-02T04:10:13.858292+00:00
2018-12-02T04:10:13.858342+00:00
22,605
false
Simulate the process with a queue.\n1. Sort the deck, it is actually the "final sequence" we want to get according to the question.\n2. Then put it back to the result array, we just need to deal with the index now!\n3. Simulate the process with a queue (initialized with 0,1,2...(n-1)), now how do we pick the card?\n4. We first pick the index at the top: ```res[q.poll()]=deck[i]```\n5. Then we put the next index to the bottom: ```q.add(q.poll());```\n6. Repeat it n times, and you will have the result array!\n\n**update**\nLet\'s walk through the example:\nInput: ```[17,13,11,2,3,5,7]```\nOutput: ```[2,13,3,11,5,17,7]```\n1. Sort the deck: ```[2,3,5,7,11,13,17]```, this is the increasing order we want to generate\n2. Initialize the queue: ```[0,1,2,3,4,5,6]```, this is the index of the result array\n3. **The first card** we pick is ```res[0]```, observe the deck, it should be ```deck[0]==2```, so assign ```res[0]=2```\n4. Then we put ```res[1]``` to the bottom, so we re-insert ```1``` to the queue\n5. **The second card** we pick is ```res[2]```, which should be ```deck[1]==3```, so assign ```res[2]=3```\n6. Then we re-insert ```3``` to the queue\n7. Each time we assign 1 value to the res, so we repeat this n times.\n\nHope this helps.\n```\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n int n= deck.length;\n Arrays.sort(deck);\n Queue<Integer> q= new LinkedList<>();\n for (int i=0; i<n; i++) q.add(i);\n int[] res= new int[n];\n for (int i=0; i<n; i++){\n res[q.poll()]=deck[i];\n q.add(q.poll());\n }\n return res;\n }\n}\n```\nHappy Coding!
353
7
[]
32
reveal-cards-in-increasing-order
[Java/C++/Python] Simulate the Reversed Process
javacpython-simulate-the-reversed-proces-vt13
We simulate the reversed process.\nInitial an empty list or deque or queue,\neach time rotate the last element to the first,\nand append a the next biggest numb
lee215
NORMAL
2018-12-02T04:05:58.121137+00:00
2018-12-02T04:05:58.121180+00:00
22,161
false
We simulate the reversed process.\nInitial an empty list or deque or queue,\neach time rotate the last element to the first,\nand append a the next biggest number to the left.\n\nTime complexity:\n`O(NlogN)` to sort,\n`O(N)` to construct using deque or queue.\n\n\n**Java, using queue**\n```\n public int[] deckRevealedIncreasing(int[] deck) {\n int n = deck.length;\n Arrays.sort(deck);\n Queue<Integer> q = new LinkedList<>();\n for (int i = n - 1; i >= 0; --i) {\n if (q.size() > 0) q.add(q.poll());\n q.add(deck[i]);\n }\n int[] res = new int[n];\n for (int i = n - 1; i >= 0; --i) {\n res[i] = q.poll();\n }\n return res;\n }\n```\n\n**C++, using deque**\n```\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.rbegin(), deck.rend());\n deque<int> d;\n d.push_back(deck[0]);\n for (int i = 1; i < deck.size(); i++) {\n d.push_front(d.back());\n d.pop_back();\n d.push_front(deck[i]);\n }\n vector<int> res(d.begin(), d.end());\n return res;\n }\n```\n\n**Python, using list, `O(N^2)`:**\n```\n def deckRevealedIncreasing(self, deck):\n d = []\n for x in sorted(deck)[::-1]:\n d = [x] + d[-1:] + d[:-1]\n return d\n```\n\n**Python, using deque:**\n```\n def deckRevealedIncreasing(self, deck):\n d = collections.deque()\n for x in sorted(deck)[::-1]:\n d.rotate()\n d.appendleft(x)\n return list(d)\n```\n
223
7
[]
23
reveal-cards-in-increasing-order
💯Faster✅💯 Lesser✅Detailed Explaination🎯Sorting🔥Deque🧠Step-by-Step Explaination✅Python🐍Java🍵C+
faster-lesserdetailed-explainationsortin-9o3l
\uD83D\uDE80 Hi, I\'m Mohammed Raziullah Ansari, and I\'m excited to share solution to this question with detailed explanation:\n\n# \uD83C\uDFAFProblem Explain
Mohammed_Raziullah_Ansari
NORMAL
2024-04-10T03:03:31.179794+00:00
2024-04-10T04:37:19.177030+00:00
30,177
false
# \uD83D\uDE80 Hi, I\'m [Mohammed Raziullah Ansari](https://leetcode.com/Mohammed_Raziullah_Ansari/), and I\'m excited to share solution to this question with detailed explanation:\n\n# \uD83C\uDFAFProblem Explaination: \n- We have an array deck representing a deck of cards.\n- We need to simulate the process of revealing cards in increasing order after a certain shuffling of the deck.\n# \uD83E\uDDE0Thinking Behind the Solution:\n- Sorting the deck first helps us start with the smallest card.\n- Using a deque helps in maintaining the positions (indices) in the result array, ensuring that we place the cards in the correct order for revealing.\n- The simulation process mimics the process of revealing the cards from the shuffled deck in the desired order.\n# \u2705Approach:\n**Sort the Deck:**\n- Begin by sorting the deck in ascending order. This will help us to start with the smallest card.\n\n**Simulate the Reveal Process:**\n\n- Create a result array of the same size as deck to store the revealed cards in the desired order.\n- Use a deque (double-ended queue) to keep track of the indices of the result array. This deque will help in maintaining the order of the cards during the simulation.\n\n**Simulation Process:**\n\n- Start by placing the smallest card (after sorting) at the beginning of the result array (index 0).\n- For each card in the sorted deck:\n - Remove the first index from the deque and assign the current card to this index in the result array.\n - Check if there deque is empty, if not:\n - Move the index to the end of the deque.\n\n**Final Result:**\n\n- After processing all cards, the result array will contain the deck in the required order for revealing the cards in increasing order.\n\n# Let\'s walkthrough\uD83D\uDEB6\uD83C\uDFFB\u200D\u2642\uFE0F the implementation process with an example for better understanding\uD83C\uDFAF:\n\nLet\'s use the input `[17, 13, 11, 2, 3, 5, 7]` and go through each step of the simulation to reveal the cards in increasing order.\n\n### Input:\nDeck: `[17, 13, 11, 2, 3, 5, 7]`\n\n### Step-by-Step Simulation:\n1. **Sort the Deck**:\n - Sorted Deck: `[2, 3, 5, 7, 11, 13, 17]`\n\n2. **Initialize Variables**:\n - `deck`: `[2, 3, 5, 7, 11, 13, 17]`\n - `n` (size of deck): `7`\n - `result`: `[0, 0, 0, 0, 0, 0, 0]` (initialized with zeros)\n - `indices`: `deque([0, 1, 2, 3, 4, 5, 6])`\n\n### Simulation Process:\n\n#### 1st Card (`2`):\n- `card`: `2`\n- `idx` (popped from `indices`): `0`\n- `result` after assigning `2` at `idx`: `[2, 0, 0, 0, 0, 0, 0]`\n- `indices` after moving `next index: 1` to the end: `deque([2, 3, 4, 5, 6, 1])`\n\n#### 2nd Card (`3`):\n- `card`: `3`\n- `idx` (popped from `indices`): `2`\n- `result` after assigning `3` at `idx`: `[2, 0, 3, 0, 0, 0, 0]`\n- `indices` after moving `next index: 3` to the end: `deque([4, 5, 6, 1, 3])`\n\n#### 3rd Card (`5`):\n- `card`: `5`\n- `idx` (popped from `indices`): `4`\n- `result` after assigning `5` at `idx`: `[2, 0, 3, 0, 5, 0, 0]`\n- `indices` after moving `next index: 5` to the end: `deque([6, 1, 3, 5])`\n\n#### 4th Card (`7`):\n- `card`: `7`\n- `idx` (popped from `indices`): `6`\n- `result` after assigning `7` at `idx`: `[2, 0, 3, 0, 5, 0, 7]`\n- `indices` after moving `3` to the end: `deque([3, 5, 1])`\n\n#### 5th Card (`11`):\n- `card`: `11`\n- `idx` (popped from `indices`): `3`\n- `result` after assigning `11` at `idx`: `[2, 0, 3, 11, 5, 0, 7]`\n- `indices` after moving `4` to the end: `deque([1, 5])`\n\n#### 6th Card (`13`):\n- `card`: `13`\n- `idx` (popped from `indices`): `1`\n- `result` after assigning `13` at `idx`: `[2, 13, 3, 11, 5, 0, 7]`\n- `indices` after moving `5` to the end: `deque([5])`\n\n#### 7th Card (`17`):\n- `card`: `17`\n- `idx` (popped from `indices`): `6`\n- `result` after assigning `17` at `idx`: `[2, 13, 3, 11, 5, 17, 7]`\n- `indices` after moving `6` to the end: `deque([])`\n\n### Final Result:\nThe `result` array after simulating the process will be `[2, 13, 3, 11, 5, 17, 7]`, which represents the deck of cards revealed in increasing order.\n\n# Code:\n```Python []\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n # Sort the deck in increasing order\n deck.sort()\n \n n = len(deck)\n result = [0] * n\n indices = deque(range(n))\n \n for card in deck:\n idx = indices.popleft() # Get the next available index\n result[idx] = card # Place the card in the result array\n if indices: # If there are remaining indices in the deque\n indices.append(indices.popleft()) # Move the used index to the end of deque\n \n return result\n```\n```Java []\nimport java.util.*;\n\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck); // Sort the deck in increasing order\n \n int n = deck.length;\n int[] result = new int[n];\n Deque<Integer> indices = new LinkedList<>();\n \n for (int i = 0; i < n; i++) {\n indices.add(i); // Initialize deque with indices 0, 1, 2, ..., n-1\n }\n \n for (int card : deck) {\n int idx = indices.poll(); // Get the next available index\n result[idx] = card; // Place the card in the result array\n if (!indices.isEmpty()) {\n indices.add(indices.poll()); // Move the used index to the end of deque\n }\n }\n \n return result;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.begin(), deck.end()); // Sort the deck in increasing order\n \n int n = deck.size();\n vector<int> result(n);\n deque<int> indices;\n \n for (int i = 0; i < n; i++) {\n indices.push_back(i); // Initialize deque with indices 0, 1, 2, ..., n-1\n }\n \n for (int card : deck) {\n int idx = indices.front(); // Get the next available index\n indices.pop_front(); // Remove the index from the front\n result[idx] = card; // Place the card in the result array\n if (!indices.empty()) {\n indices.push_back(indices.front()); // Move the used index to the end of deque\n indices.pop_front(); // Remove the index from the front\n }\n }\n \n return result;\n }\n};\n\n```\n\n\n\n\n\n\n\n\n\n
210
3
['Array', 'Queue', 'Sorting', 'Simulation', 'C++', 'Java', 'Python3']
42
reveal-cards-in-increasing-order
C++ with picture, skip over empty spaces
c-with-picture-skip-over-empty-spaces-by-3mug
We sort the input array and initialize the result array with zeros (empty spaces). Then we insert sorted numbers into the second available empty space, skipping
votrubac
NORMAL
2018-12-04T08:00:30.428842+00:00
2018-12-04T08:00:30.428907+00:00
11,351
false
We sort the input array and initialize the result array with zeros (empty spaces). Then we insert sorted numbers into the second available empty space, skipping the first available empty space. \n\nAfter we reach the end of the result array, we continue looking for empty spaces from the beginning. The picture below demonstrates each "swipe" of the results array for input numbers [1..15]. Empty spaces are yellow, newly inserted numbers are highlighted.\n![image](https://assets.leetcode.com/users/votrubac/image_1543911256.png)\nNote that for the very last number, we skip the last empty space (position 14) twice. \n```\nvector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(begin(deck), end(deck));\n vector<int> res(deck.size(), 0);\n res[0] = deck[0];\n for (auto i = 1, p = 0; i < deck.size(); ++i) {\n for (auto j = 0; j < 2; p %= res.size(), j += (res[p] == 0 ? 1 : 0)) ++p;\n res[p] = deck[i];\n }\n return res;\n}\n```\nAnother way to look at this is to have a list of positions ```l = [0, 1, ... n - 1]```. We skip the first position and take (remove) the second one. This is the position of the next element from ```deck```. We then repeat the same until we have no more positions left. The solution below demonstrates this. The second solution should be a bit faster since we go through all positions ```2 * n```, where in the first solution it\'s ```n log n``` (we scan through the entire array ```log n``` times).\n```\nvector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(begin(deck), end(deck));\n list<int> l(deck.size());\n iota(begin(l), end(l), 0); \n vector<int> res(deck.size());\n auto lp = l.begin();\n for (int i = 0, skip = 0; !l.empty(); skip = !skip) {\n if (lp == l.end()) lp = l.begin();\n if (skip) ++lp;\n else {\n res[*lp] = deck[i++];\n l.erase(lp++);\n }\n }\n return res;\n}\n```
153
3
[]
29
reveal-cards-in-increasing-order
Java solution without queue
java-solution-without-queue-by-weibiny-k0x5
sort the inputed deck in ascending order.\n\ndeck = [17,13,11,2,3,5,7] => [2,3,5,7,11,13,17]\n\n2. fill the empty slot of array to be returned by the following
weibiny
NORMAL
2020-02-10T05:33:10.034472+00:00
2020-02-10T05:57:34.389708+00:00
2,397
false
1. sort the inputed deck in ascending order.\n```\ndeck = [17,13,11,2,3,5,7] => [2,3,5,7,11,13,17]\n```\n2. fill the empty slot of array to be returned by the following way: fill and skip the next empty slot alternatively.\n```\n[fill, skip, fill, skip, fill, skip, fill]\n[2, _, 3, _, 5, _, 7]\nThe last status is \'fill\', next status should be \'skip\'\n skip, fill, skip \n[2, _, 3, 11, 5, _, 7]\nThe last status is \'skip\', so the next status should be \'fill\'\n\t fill, skip \n[2, 13, 3, 11, 5, _, 7]\nThe last status is \'skip\', so the next status should be \'fill\'\n fill\n[2, 13, 3, 11, 5, 17, 7]\n```\n\n```\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck);\n int[] res = new int[deck.length];\n boolean[] filled = new boolean[deck.length];\n boolean skip = false;\n int i = 0, j = 0;\n while(i < deck.length) {\n if(filled[j]) {\n j = (j + 1) % deck.length;\n continue;\n }\n\n if(skip) {\n skip = false;\n } else {\n res[j] = deck[i++];\n filled[j] = true;\n skip = true;\n }\n j = (j + 1) % deck.length;\n }\n\n return res;\n }\n}\n```
59
0
[]
10
reveal-cards-in-increasing-order
C++ 80% with Actual Explanation and Workout...
c-80-with-actual-explanation-and-workout-rwhm
Time Complexity is O(nLogn). Not the fastest but it\'s at least simple (Relatively)..\n\nIntuition:\nWhat if.... I just build the deck from the back to the fron
zachaccino
NORMAL
2019-07-23T11:27:57.842383+00:00
2019-07-23T11:28:35.757363+00:00
4,784
false
Time Complexity is O(nLogn). Not the fastest but it\'s at least simple (Relatively)..\n\nIntuition:\nWhat if.... I just build the deck from the back to the front.... so we can reverse the steps that were involved to reveal the card in increasing order. \n\nAlgorithm Description:\n1. Sort the deck in increasing order. \n\t[17,13,11,2,3,5,7] then become [2,3,5,7,11,13,17]\n\n2. Create a DEQUE data structure so we can efficiently push to the front and pop at the back.\n\n3. To setup the while loop. We need to pop the largest number from deck and insert it to the beginning of the deque before looping. So your memory should looks like below.\n\tDECK: [2,3,5,7,11,13]\n\tDEQUE: [17]\n\n4. In each iteration\n\t(3.1)Store the last element in DEQUE\n\t(3.2)Pop the last element in DEQUE\n\t(3.3)Push the stored element to the FRONT of DEQUE\n\t(3.4)Push the last element from DECK to the FRONT of DEQUE\n\t(3.5)Pop the last element from DECK.\n\t\n\tInitially:\n\t\tDECK: [2,3,5,7,11,13]\n\t\tDEQUE: [17]\n\t\t\n\tAfter 3.1 and 3.2:\n\t\tDECK: [2,3,5,7,11,13]\n\t\tDEQUE: []\n\t\tSTORED: 17\n\t\t\n\tAfter 3.3, 3.4 and 3.5:\n\t\tDECK: [2,3,5,7,11]\n\t\tDEQUE: [13, 17]\n\t\tSTORED: \n\t\t\n5. Repeat Step 4 until no more numbers in the deck.\n\n\tAfter First Iteration...\n\t\tDECK: [2,3,5,7,11]\n\t\tDEQUE: [13, 17]\n\t\n\tAfter Second Iteration...\n\t\tDECK: [2,3,5,7]\n\t\tDEQUE: [11,17,13]\n\t\n\tAfter Third Iteration...\n\t\tDECK: [2,3,5]\n\t\tDEQUE: [7,13,11,17]\n\t\n\tAfter Forth Iteration...\n\t\tDECK: [2,3]\n\t\tDEQUE: [5,17,7,13,11]\n\t\n\tAfter Fifth Iteration...\n\t\tDECK: [2]\n\t\tDEQUE: [3,11,5,17,7,13]\n\t\n\tAfter Sixth Iteration...\n\t\tDECK: []\n\t\tDEQUE: [2,13,3,11,5,17,7]\n\t\t\n\tThe End... No more numbers in the deck.\n\t\n\t\t\n\n\n\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n // Sort by increasing order.\n sort(deck.begin(), deck.end());\n \n // Return the ans if there are max 2 elements since it\'s already sorted.\n if (deck.size() <= 2)\n {\n return deck;\n }\n \n // For more than 2 elements.\n deque<int> ans;\n ans.push_front(deck.back());\n deck.pop_back();\n \n while (!deck.empty())\n {\n int temp = ans.back();\n ans.pop_back();\n ans.push_front(temp);\n ans.push_front(deck.back());\n deck.pop_back();\n }\n\n return vector<int>(ans.begin(), ans.end());\n }\n};\n```
55
2
['C']
8
reveal-cards-in-increasing-order
Beats 94% 🔥|| Easy Approach ✅ Using Deque🚀with Explanation🔥
beats-94-easy-approach-using-dequewith-e-zavb
Question:\nSo the question says i will do a certain operation while i am picking the elements from the array and when the operations are over the cards in my ha
21eca01
NORMAL
2024-04-10T01:05:23.265014+00:00
2024-04-10T04:04:36.972006+00:00
14,161
false
**Question:\nSo the question says i will do a certain operation while i am picking the elements from the array and when the operations are over the cards in my hand should be of sorted order.**\n\n**the pattern:\n1.Take the top card of the deck, reveal it, and take it out of the deck.**\n\n**2.If there are still cards in the deck then put the next top card of the deck at the bottom of the deck.**\n\n**3.Repeat step 1.**\n\n**so how can we approach this we can either go recursivey to find the soln. or can make the soln ourselves from base.**\n\n\n## Approach 1: (Using Dequeue)\n**let us take one example first to better understand the pattern.\nExample 1:**\n\n**Input: deck = [17,13,11,2,3,5,7]\nOutput: [2,13,3,11,5,17,7]\nExplanation: \nWe get the deck in the order [17,13,11,2,3,5,7] (this order does not matter), and reorder it.\nAfter reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.\n1.Take 2, and move 13 to the bottom. The deck is now [3,11,5,17,7,13].2.Take 3, and move 11 to the bottom. The deck is now [5,17,7,13,11].\n3.Take 5, and move 17 to the bottom. The deck is now [7,13,11,17].\n4.Take 7, and move 13 to the bottom. The deck is now [11,17,13].\n5.Take 11, and move 17 to the bottom. The deck is now [13,17].\n6.Take 13, and move 17 to the bottom. The deck is now [17].\n7.Take 17. as there are no elements left break the loop.**\n\n**Consider building the array and analyzing from below you can see the gist of the soln:**\n\n**ex. on step 4. we can see that before 11 is added the last element 17 was move to the first and then 11 is added.\nthus this pattern continues further**\n\n**we can see that the whenever a element is added in the front the last element is popped and brought to the first of the queue and then the ordered element is added right.**\n\n\n**so we can achieve this via deque. if a element is present we just have to pop the element and add it to the first and then add the element to the array.**\n\n**Thats it you have your soln. Give it a go yourself guys!! before seeing soln..**\n\n# Code\n``` Java []\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n int n=deck.length;\n Arrays.sort(deck);\n Deque <Integer> st=new ArrayDeque<>();\n st.addFirst(deck[n-1]);\n for(int i=n-2;i>=0;i--){\n st.addFirst(st.removeLast());\n st.addFirst(deck[i]);\n }\n //we can either create a new array or change the existing since we dont need it right??but it is not recommended \n\n for(int i=0;i<n;i++){\n deck[i]=(int)st.removeFirst();\n }\n return deck;\n }\n}\n```\n``` Python3 []\nfrom collections import deque\n\nclass Solution:\n def deckRevealedIncreasing(self, deck):\n n = len(deck)\n deck.sort()\n st = deque()\n st.append(deck[n - 1])\n for i in range(n - 2, -1, -1):\n st.appendleft(st.pop())\n st.appendleft(deck[i])\n revealed = []\n while st:\n revealed.append(st.popleft())\n return revealed\n\n```\n\n``` C++ []\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n\n int n = deck.size();\n std::sort(deck.begin(), deck.end());\n std::deque<int> st;\n st.push_front(deck[n - 1]);\n for (int i = n - 2; i >= 0; i--) {\n st.push_front(st.back());\n st.pop_back();\n st.push_front(deck[i]);\n }\n std::vector<int> revealed;\n for (int i = 0; i < n; i++) {\n revealed.push_back(st.front());\n st.pop_front();\n }\n return revealed;\n }\n};\n\n```\n``` JavaScript []\n/**\n * @param {number[]} deck\n * @return {number[]}\n */\nvar deckRevealedIncreasing = function(deck) {\n \n const n = deck.length;\n deck.sort((a, b) => a - b);\n const revealed = [];\n revealed.unshift(deck[n - 1]);\n for (let i = n - 2; i >= 0; i--) {\n revealed.unshift(revealed.pop());\n revealed.unshift(deck[i]);\n }\n return revealed;\n};\n\n```\n# If this was helpful Please upvote!!
39
1
['Array', 'Queue', 'Sorting', 'C++', 'Java', 'Python3', 'JavaScript']
12
reveal-cards-in-increasing-order
Beat 100%| Using Deque
beat-100-using-deque-by-cs_monks-cf1h
\n\n# Intuition\n1. To solve this problem, we can simulate the process described in the prompt.\n \n# Approach\n- Sort the deck in descending order: \n 1. S
CS_MONKS
NORMAL
2024-04-10T00:19:07.210001+00:00
2024-04-10T12:52:28.372977+00:00
5,624
false
![Screenshot from 2024-04-10 05-46-23.png](https://assets.leetcode.com/users/images/ec244e24-6b7b-4bcf-af2b-f1fee65d149d_1712708730.2507572.png)\n\n# Intuition\n1. To solve this problem, we can simulate the process described in the prompt.\n \n# Approach\n- **Sort the deck in descending order**: \n 1. Sort the deck in descending order so that the largest cards are placed at the beginning of the deck.\n 2. Use `sort(rbegin(deck), rend(deck))` to sort the deck in descending order.\n\n- **Prepare a deque to simulate the card revealing process**: \n 1. Use a deque (`deque<int> dq`) to simulate the process of revealing cards.\n 2. A deque is chosen because it allows efficient insertion and removal of elements from both ends. \n\n- **Initialize deque with the largest card**: \n 1. Add the largest card from the sorted deck to the front of the deque using `dq.push_front(deck[0])`.\n\n- **Simulate the revealing process**: \n 1. Starting from the second largest card, iterate through the sorted deck.\n 2. For each card:\n - Take the top card from the back of the deque to simulate revealing a card (`int x = dq.back()`).\n - Remove this card from the deque (`dq.pop_back()`).\n - Place this revealed card at the front of the deque (`dq.push_front(x)`).\n - Add the current card from the sorted deck to the front of the deque (`dq.push_front(deck[i])`).\n\n- **Retrieve the revealed cards in increasing order**: \n 1. After simulating the revealing process for all cards, retrieve the revealed cards from the front of the deque one by one.\n 2. Add them to a vector (`vector<int> ans`).\n 3. Continue this process until the deque is empty.\n\n- **Return the ordered deck**: \n 1. Return the vector containing the ordered deck, where the order represents the sequence in which the cards are revealed.\n\n\n\n# Complexity\n- **Time complexity**: \n - Sorting the deck takes $$O(n \\log n)$$ time.\n - Revealing each card and updating the deque takes $$O(n)$$ time.\n - Overall time complexity is $$O(n \\log n)$$.\n- **Space complexity**:\n - We use a deque of size $$n$$ to store the revealed cards, so the space complexity is $$O(n)$$.\n# Dry Run\nOriginal deck: [17, 13, 11, 2, 3, 5, 7]\nAfter sorting: [17, 13, 11, 7, 5, 3, 2]\n\nnitialize deque with the largest card:\nDeque: [17]\n\nCard 13: First, move 17 to the front, then insert 13 at the front: [13, 17]\nCard 11: First, move 17 to the front, then insert 13 at the front: [11, 17, 13]\nCard 7: First, move 13 to the front, then insert 7 at the front: [7, 13, 11, 17]\nCard 5:First, move 17 to the front, then insert 5 at the front: [5, 17,7, 13, 11]\nCard 3: First, move 11 to the front, then insert 3 at the front: [3, 11,5, 17,7, 13]\nCard 2: First, move 17 to the front, then insert 13 at the front: [2, 13, 3, 11,5, 17,7]\n# Code\n```c++ []\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n // Sort the deck in descending order\n sort(rbegin(deck), rend(deck)); // Initialize a deque to simulate the card revealing process\n deque<int> dq; // Number of cards in the deck\n int n = deck.size(); // Initialize deque with the largest card\n dq.push_front(deck[0]); // Simulate the revealing process\n for(int i = 1; i < n; i++) {\n // Take the top card from the back of the deque\n int x = dq.back();\n // Remove this card from the deque\n dq.pop_back();\n // Place this revealed card at the front of the deque\n dq.push_front(x);\n // Add the current card from the sorted deck to the front of the deque\n dq.push_front(deck[i]);\n }\n // Retrieve the revealed cards in increasing order\n vector<int> ans;\n while(!dq.empty()) {\n ans.push_back(dq.front());\n dq.pop_front();\n }\n // Return the ordered deck\n return ans;\n }\n};\n\n```\n\n```java []\n\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck);\n Deque<Integer> dq = new LinkedList<>();\n int n = deck.length;\n dq.offerFirst(deck[n - 1]);\n for (int i = n - 2; i >= 0; i--) {\n int x = dq.pollLast();\n dq.offerFirst(x);\n dq.offerFirst(deck[i]);\n }\n\n int[] ans = new int[n];\n int index = 0;\n while (!dq.isEmpty()) {\n ans[index++] = dq.pollFirst();\n }\n return ans;\n }\n}\n\n```\n```python3 []\nfrom typing import List\nfrom collections import deque\n\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n deck.sort(reverse=True)\n dq = deque()\n n = len(deck)\n dq.appendleft(deck[0])\n for i in range(1, n):\n x = dq.pop()\n dq.appendleft(x)\n dq.appendleft(deck[i])\n\n ans = []\n while dq:\n ans.append(dq.popleft())\n return ans\n\n```\n``` javascript []\n\nvar deckRevealedIncreasing = function(deck) {\n deck.sort((a, b) => b - a); // Sort the deck in descending order\n const dq = [];\n const n = deck.length;\n dq.push(deck[0]);\n for (let i = 1; i < n; i++) {\n const x = dq.pop();\n dq.unshift(x);\n dq.unshift(deck[i]);\n }\n\n const ans = [];\n while (dq.length > 0) {\n ans.push(dq.shift());\n }\n return ans;\n};\n\n```\n![upvote.jpg](https://assets.leetcode.com/users/images/e794be62-1f12-44b3-aeb9-0552604b08b4_1712708602.8748598.jpeg)\n
33
0
['Python', 'C++', 'Java', 'Python3', 'JavaScript']
10
reveal-cards-in-increasing-order
c++ | easy understanding | queue
c-easy-understanding-queue-by-gom3a98-iu4c
\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.begin() , deck.end());\n int n = deck.size();
gom3a98
NORMAL
2022-09-28T08:58:48.823887+00:00
2022-09-28T08:58:48.823927+00:00
1,884
false
```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.begin() , deck.end());\n int n = deck.size();\n queue<int>q;\n int i = 0;\n while(i<n) q.push(i++);\n vector<int>ans(n);\n for(i = 0 ; i < n ; i++){\n ans[q.front()] = deck[i];\n q.pop();\n q.push(q.front());\n q.pop();\n }\n return ans;\n }\n};\n\n```
25
0
['Queue', 'C']
6
reveal-cards-in-increasing-order
Sort decreasing & deque vs radix sort & deque||0ms beats 100%
sort-decreasing-deque-vs-radix-sort-dequ-g0av
Intuition\n Describe your first thoughts on how to solve this problem. \nLook at this picture from @PrashantUnity, it is to get a clue how to solve this qestion
anwendeng
NORMAL
2024-04-10T00:43:20.221967+00:00
2024-04-10T09:21:50.339715+00:00
3,651
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLook at this picture from @PrashantUnity, it is to get a clue how to solve this qestion. Revealing process makes the revealing card on the front!!\n![61b8e65d-37fe-4809-b4f4-d327f9714ad8_1675091990.5803869.png](https://assets.leetcode.com/users/images/ed1ef4bd-4772-4547-babe-b10d62f0674d_1712709579.0850759.png)\n\n2nd approach uses radix sort with 1024 buckets to reduce the time complexity of $O(n\\log_{1024}(\\max(deck))+n)=O(n\\times 2+n)=O(n)$\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sort deck in decreasing order\n2. Creat a deque `reveal` containing `deck[0]`\n3. a loop from i=1 to n-1 do the following( which is the reversive process of revealing)\n```\nint back=reveal.back();\nreveal.pop_back();\nreveal.push_front(back);\nreveal.push_front(deck[i]);\n```\n4. Convert reveal to vector & return it\nLet\'s see how this process for the testcase=`deck =\n[13,3,5,7,11,17]`\n```\nsorted deck=[17, 13, 11, 7, 5, 3]\n0-> reveal=[17]\n1-> reveal=[13, 17]\n2-> reveal=[11, 17, 13]\n3-> reveal=[7, 13, 11, 17]\n4-> reveal=[5, 17, 7, 13, 11]\n5-> reveal=[3, 11, 5, 17, 7, 13]\n```\nthe process for testcase `deck =\n[17,13,1,2,3,5,7]`\n```\nsorted deck=[17, 13, 7, 5, 3, 2, 1]\n0-> reveal=[17]\n1-> reveal=[13, 17]\n2-> reveal=[7, 17, 13]\n3-> reveal=[5, 13, 7, 17]\n4-> reveal=[3, 17, 5, 13, 7]\n5-> reveal=[2, 7, 3, 17, 5, 13]\n6-> reveal=[1, 13, 2, 7, 3, 17, 5]\n```\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n\\log n)\\to O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.rbegin(), deck.rend());\n int n=deck.size();\n deque<int> reveal={deck[0]};\n for(int i=1; i<n; i++){\n int back=reveal.back();\n reveal.pop_back();\n reveal.push_front(back);\n reveal.push_front(deck[i]);\n }\n return vector<int>(reveal.begin(), reveal.end());\n }\n};\n\n\n\nauto init = []() {\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n# 2nd approach uses radix sort||0ms beats 100%\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n vector<int> bucket[1024];\n void radix_sort(vector<int>& nums) {\n // 1st round\n for (int x : nums)\n bucket[x&1023].push_back(x);\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>>10].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 }\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n radix_sort(deck);\n int n=deck.size();\n deque<int> reveal={deck[n-1]};\n for(int i=n-2; i>=0; i--){\n int back=reveal.back();\n reveal.pop_back();\n reveal.push_front(back);\n reveal.push_front(deck[i]);\n }\n return vector<int>(reveal.begin(), reveal.end());\n }\n};\n\n```\n
22
0
['Queue', 'Sorting', 'Radix Sort', 'C++']
10
reveal-cards-in-increasing-order
0ms | 100% faster | Using Queue in C++
0ms-100-faster-using-queue-in-c-by-steel-ls9r
\n// T.C = O(nlog(n)) because of sort function\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n queue<int> Q;\n
SteelTitan
NORMAL
2021-02-12T20:21:38.833980+00:00
2021-02-12T20:21:38.834005+00:00
2,198
false
```\n// T.C = O(nlog(n)) because of sort function\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n queue<int> Q;\n int n=deck.size();\n vector<int> ans(n,0);\n \n for(int i=0;i<n;i++)\n Q.push(i);\n \n sort(deck.begin(),deck.end());\n int i=0;\n \n while(!Q.empty() && i<n){\n ans[Q.front()] = deck[i];\n Q.pop();\n Q.push(Q.front());\n Q.pop();\n i++;\n }\n return ans;\n }\n};\n```
22
1
['Array', 'Queue', 'C', 'Sorting', 'C++']
5
reveal-cards-in-increasing-order
JavaScript 52ms 100%
javascript-52ms-100-by-space_sailor-gdel
Draw process: \n\n1. newDeck = deck.pop()\n2. deck.push(deck.shift())\n3. Start from step 1\n\n### Reverse draw process: \n\n1. ans.unshift(newDeck.pop())\n2. a
space_sailor
NORMAL
2019-09-23T13:45:44.900374+00:00
2019-09-23T13:46:07.860780+00:00
1,289
false
### Draw process: \n\n1. newDeck = deck.pop()\n2. deck.push(deck.shift())\n3. Start from step 1\n\n### Reverse draw process: \n\n1. ans.unshift(newDeck.pop())\n2. ans.unshift(ans.pop())\n3. If newDeck is not empty, start from step 1, otherwise go step 4.\n4. When finished, there will be an extra step 2, so need to undo step 2 once: `ans.push(ans.shift())`\n\n```\nconst deckRevealedIncreasing = deck => {\n deck.sort((a, b) => a - b);\n const ans = [];\n while (deck.length) {\n ans.unshift(deck.pop());\n ans.unshift(ans.pop());\n }\n ans.push(ans.shift());\n return ans;\n};\n```
21
0
['JavaScript']
2
reveal-cards-in-increasing-order
Beats 100%|| 0ms || Easy Approach ✅ Using Queue 🚀with Explanation🔥
beats-100-0ms-easy-approach-using-queue-l4yw7
Intuition\n Describe your first thoughts on how to solve this problem. \n- As topic were listed as queue and to order the cards in alternative but increasing or
lucky_chajjer
NORMAL
2024-04-10T05:28:28.455996+00:00
2024-04-10T05:28:28.456031+00:00
3,213
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- As topic were listed as queue and to order the cards in alternative but increasing order we have to use queue\'s properties that is pushes element forward after pop.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nFor rearranging first we have to sort the given.Then traverse it in reverse. Think in a reverse order as what would you want the last case to look like and move upway to the first case or start.\n\n- Take the eg: [17,13,11,2,3,5,7]\n- After sorting: [2,3,5,7,11,13,17]\n1. Taking the from last to first \n- [17]\n- [13,17] - the next element is added forward\n- [11,17,13] - here before the next ele is added 17,13 swapped places or 17 was popped and pushed back then new element is added.\n- [7,13,11,17] - here 13 is popped pushed after 11 and then next ele 7 is pushed.\n- [5,17,7,13,11] - 17 popped pushed to back then new ele 5 is pushed.\n- [3,11,5,17,7,13] - 13 popped pushed and then 3 is pushed. \n- [2,13,3,11,5,17,7] - 13 is popped pushed and then 2 is pushed.\n\n2. Using the pattern obtain the pseudocode is:\n - sort the list and iterate in reverse.\n - pop the last element in queue and push it to back.\n - add the next element in array.\n - as it is a queue elements are stored reversed.\n - while popping back element to array insert element in reverse.\n\n# Complexity\n- Time complexity: \n- Sorting - $$O(nlogn)$$ Queue implemented -$$O(n)$$ and retreving element from queue - $$O(n)$$ ---> Time complexity: $$O(nlogn)$$\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 {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n queue<int> qp;\n sort(deck.begin(),deck.end()); //sort the array\n for(int i = deck.size()-1;i>=0;i--){\n if(!qp.empty()){ \n qp.push(qp.front()); // push the top element\n qp.pop(); // pop the element\n }\n qp.push(deck[i]); // then push new element\n }\n for(int i = deck.size()-1;i>=0;i--){\n deck[i] = qp.front(); \n qp.pop();\n }\n return deck;\n }\n};\n```
20
0
['Queue', 'C++']
6
reveal-cards-in-increasing-order
✅Different approach💯🔥with expanation💯🔥 Beats 100% ✅
different-approachwith-expanation-beats-ee4jb
Intuition\n#### The solution follows a divide-and-conquer strategy, using the merge sort algorithm. Initially, it sorts the deck in ascending order. Then, it re
ribhav_32
NORMAL
2024-04-10T06:52:27.907231+00:00
2024-04-10T06:52:27.907261+00:00
1,060
false
# Intuition\n#### *The solution follows a divide-and-conquer strategy, using the merge sort algorithm. Initially, it sorts the deck in ascending order. Then, it recursively divides the sorted deck into halves until each subarray contains only one or zero elements. During the merging process, it interleaves the elements from the divided subarrays in a manner that reveals the cards in increasing order. By merging the sorted subarrays, it reconstructs the deck with the cards revealed in ascending order.*\n\n![b772cc9a-b8c8-45ab-941f-ac36c1900ea2_1696303869.2008665.png](https://assets.leetcode.com/users/images/f2e6dcb5-cfa0-46d6-9d53-702ac11cb766_1712731907.2145538.png)\n\n\n\n# Approach\n#### The provided solution employs a recursive merge sort algorithm to achieve the desired result of revealing cards in increasing order. \n\n## Here\'s an explanation of the approach:\n\n1. **Merge Function** (`merge`):\n - This function takes two sorted vectors, `left` and `right`, and merges them into a single sorted vector.\n - It determines the size of the merged vector and adjusts it if necessary to handle odd-sized arrays.\n - Then, it iterates through both vectors, comparing elements and adding them to the merged vector in ascending order.\n - If there are any remaining elements in either `left` or `right` vector, they are appended to the merged vector.\n\n2. **Divide Function** (`divide`):\n - This function recursively divides the input array into smaller subarrays until it reaches base cases (subarrays of size 0 or 1).\n - It calculates the middle index of the current subarray and recursively divides the array into two halves.\n - Each half is processed recursively using `divide`.\n - Once the base cases are reached, the function returns the sorted subarrays.\n\n3. **Deck Revealed Increasing Function** (`deckRevealedIncreasing`):\n - This is the entry point of the solution.\n - It sorts the input deck in ascending order using `sort`.\n - Then, it calls the `divide` function to split the sorted deck into smaller subarrays and merge them in increasing order.\n\n#### Overall, the solution reveals the cards in increasing order by utilizing the merge sort algorithm.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(Nlog(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```\nclass Solution {\npublic:\n // Function to merge two sorted vectors into a single sorted vector\n vector<int> merge(vector<int>& left, vector<int>& right) {\n // Calculate the size of the merged vector\n int merged_size = left.size() + right.size();\n // Adjust the size if it\'s odd to ensure correct merging\n if (merged_size % 2 == 1) {\n int last_element = right[right.size() - 1];\n // Shift elements in the right vector to make space for the last element\n for (int i = right.size() - 1; i > 0; i--) {\n right[i] = right[i - 1];\n }\n right[0] = last_element; // Place the last element at the beginning\n }\n // Create a vector to store the merged elements\n vector<int> merged(merged_size);\n int left_index = 0, right_index = 0, merged_index = 0;\n // Merge the elements from left and right vectors in sorted order\n while (left_index < left.size() && right_index < right.size()) {\n merged[merged_index++] = left[left_index++];\n merged[merged_index++] = right[right_index++];\n }\n // Append any remaining elements from the left vector\n while (left_index < left.size()) {\n merged[merged_index++] = left[left_index++];\n }\n // Append any remaining elements from the right vector\n while (right_index < right.size()) {\n merged[merged_index++] = right[right_index++];\n }\n return merged; // Return the merged vector\n }\n\n // Recursive function to divide the array and merge the subarrays\n vector<int> divide(vector<int>& array, int start, int end) {\n if (start > end) return {}; // Base case: empty subarray\n if (start == end) return {array[start]}; // Base case: single element subarray\n // Calculate the middle index of the current subarray\n int mid = start + (end - start) / 2;\n // Recursively divide the left half of the array\n vector<int> left_half;\n for(int i = start; i <= mid; i++){\n left_half.push_back(array[i]);\n }\n // Recursively divide the right half of the array\n vector<int> right_half = divide(array, mid + 1, end);\n // Merge the sorted subarrays and return the result\n return merge(left_half, right_half);\n }\n\n // Function to sort the deck and reveal cards in increasing order\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.begin(), deck.end()); // Sort the deck in increasing order\n // Divide the sorted deck into subarrays and merge them\n return divide(deck, 0, deck.size() - 1);\n }\n};\n```\n\n![593c0559-644c-43cf-95fc-b18138253456_1684110070.1871367.png](https://assets.leetcode.com/users/images/f351e8bb-7c28-4022-bddf-590890d86433_1712731885.7986205.png)
16
0
['Array', 'Recursion', 'Merge Sort', 'C++']
3
reveal-cards-in-increasing-order
Easy simulation based approach and intuition✅ || Clean code ✅ || Python3
easy-simulation-based-approach-and-intui-zfkh
Intuition\nIf the question were to validate whether a given answer is correct, a straightforward way to approach this problem would have been by simulating it.
reas0ner
NORMAL
2024-04-10T00:34:41.014263+00:00
2024-04-10T20:12:23.816883+00:00
1,066
false
# Intuition\nIf the question were to validate whether a given answer is correct, a straightforward way to approach this problem would have been by simulating it. We could use a queue to simulate the taking and putting cards at the start and end. The problem statement is a little confusing, but what it means is that we want to find one such valid ordering.\n\n# Approach\nThe first important thing to do is to sort the deck in increasing order, as it represents the final sequence of cards we want. \n\nLet\'s take the example - \ndeck = 17,13,11,2,3,5,7\nsorted deck = 2,3,5,7,11,13,17\n\nNow is there a way to reverse engineer a valid ordering such that when we run the queue-based process on it, we get back the original array? For this, the logical step is to analyze the shuffle and try to find what order the indices are getting revealed.\n\nBut we have different indices every time, and programmatically way to do that is by simulating the shuffle with a queue - and once we have the ordering, we can just use it to make a valid result. In other words, if we know what position of the array would be picked at what step of the algorithm when we run it later, could we not just put the right number there?\n\nLet\'s play out the example we started with to understand the above idea better.\n\nqueue: 0,1,2,3,4,5,6\n\nindex 0 is getting processed, put 2 at index 0, queue : 2,3,4,5,6,1\nindex 2 is getting processed, put 3 at index 2, queue: 4,5,6,1,3\nindex 4 is getting processed, put 5 at index 4, queue: 6,1,3,5\nindex 6 is getting processed, put 7 at index 6, queue: 3,5,1\nindex 3 is getting processed, put 11 at index 3, queue: 1,5\nindex 1 is getting processed, put 13 at index 1, queue: 5\nindex 5 is getting processed, put 17 at index 5\n\nAs we see, we end up with the valid ordering: [2,13,3,11,5,17,7] because we know the indices are always gonna be processed in the order: 0,2,4,6,3,1,5 when we run the shuffle algorithm on it.\n\n\n# Complexity\n- Time complexity:\nO(nlogn) - due to sorting\n\n- Space complexity:\nO(n) - due to the queue\n\n# Code\n```\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n n = len(deck)\n deck.sort()\n q = deque(range(n))\n res = [0] * n\n\n for card in deck:\n res[q.popleft()] = card # reveal the top card and take it out of the deck\n if q:\n q.append(q.popleft()) # putting the next top card of the deck at the bottom of the deck\n\n return res\n```\n\nIf this post helped you understand the problem better, please leave an upvote :)
16
3
['Queue', 'Simulation', 'Python3']
3
reveal-cards-in-increasing-order
Python concise & straightforward
python-concise-straightforward-by-cenkay-z9c1
Just follow the instructions and simulate\n For your final array, just make index array (ind) showing indexes of each (to be determined) number.\n During each s
cenkay
NORMAL
2018-12-02T04:03:04.884297+00:00
2018-12-02T04:03:04.884395+00:00
3,163
false
* Just follow the instructions and simulate\n* For your final array, just make index array (ind) showing indexes of each (to be determined) number.\n* During each simulation; \n\t* assign current popped number in the ref array(ordered) for faced index\n\t* remove first element from index array and move 2nd element to the end\n\n* Contest solution\n```\nclass Solution:\n def deckRevealedIncreasing(self, deck):\n ref, res, ind = sorted(deck, reverse = True), deck[:], list(range(len(deck)))\n while ref:\n res[ind[0]] = ref.pop()\n ind = ind[2:] + [ind[1]] if len(ind) > 1 else []\n return res\n```\n* Optimized solution\n```\nclass Solution:\n def deckRevealedIncreasing(self, deck):\n ind = list(range(len(deck)))\n for num in sorted(deck):\n deck[ind[0]] = num\n ind = ind[2:] + [ind[1]] if len(ind) > 1 else []\n return deck\n```
16
3
[]
3
reveal-cards-in-increasing-order
Interview Approach with Video Solution ✅ || Sort + Queue Simulation 🔥
interview-approach-with-video-solution-s-wvk4
Intuition\nUnderstand the question clearly and dry-run few examples then you can implement the solution\n\nIf you learned something from the solution. Please Up
ayushnemmaniwar12
NORMAL
2024-04-10T08:33:49.508782+00:00
2024-04-10T08:35:48.803606+00:00
1,361
false
# Intuition\nUnderstand the question clearly and dry-run few examples then you can implement the solution\n\n***If you learned something from the solution. Please Upvote and subscribe to my youtube channel***\n\n\n# Easy Video Solution \n\nhttps://youtu.be/bvDQ4NSUn0g\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& v) {\n sort(v.begin(),v.end());\n queue<int>q;\n int n=v.size();\n for(int i=0;i<n;i++) {\n q.push(i);\n }\n vector<int>ans(n,0);\n int i=0;\n while(!q.empty()) {\n int k=q.front();\n ans[k]=v[i];\n q.pop();\n if(!q.empty()) {\n int x=q.front();\n q.push(x);\n q.pop();\n }\n i++;\n }\n return ans;\n }\n};\n```
15
0
['Queue', 'Sorting', 'C++']
1
reveal-cards-in-increasing-order
Java 1ms solution | 100% faster | Based on Simple Math
java-1ms-solution-100-faster-based-on-si-k5wq
\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n \n if(deck.length==1)\n return deck;\n \n Arr
janakikeerthi1997
NORMAL
2021-05-20T15:30:39.254472+00:00
2021-06-12T14:47:00.053711+00:00
1,319
false
```\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n \n if(deck.length==1)\n return deck;\n \n Arrays.sort(deck);\n int res[] = new int[deck.length];\n int k = 1;\n int c = 0;\n res[0] = deck[0];\n \n // insert the elements from the sorted array into every 2nd empty slot of result array\n while(k<deck.length)\n {\n for(int i=1;i<deck.length;i++)\n { \n if(res[i]==0)\n {\n c++;\n if(c==2)\n {\n res[i] = deck[k++];\n c=0;\n }\n }\n }\n }\n\n return res;\n }\n}\n```
14
0
['Java']
3
reveal-cards-in-increasing-order
Reveal Cards In Increasing Order Solution in C++
reveal-cards-in-increasing-order-solutio-iu0e
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
The_Kunal_Singh
NORMAL
2023-04-24T12:59:34.974412+00:00
2023-04-27T16:25:42.709514+00:00
1,094
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n int i;\n vector<int> ans(deck.size(), 0);\n sort(deck.begin(), deck.end());\n queue<int> q;\n\n for(i=0 ; i<deck.size() ; i++)\n {\n q.push(i);\n }\n\n for(i=0 ; i<deck.size() ; i++)\n {\n ans[q.front()] = deck[i];\n q.pop();\n q.push(q.front());\n q.pop();\n }\n\n return ans;\n }\n};\n```\n![upvote new.jpg](https://assets.leetcode.com/users/images/1052d759-9645-4863-9a29-8e9735109513_1682612739.921707.jpeg)\n
12
0
['C++']
5
reveal-cards-in-increasing-order
[950. Reveal Cards In Increasing Order] C++_8ms_100%
950-reveal-cards-in-increasing-order-c_8-20sy
Algorithm: Start from the last step, and go back to the first step.\nOur vector is [2,13,3,11,5,17,7].\nThe last step is [17], which is the largest element. [17
jasonshieh
NORMAL
2018-12-03T01:05:21.235129+00:00
2018-12-03T01:05:21.235189+00:00
1,347
false
Algorithm: Start from the last step, and go back to the first step.\nOur vector is [2,13,3,11,5,17,7].\nThe last step is [17], which is the largest element. **[17]**\nBefore 17, the number should be 13. Of course, the vector can be [13, 17], as we pop out 13, then there is 1 element in the vector, it does not matter whether we rotate the vector.**[13 ,17]**\nThe next element should be 11. If we wanna make the vector like [13, 17] after popping out 11, then 17 should be the next element after 11. Because once we pop out 13, the 17 can be moved to the end of vector. so now the vector is **[11, 17, 13]**\nThe next element is 7. Similar as previous step, if we want to make the vector to be [11, 17, 13] after popping out 7, then 13 is the next element after 7, so the vector is **[7, 13, 11, 17]**\n\nAlgorithm:\nSort the deck.\nPush the current number deck[i] to the vector [i]\nIndexes: [0, 1, 2, ......, i, i+1, ......n-2, n-1]\nrotate the range [i+1],...,[n-2] with [n-1].\nRepeat until the last element is pushed into the vector.\n\n\n\n\n class Solution {\n\tpublic:\n\t\tvector<int> deckRevealedIncreasing(vector<int>& deck) {\n\t\t\t//Just do the Counter Operation\n\t\t\tint n = deck.size();\n\t\t\tvector<int> res(n);\n\t\t\tsort(deck.begin(), deck.end());\n\t\t\tres[n-1] = deck.back();\n\t\t\tfor(int i = n - 2; i >= 0; --i){\n\t\t\t\tres[i] = deck[i];\n\t\t\t\trotate(res.begin() + i + 1, res.begin() + n - 1, res.end());\n\t\t\t}\n\t\t\treturn res;\n\t\t}\n\t};
12
0
[]
5
reveal-cards-in-increasing-order
👏Beats 86.41% of users with Java || ✅Easy & Well Explain Solution using Deque🔥💥
beats-8641-of-users-with-java-easy-well-5ihdq
Intuition\nGiven an integer array deck representing a deck of cards, you want to reveal cards in increasing order. You reveal cards one by one, and you choose t
Rutvik_Jasani
NORMAL
2024-04-10T09:47:28.002310+00:00
2024-04-10T09:47:28.002337+00:00
442
false
# Intuition\nGiven an integer array deck representing a deck of cards, you want to reveal cards in increasing order. You reveal cards one by one, and you choose the order in which you reveal them. Initially, all the cards are face down (i.e., hidden). The first card you reveal is the leftmost card. Then, you reveal every other card in the deck, alternating between face-up and face-down.\n\nReturn an array of the deck in the order you should reveal the cards.\n\n# I Think This Can Help You(For Proof Click on the Image)\n[![Screenshot 2024-02-24 232407.png](https://assets.leetcode.com/users/images/1a94d26a-bdf7-49b1-bb7e-f9668e68cd1f_1712742420.7162144.png)](https://leetcode.com/problems/reveal-cards-in-increasing-order/submissions/1228415631/?envType=daily-question&envId=2024-04-10)\n\n\n# Approach\n1. **Sort the Deck:** First, we sort the deck in ascending order. This ensures that when we start revealing cards, we reveal them in increasing order.\n \n ```java\n Arrays.sort(deck);\n ```\n\n2. **Initialize Deque and Answer Array:** We initialize a deque (double-ended queue) to hold the indices of the cards in the deck, and an array to store the order in which the cards will be revealed.\n\n ```java\n Deque<Integer> ind = new ArrayDeque<>();\n int[] ans = new int[deck.length];\n ```\n\n3. **Populate Deque with Indices:** We populate the deque with the indices of the cards in the deck.\n\n ```java\n for(int i = 0; i < deck.length; i++) {\n ind.addLast(i);\n }\n ```\n\n4. **Reveal Cards:** We iterate through the deck indices. For each index, we reveal the card at that index by setting the corresponding position in the answer array to the card value. Then, we adjust the deque to alternate revealing cards.\n\n ```java\n int i = 0;\n while(!ind.isEmpty()) {\n ans[ind.pollFirst()] = deck[i];\n if(!ind.isEmpty()) {\n ind.addLast(ind.pollFirst());\n }\n i++;\n }\n ```\n\n5. **Return the Answer:** Finally, we return the array containing the order in which the cards should be revealed.\n\n ```java\n return ans;\n ```\n\n# Complexity\n- Time complexity:\nO(NlogN)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck);\n Deque<Integer> ind = new ArrayDeque<>();\n for(int i=0;i<deck.length;i++){\n ind.addLast(i);\n }\n int[] ans = new int[deck.length];\n int i=0;\n while(!ind.isEmpty()){\n ans[ind.pollFirst()] = deck[i];\n if(!ind.isEmpty()){\n ind.addLast(ind.pollFirst());\n }\n i++;\n }\n return ans;\n }\n}\n```\n\n![_6192221a-56cd-426e-b194-f5f718a7d8ae.jpeg](https://assets.leetcode.com/users/images/37919db1-a753-4bba-ab1b-29eb539c894c_1712742386.629275.jpeg)\n
10
0
['Array', 'Queue', 'Sorting', 'Simulation', 'Java']
1
reveal-cards-in-increasing-order
Intuition from fill gaps to optimized
intuition-from-fill-gaps-to-optimized-by-0qcg
From the example 1,2,3,4,5,6,7,8 and expected output 1,5,2,7,3,6,4,8 we can deduce:\nthat the first N/2 elements are going to fill positions 0,2,4,... (fill gap
vokasik
NORMAL
2024-03-15T01:36:40.590094+00:00
2024-03-15T01:36:40.590121+00:00
577
false
From the example `1,2,3,4,5,6,7,8` and expected output `1,5,2,7,3,6,4,8` we can deduce:\nthat the first `N/2` elements are going to fill positions 0,2,4,... (fill gap, skip gap, fill gap, skip gap, fill gap, ...)\n```\nInput:\n1 2 3 4 5 6 7 8\nOutput:\n_ _ _ _ _ _ _ _\n1 _ 2 _ 3 _ 4 _\n```\nThe next elements will follow the same pattern: fill gap, skip gap, fill gap, skip gap\n```\nOutput:\n1 _ 2 _ 3 _ 4 _\n1 5 2 _ 3 6 4 _\n```\nAnd again:\n```\nOutput:\n1 5 2 _ 3 6 4 _\n1 5 2 7 3 6 4 8\n```\nSo we can simulate the observation with inefficient, but quite easy solution:\n```\nclass Solution:\n def deckRevealedIncreasing(self, nums: List[int]) -> List[int]:\n N = len(nums)\n res = [0] * N\n nums.sort()\n i = 0\n j = 0\n skip = False\n while i < N: # while we have left nums to use\n if res[j] == 0: # if we found a gap\n if not skip: # fill phase\n res[j] = nums[i] # put num in a gap\n i += 1 # move to next num\n skip = not skip # flip skip and fill stages\n j = (j + 1) % N # cycle the res array to find gaps\n return res\n```\nNow that we know the idea, we see that the cycling is not optimal because we iterate over filled elements again and again (useless cycles).\nWe can optimize the cycle by keeping only gaps in a queue:\n```\nclass Solution:\n def deckRevealedIncreasing(self, nums: List[int]) -> List[int]:\n N = len(nums)\n res = [0] * N\n nums.sort(reverse=True) # reverse here to have nums.pop() later, we can add i and go forward too\n queue = deque(range(N)) # put available gaps in a queue\n take = True\n while queue:\n if take: # if we take, we remove the index from the queue as we won\'t use it again\n res[queue.popleft()] = nums.pop()\n else: # if it\'s skip filling the gap, we add the index to the back of the queue (exactly what we do in the original problem statement)\n queue.append(queue.popleft())\n take = not take # flip fill / skip\n return res\n```\nIn the previous example we see that we can remove `take/skip` variable as we always heve only 2 steps that are executed sequentially: take, skip, take, skip, take, skip....\n```\nclass Solution:\n def deckRevealedIncreasing(self, nums: List[int]) -> List[int]:\n N = len(nums)\n res = [0] * N\n nums.sort(reverse=True)\n queue = deque(range(N))\n for _ in range(N):\n res[queue.popleft()] = nums.pop() # 1) this is take\n if queue:\n queue.append(queue.popleft()) # 2) this is skip\n return res\n```\nCheers!\n\nQuestions?
10
0
['Python', 'Python3']
0
reveal-cards-in-increasing-order
Java solution by thinking reversely with explanation
java-solution-by-thinking-reversely-with-ewv2
```\n/ Consider reversely...\n * for ordered array [2, 5, 7, 10, 13, 17]\n * if there is only one card left, it must be 17;\n * if there are two card left, the
self_learner
NORMAL
2018-12-02T04:03:42.507932+00:00
2018-12-02T04:03:42.507979+00:00
963
false
```\n/* Consider reversely...\n * for ordered array [2, 5, 7, 10, 13, 17]\n * if there is only one card left, it must be 17;\n * if there are two card left, the order must be 13, 17;\n * if there are 3 card left, since after we reveal the first one, we will put the second one at the end:\n * thus reversely, we need to put the current last one at the front, and put the third card on top:\n * 10, 17, 13\n * similarly, if we have 4 card left, we will need to put the current last card 13 on top, and then add 7 on top:\n * thus we have 7, 13, 10, 17\n * ...\n */\n\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n if (deck == null) return deck;\n if (deck.length <= 1) return deck.clone();\n \n List<Integer> list = new LinkedList<>();\n Arrays.sort(deck);\n \n int n = deck.length;\n list.add(deck[n - 2]);\n list.add(deck[n - 1]);\n for (int i = n - 3; i >= 0; i--) {\n list.add(0, list.remove(list.size() - 1)); //move the current last card to the front...\n list.add(0, deck[i]); //add the prevoius card onto the top...\n }\n int[] res = new int[n];\n for (int i = 0; i < n; i++) {\n res[i] = list.get(i);\n }\n return res;\n }\n}
10
5
[]
4
reveal-cards-in-increasing-order
✅Easy✨||C++|| Beats 100% || With Explanation ||
easyc-beats-100-with-explanation-by-olak-ywbu
Intuition\n Describe your first thoughts on how to solve this problem. \nAs topic were listed as queue and to order the cards in alternative but increasing orde
olakade33
NORMAL
2024-04-10T10:20:38.985958+00:00
2024-04-10T10:20:38.985993+00:00
754
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs topic were listed as queue and to order the cards in alternative but increasing order we have to use queue\'s properties that is pushes element forward after pop.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor rearranging first we have to sort the given.Then traverse it in reverse. Think in a reverse order as what would you want the last case to look like and move upway to the first case or start.\n\nTake the eg: [17,13,11,2,3,5,7]\nAfter sorting: [2,3,5,7,11,13,17]\n1. Taking the from last to first\n. [17]\n. [13,17] - the next element is added forward\n. [11,17,13] - here before the next ele is added 17,13 swapped places or 17 was popped and pushed back then new element is added.\n. [7,13,11,17] - here 13 is popped pushed after 11 and then next ele 7 is pushed.\n. [5,17,7,13,11] - 17 popped pushed to back then new ele 5 is pushed.\n. [3,11,5,17,7,13] - 13 popped pushed and then 3 is pushed.\n. [2,13,3,11,5,17,7] - 13 is popped pushed and then 2 is pushed.\n2. Using the pattern obtain the pseudocode is:\n. sort the list and iterate in reverse.\n. pop the last element in queue and push it to back.\n. add the next element in array.\n. as it is a queue elements are stored reversed.\n. while popping back element to array insert element in reverse.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\nSorting - O(nlogn)O(nlogn)O(nlogn) Queue implemented -O(n) and retreving element from queue - O(n) ---> Time complexity: O(nlogn)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n queue<int> qp;\n sort(deck.begin(),deck.end()); //sort the array\n for(int i = deck.size()-1;i>=0;i--){\n if(!qp.empty()){ \n qp.push(qp.front()); // push the top element\n qp.pop(); // pop the element\n }\n qp.push(deck[i]); // then push new element\n }\n for(int i = deck.size()-1;i>=0;i--){\n deck[i] = qp.front(); \n qp.pop();\n }\n return deck;\n }\n};\n```
9
0
['C++']
0
reveal-cards-in-increasing-order
Short and Elegant Python Solution (with explanation)
short-and-elegant-python-solution-with-e-zqz2
Deck can be represented as a queue. If we have a solution, we repeat the following two operations:\n(1) Pull head of the queue (in ascending order).\n(2) Move h
marboni
NORMAL
2021-08-07T04:57:18.588125+00:00
2021-08-07T05:29:54.108817+00:00
807
false
Deck can be represented as a queue. If we have a solution, we repeat the following two operations:\n(1) Pull head of the queue (in ascending order).\n(2) Move head to the tail.\n\n```\n1 3 2 4\n\n1 <<< 2 4 (3)\n2 <<< 3 (4)\n3 <<< (4)\n4 <<< empty\n```\n\nTo come up with the solution, we need to "load" the queue back, reversing both operations and their order:\n(2) Move tail to the head.\n(1) Push head to the queue (in descending order).\n\nWe will skip (2) if the queue is empty, of course.\n\n```\n4 >>> 4\n3 >>> 3 (4)\n2 >>> 2 (4) 3 \n1 >>> 1 (3) 2 4\n```\n\n```\nfrom collections import deque\n\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n queue = deque()\n deck.sort(reverse=True)\n for card in deck:\n if queue:\n queue.appendleft(queue.pop())\n queue.appendleft(card)\n return queue\n```
9
0
['Queue', 'Python']
0
reveal-cards-in-increasing-order
C++ Simple and Short Clean Solution, No Queue - O(1) SC, 0ms Faster than 100%
c-simple-and-short-clean-solution-no-que-yvi8
In each iteration, we look for the next empty slot, skip it, and fill only the next one.\n\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(ve
yehudisk
NORMAL
2021-07-19T13:53:11.995218+00:00
2021-07-19T13:53:23.810548+00:00
587
false
In each iteration, we look for the next empty slot, skip it, and fill only the next one.\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n int n = deck.size(), filled = 0;\n vector<int> res(n, -1);\n sort(deck.begin(), deck.end());\n \n for (int i = 0, ptr = 0; i < n; i++) {\n res[ptr] = deck[i];\n filled++;\n \n if (filled == n) return res;\n \n // Find a -1, skip it and look for the next -1\n while (res[ptr] != -1) ++ptr %= n;\n ++ptr %= n;\n while (res[ptr] != -1) ++ptr %= n;\n }\n return res;\n }\n};\n```\n**Like it? please upvote!**
9
1
['C']
4
reveal-cards-in-increasing-order
Time Complexity O(N) Java Simulation with Queue
time-complexity-on-java-simulation-with-exzcj
You will see most of answers has Array sorting. The complexity of sorting is generally O(NlogN) that is increasing solutions\' time complexity but there are som
uyarertalat1961
NORMAL
2019-01-10T18:24:49.187947+00:00
2019-01-10T18:24:49.188009+00:00
1,170
false
You will see most of answers has Array sorting. The complexity of sorting is generally O(NlogN) that is increasing solutions\' time complexity but there are some sorting algorithms which works with complexity of O(N) like as Counting sort, Radix Sort or Bucket sort.\n\nFor this question since **the range of numbers are limited**, we can take advantage of Counting sort for complexity of O(N).\n\nFor my solution Time Complexity is O(n+k) where n is the number of elements in input array and k is the range of input which is 10^6.\n\n```\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n //Queue for storing deck indicies.\n Queue<Integer> index = new LinkedList();\n //Card counts\n int[] cards = new int[1000001];\n \n for(int i = 0; i < deck.length; i++){\n index.add(i);\n cards[deck[i]]++;\n }\n \n //Returning array\n int[] result = new int[deck.length];\n\n for(int card = 1; card < cards.length; card++){\n if(cards[card] != 0){\n result[index.poll()] = card;\n index.add(index.poll()); \n }\n } \n return result;\n \n }\n}\n```
8
0
[]
5
reveal-cards-in-increasing-order
Python3 Solution
python3-solution-by-motaharozzaman1996-c7vf
\n\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n ans=[]\n deck.sort(reverse=True)\n for i in deck
Motaharozzaman1996
NORMAL
2024-04-10T01:29:04.640875+00:00
2024-04-10T01:29:04.640901+00:00
503
false
\n```\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n ans=[]\n deck.sort(reverse=True)\n for i in deck:\n ans=[i]+ans[-1:]+ans[:-1]\n return ans \n```
7
0
['Python', 'Python3']
2
reveal-cards-in-increasing-order
✅🔥Easy Solution with Explanation🔥✅ | Fast | Python3 | Python | Queue
easy-solution-with-explanation-fast-pyth-2jiy
Intuition\nImagine you have a deck of cards and want to reveal them in a special way. First, you sort them from highest to lowest. Then, you start placing them
KrishSukhani23
NORMAL
2024-04-10T00:47:29.511781+00:00
2024-04-10T00:47:29.511801+00:00
964
false
# Intuition\nImagine you have a deck of cards and want to reveal them in a special way. First, you sort them from highest to lowest. Then, you start placing them in a new pile, but with a twist: every time you place a card, you take the card that\'s on top of the new pile and put it underneath before adding the next highest card. This way, when you finish and look at the new pile from top to bottom, they appear in a specific increasing order, even though that\'s not how you placed them originally.\n\n\n# Approach\nSort the Cards: Begin with the highest card so it ends up in the correct position at the end.\nRearrange: For each card, move the top card of your new pile to the bottom and then add your next highest card on top. This simulates the special revealing process.\nRepeat: Keep doing this for all cards in your sorted deck.\n\n# Code\n```\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n # Sort the deck in decreasing order so we can place the highest cards correctly.\n deck_sorted_desc = sorted(deck, reverse=True)\n ordered_deck = deque()\n\n for card in deck_sorted_desc:\n if len(ordered_deck) > 1:\n ordered_deck.rotate(1)\n ordered_deck.appendleft(card)\n\n return list(ordered_deck)\n\n# Upvote highly appreciated\n```
7
0
['Array', 'Queue', 'Sorting', 'Simulation', 'Python', 'Python3']
6
reveal-cards-in-increasing-order
[C++] 10 Lines - Reverse simulation - Beats all
c-10-lines-reverse-simulation-beats-all-r2vjr
\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& v) {\n sort(v.begin(),v.end());\n deque<int> dq;\n while(!
rexagod
NORMAL
2020-10-02T17:34:35.533270+00:00
2020-10-02T17:34:35.533310+00:00
897
false
```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& v) {\n sort(v.begin(),v.end());\n deque<int> dq;\n while(!v.empty()) {\n int el = v[v.size()-1];\n v.pop_back();\n if(!dq.empty()) {\n int x = dq.back();\n dq.pop_back();\n dq.push_front(x);\n }\n dq.push_front(el);\n }\n return vector<int>(dq.begin(),dq.end());\n }\n};\n```
7
2
['Queue', 'C', 'Simulation']
3
reveal-cards-in-increasing-order
Python - 44 ms - Explained
python-44-ms-explained-by-rowe1227-8ged
The idea here is to reverse the process of playing the cards in order. i.e. move the bottom card to the top of res, then add the highest valued card in the pil
rowe1227
NORMAL
2020-06-15T18:27:47.303647+00:00
2020-06-15T18:29:17.205894+00:00
450
false
The idea here is to reverse the process of playing the cards in order. i.e. move the bottom card to the top of ```res```, then add the highest valued card in the pile to the top of ```res``` and repeat until there are no more cards in the pile. \n\nThat said, we start with the deck sorted (so that the last card played is at the end of the list). We do this because we want to insert the last card played (the highest card) into ```res``` first and because popping from the end of a list is much faster than from the beginning of a list. \n\nThen repeat the process of moving the bottom card of ```res``` to the top of ```res``` and taking the last (highest) card in ```deck``` and placing it on top of ```res```. \n\nBecause we will be appending to the left end of ```res``` (the top of our ordered deck) and popping from the right end, it is more efficient make ```res``` a double ended queue. \n\nHope this helps!\n\n```\nfrom collections import deque\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n deck = sorted(deck)\n \n res = deque()\n while deck:\n if res:\n res.appendleft(res.pop()) #this is the reverse of moving a card from top of deck to bottom of deck\n res.appendleft(deck.pop()) #this is the reverse of playing the card from the top of the deck\n \n return res\n```\n
7
0
[]
0
reveal-cards-in-increasing-order
🗓️ Daily LeetCoding Challenge Day 112|| 🔥 JAVA SOL
daily-leetcoding-challenge-day-112-java-qf1z0
Code\n\npublic class Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n int N = deck.length;\n int[] result = new int[N];\n\n
DoaaOsamaK
NORMAL
2024-04-10T17:43:24.093095+00:00
2024-04-10T17:43:24.093152+00:00
31
false
# Code\n```\npublic class Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n int N = deck.length;\n int[] result = new int[N];\n\n Arrays.sort(deck);\n\n return everyOther(deck, result, 0, 0, false);\n }\n\n private int[] everyOther(int[] deck, int[] result, int indexInDeck, int indexInResult, boolean skip) {\n int N = deck.length;\n\n if (indexInDeck == N) {\n return result;\n }\n\n while (indexInResult < N) {\n if (result[indexInResult] == 0) {\n if (!skip) {\n result[indexInResult] = deck[indexInDeck];\n indexInDeck++;\n }\n skip = !skip;\n }\n indexInResult++;\n }\n\n return everyOther(deck, result, indexInDeck, 0, skip);\n }\n}\n```
6
0
['Java']
0
reveal-cards-in-increasing-order
Clean C++ code | 2 Approches
clean-c-code-2-approches-by-omsl9850-4n8w
Intuition\nBoth approaches aim to solve the problem of revealing cards in increasing order. The first approach achieves this by sorting the deck and then fillin
omsl9850
NORMAL
2024-04-10T07:09:06.545231+00:00
2024-04-10T07:09:06.545248+00:00
441
false
## Intuition\nBoth approaches aim to solve the problem of revealing cards in increasing order. The first approach achieves this by sorting the deck and then filling cards in alternate empty positions, while the second approach simulates the process using a queue.\n\n## Approach\n### Approach 1: Logical\n1. Sort the deck in increasing order.\n2. Initialize an answer vector with all elements as 0.\n3. Iterate through the sorted deck and fill cards in alternate empty positions, ensuring that cards are revealed in increasing order.\n\n### Approach 2: Simulating using Queue\n1. Initialize a queue with indices representing the positions of cards.\n2. Sort the deck in increasing order.\n3. Iterate through the sorted deck and reveal cards in increasing order by popping an index from the queue, assigning the corresponding card from the deck to that index in the answer vector, and then pushing the next index to the back of the queue.\n\n## Complexity\n### Approach 1: Logical\n- Time complexity: O(n log n) due to sorting the deck.\n- Space complexity: O(n) for storing the answer vector.\n\n### Approach 2: Simulating using Queue\n- Time complexity: O(n log n) due to sorting the deck.\n- Space complexity: O(n) for storing the answer vector and the queue.\n\n## Code\n```cpp\n// Approach 1: Logical\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n int n = deck.size();\n sort(begin(deck), end(deck)); // sort\n\n vector<int> ans(n, 0); // Initialize all with 0\n int i = 0; // for deck\n int j = 0; // for ans\n bool skip = false;\n while(i < n){\n if(ans[j] == 0){\n if(skip == false){\n ans[j] = deck[i];\n i++;\n }\n\n skip = !skip; // switch for alternating\n }\n\n j = (j+1) % n;\n }\n\n return ans;\n }\n};\n\n// Approach 2: Simulating using queue\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n int n = deck.size();\n \n queue<int> q; // stores indices\n for(int i=0; i<n; i++){ // initialize with indices\n q.push(i);\n }\n\n sort(begin(deck), end(deck));\n vector<int> ans(n);\n\n for(int i=0; i<n; i++){\n int idx = q.front();\n q.pop();\n\n ans[idx] = deck[i];\n\n if(!q.empty()){\n q.push(q.front());\n q.pop();\n }\n }\n\n return ans;\n }\n};\n```\n![Upvote3.png](https://assets.leetcode.com/users/images/4951092d-59f1-4563-be2a-1f50afb506f4_1712732901.6784816.png)\n> \u2705 Please Upvote \u2B06\n
6
0
['Array', 'Queue', 'Sorting', 'Simulation', 'C++']
0
reveal-cards-in-increasing-order
JAVA Solution Explained in HINDI
java-solution-explained-in-hindi-by-the_-fjrf
https://youtu.be/7lCGkLNVYPs\n\nFor explanation, please watch the above video and do like, share and subscribe the channel. \u2764\uFE0F Also, please do upvote
The_elite
NORMAL
2024-04-10T06:07:53.071610+00:00
2024-04-10T06:07:53.071649+00:00
251
false
https://youtu.be/7lCGkLNVYPs\n\nFor explanation, please watch the above video and do like, share and subscribe the channel. \u2764\uFE0F Also, please do upvote the solution if you liked it.\n\nSubscribe link:- [ReelCoding](https://www.youtube.com/@reelcoding?sub_confirmation=1)\n\nSubscribe Goal:- 400\nCurrent Subscriber:- 307\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[] deckRevealedIncreasing(int[] deck) {\n \n int n = deck.length;\n\n Queue<Integer> queue = new LinkedList<>();\n\n for(int i = 0; i < n; i++) {\n queue.offer(i);\n }\n\n Arrays.sort(deck);\n\n int ans[] = new int[n];\n\n for(int i = 0; i < n; i++) {\n ans[queue.poll()] = deck[i];\n\n queue.offer(queue.poll());\n }\n return ans;\n }\n}\n```
6
0
['Java']
0
reveal-cards-in-increasing-order
Sorting and inserting into every other index
sorting-and-inserting-into-every-other-i-lyme
Intuition\nBlaise Pascal himself talked to me in a vision and gave me this idea.\n\n# Approach\n- Make a sorted copy of the deck. \n- Inserted the sorted copy,
midnightsimon
NORMAL
2024-04-10T01:37:02.734513+00:00
2024-04-10T01:37:02.734531+00:00
969
false
# Intuition\nBlaise Pascal himself talked to me in a vision and gave me this idea.\n\n# Approach\n- Make a sorted copy of the deck. \n- Inserted the sorted copy, starting from the lowest index, into every other index in the answer.\n- `i % n` will keep the index inbounds when i goes out of bounds.\n- I will live stream tomorrow\'s daily problem on twitch (9pm est).\n\n# Complexity\n- Time complexity:\n$$O(n logn)$$ because sorting\n\n\n- Space complexity:\n$$O(n)$$ because saving a copy also keeping track of "already_inserted"\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n\n vector<int> sorted_copy = deck;\n sort(sorted_copy.begin(), sorted_copy.end());\n\n int n = deck.size();\n vector<int> ans(n);\n vector<bool> already_inserted(n, false);\n bool should_insert = true;\n int j = 0;\n for(int i = 0; j < n; i++) {\n i %= n;\n if(should_insert & !already_inserted[i]) {\n already_inserted[i] = true;\n ans[i] = sorted_copy[j++];\n should_insert ^= 1;\n } else if(!already_inserted[i]) {\n should_insert ^= 1;\n }\n }\n\n\n return ans;\n\n \n }\n};\n```
6
0
['C++']
1
reveal-cards-in-increasing-order
🟢Beats 100.00% of users with Java, Easy Solution with Explanation
beats-10000-of-users-with-java-easy-solu-95ti
Keep growing \uD83D\uDE0A\n\n\n---\n\n# Complexity\n\n- Time complexity: O(N log N)\n\n- Space complexity: O(n)\n\n---\n\n# Problem\n\n## Real-world scenario\n\
rahultripathi17
NORMAL
2024-04-10T00:14:32.284068+00:00
2024-04-10T00:21:47.848784+00:00
1,120
false
##### Keep growing \uD83D\uDE0A\n![HOT](https://assets.leetcode.com/users/images/e1474fba-9eec-4656-8896-09d3ee770517_1712708042.6916254.png)\n\n---\n\n# Complexity\n\n- Time complexity: O(N log N)\n\n- Space complexity: O(n)\n\n---\n\n# Problem\n\n## Real-world scenario\n\nImagine you have a deck of cards, where each card has a unique integer written on it. The integers on the cards are represented by the array "deck". Initially, all the cards are placed face down in a single deck.\n\nNow, you\'re tasked with sorting the deck in such a way that when you reveal the cards one by one according to the following steps, the revealed cards are in increasing order:\n\n- Take the top card of the deck, reveal it, and remove it from the deck.\n- If there are still cards left in the deck, take the next top card and put it at the bottom of the deck.\n- Repeat steps 1 and 2 until all cards are revealed.\n\nFinally, return the ordering of the deck that would reveal the cards in increasing order.\n\nSo, in this real-world scenario, you\'re essentially organizing the deck of cards to be revealed in ascending order, following a specific sequence of steps for revealing and reshuffling the deck.\n\n---\n\n# Approach Explanation\n\n### Revealing Deck of Cards in Increasing Order\n- The class `Solution` contains a method `deckRevealedIncreasing` that takes an array `deck` representing a deck of cards and aims to reveal the cards in increasing order.\n- It initializes an array `result` to store the revealed cards.\n- The method sorts the input `deck` array in ascending order using `Arrays.sort()` to ensure the cards are in increasing order.\n\n### Recursive Approach to Reveal Cards\n- The method `revealCards` is a recursive helper method that reveals the cards according to the given pattern.\n- It takes parameters: `deck` (the sorted deck of cards), `result` (array to store revealed cards), `deckIndex` (index to iterate through the deck array), `resultIndex` (index to iterate through the result array), and `skip` (a boolean flag to determine whether to skip revealing a card).\n- The base case of the recursive function is when `deckIndex` equals the number of cards, indicating all cards have been revealed, and it returns the `result` array.\n- Inside the recursive function, it iterates through the `result` array.\n - If the current position in `result` is empty (initialized with 0), it reveals the next card from `deck` at `deckIndex` position.\n - The `skip` flag is toggled to alternate revealing and skipping cards.\n- After updating the `result` array, the function calls itself recursively with updated indices and the `skip` flag until all cards are revealed.\n\n### Calling the Recursive Function\n- The `deckRevealedIncreasing` method initiates the revealing process by calling the `revealCards` method with initial indices and flags.\n- It then returns the resulting array of revealed cards.\n\n### Complexity Analysis\n- Time Complexity: The algorithm sorts the `deck` array with O(n log n) complexity and iterates through the `result` array, resulting in O(n) operations overall, where n is the number of cards in the deck.\n- Space Complexity: The algorithm uses O(n) additional space for the `result` array to store revealed cards, where n is the number of cards in the deck.\n\n---\n\n# Pseudocode\n\n```Javascript []\nStart\nInitialize \'numberOfCards\' to the length of \'deck\'\nInitialize \'result\' as an array of \'numberOfCards\' elements\n\nSort the \'deck\' array in increasing order\n\nReturn the result of calling the revealCards method with arguments (\'deck\', \'result\', 0, 0, false)\n\nrevealCards Method:\n Start\n Initialize \'numberOfCards\' to the length of \'deck\'\n \n If \'deckIndex\' is equal to \'numberOfCards\'\n Return \'result\'\n End\n \n While \'resultIndex\' is less than \'numberOfCards\'\n If \'result[resultIndex]\' is equal to 0\n If \'skip\' is false\n Set \'result[resultIndex]\' to \'deck[deckIndex]\'\n Increment \'deckIndex\' by 1\n End\n Set \'skip\' to the negation of its current value\n End\n Increment \'resultIndex\' by 1\n End\n \n Return the result of calling the revealCards method recursively with arguments (\'deck\', \'result\', \'deckIndex\', 0, \'skip\')\n End\n```\n\n# Code\n\n```java []\nimport java.util.Arrays;\n\npublic class Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n int numberOfCards = deck.length;\n int[] result = new int[numberOfCards];\n\n Arrays.sort(deck);\n\n return revealCards(deck, result, 0, 0, false);\n }\n\n private int[] revealCards(int[] deck, int[] result, int deckIndex, int resultIndex, boolean skip) {\n int numberOfCards = deck.length;\n\n if (deckIndex == numberOfCards) {\n return result;\n }\n\n while (resultIndex < numberOfCards) {\n if (result[resultIndex] == 0) {\n if (!skip) {\n result[resultIndex] = deck[deckIndex];\n deckIndex++;\n }\n skip = !skip;\n }\n resultIndex++;\n }\n\n return revealCards(deck, result, deckIndex, 0, skip);\n }\n}\n```\n----\n> ![VOTE](https://assets.leetcode.com/users/images/8bc25f2b-9256-46ad-a27c-2746a7c529bc_1712670904.6992257.gif)\n\n# *If you have any question, feel free to ask. If you found my solution helpful, Please UPVOTE !* \uD83D\uDE0A
6
0
['Array', 'Queue', 'Sorting', 'Simulation', 'Java']
3
reveal-cards-in-increasing-order
Java Queue w/ comments
java-queue-w-comments-by-carti-cwad
java\n//first sort the deck increasing (so that result will also be increasing)\nArrays.sort(deck);\n//length of deck\nint n = deck.length;\n//queue for our sta
carti
NORMAL
2019-10-29T00:19:28.991583+00:00
2019-10-29T00:19:28.991628+00:00
603
false
```java\n//first sort the deck increasing (so that result will also be increasing)\nArrays.sort(deck);\n//length of deck\nint n = deck.length;\n//queue for our stack of cards\nQueue<Integer> queue = new LinkedList();\n//add all indices of cards to queue\nfor (int i = 0; i < n; i++) queue.offer(i);\n//result array\nint[] res = new int[n];\n//go through each index in deck\nfor (int i : deck) {\n\t//1. take top card of the deck, reveal it, and take it out of the deck\n\tres[queue.poll()] = i;\n\t//if queue isnt empty\n\tif (!queue.isEmpty()) {\n\t\t//2. put the next top card of the deck at the bottom of the deck\n\t\tqueue.offer(queue.poll());\n\t}\n}\n//result\nreturn res;\n```
6
0
['Queue', 'Java']
1
reveal-cards-in-increasing-order
Solution in Python 3 (Deque) (three lines)
solution-in-python-3-deque-three-lines-b-b1yr
```\nclass Solution:\n def deckRevealedIncreasing(self, D: List[int]) -> List[int]:\n \tL, Q, _ = len(D)-1, collections.deque(), D.sort()\n \tfor _ in
junaidmansuri
NORMAL
2019-09-30T08:54:45.655235+00:00
2019-09-30T08:54:45.655268+00:00
1,207
false
```\nclass Solution:\n def deckRevealedIncreasing(self, D: List[int]) -> List[int]:\n \tL, Q, _ = len(D)-1, collections.deque(), D.sort()\n \tfor _ in range(L): Q.appendleft(D.pop()), Q.appendleft(Q.pop())\n \treturn D + list(Q)\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com
6
1
['Queue', 'Python', 'Python3']
1
reveal-cards-in-increasing-order
Java Solution via pattern
java-solution-via-pattern-by-sirwatermel-dufh
\nimport java.util.LinkedList;\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n \n \n /*\n If you look at the
sirwatermelon
NORMAL
2019-08-12T22:54:38.216505+00:00
2019-08-17T01:47:41.057009+00:00
653
false
```\nimport java.util.LinkedList;\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n \n \n /*\n If you look at the ordering of the Example 1, you will notice a pattern after removing the top card (step 1)and placing the next card to the bottom of the deck (step 2)\n \n We can build the solution deck by simply reversing the steps:\n step 1: place the bottom card on top\n \n step 2: place the next card over the card from step 1\n \n [top --- bottom]\n \n Here is the pattern:\n \n [2,13,3,11,5,17,7] <-- place the bottom card on top [13, 3, 11, 5, 17, 7], and then place the next largest on top [2, 13, 3, 11, 5, 17, 7]\n \n [3,11,5,17,7,13]. <-- place the bottom card on top [11, 5, 17, 7, 13], and then place the next largest on top [3, 11, 5, 17, 7, 13]\n \n [5,17,7,13,11]. <-- place the bottom card on top [17, 7, 13, 11], and then place the next largest on top [5, 17, 7, 13, 11]\n \n [7,13,11,17]. <-- place the bottom card on top [13, 11, 17], and then place the next largest on top [7, 13, 11, 17]\n \n [11,17,13]. <-- place the bottom card on top [17, 13], and then place the next largest on top [11, 17, 13]\n \n [13,17]. <-- place the bottom card on top [17], and then place the next largest on top [13, 17]\n \n [17]. <-- start here by adding the largest. This is the bottom card\n\n \n Since this is a series of shifting elements, we can use a queue (with a linked list implementation) so that the cost of combining the reversed step 1 and 2 is constant per element. Therefore, the total runtime for insertion is O(n); however, since we sorted the array, the dominating runtime is O(nlog(n))! You can also use a deque, linked list, etc to simulate this.\n \n */\n \n //sort the array\n Arrays.sort(deck);\n \n \n //Let\'s use a queue!\n \n LinkedList<Integer> queue = new LinkedList<Integer>();\n \n //queue [front, back]\n \n queue.addLast(deck[deck.length - 1]); //add the largest value first\n \n //index goes from len to 0 so we can get values in descending order\n for (int i = deck.length - 2; i >= 0; i --){ \n int val = queue.removeFirst(); //at first, only contains largest value in array\n queue.addLast(val);\n queue.addLast(deck[i]);\n }\n \n for (int i = deck.length - 1; i >= 0; i--){ \n deck[i] = queue.removeFirst(); //insert the values in descending order\n }\n \n return deck;\n \n\n }\n}\n```
6
1
[]
1
reveal-cards-in-increasing-order
C++ solution with iterator that directly generates the indices for the cards
c-solution-with-iterator-that-directly-g-3ddf
This solution seems to be unique in that I directly generate the indices needed for placing the cards into the deck in preparation for the reveal steps.\n\nThe
flarbear
NORMAL
2019-04-27T07:38:28.817697+00:00
2019-04-27T07:38:28.817731+00:00
889
false
This solution seems to be unique in that I directly generate the indices needed for placing the cards into the deck in preparation for the reveal steps.\n\nThe direct generation of the indices allows the main loop that lays out the "reveal" deck to be very simple. The magic of the ```ShuffleIterator``` class will be explained below. Note that the ShuffleIterator is instantiated with only one piece of data - the size of the deck - and it deduces all indices mathematically rather than empirically from observing the evolving deck being constructed or a simulated version of the reveal steps.\n\nThe Solution code:\n\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n int n = deck.size();\n sort(deck.begin(), deck.end());\n vector<int> ret(n);\n ShuffleIterator it(n);\n for (int i = 0; i < n; i++) {\n ret[*it++] = deck[i];\n }\n return ret;\n }\n};\n```\n\n[Side note: I\'m teaching myself C++ so I apologize for any oddities in the code here. Progressing from "Hello World" to implementing an iterator with operator overloading in one lesson may leave a lot to be desired... ;)]\n\n# And now for the magic in the iterator...\n\nThe solutions seem to fall in to 3 main categories:\n1. Reverse simulation. Start with the last card and "undo" the reveal steps one by one as you add new cards. Add the last card, then reverse one step of the reveal - and repeat.\n2. Forward simulation. Notice that the cards are ending up in alternating spots and use a shuffling technique that simulates the insertion process and shuffles cards to the end of the list for later insertion.\n3. Insert a card, skip an empty spot and repeat. The skipping will return to the beginning of the array and use searches to find an empty entry in the deck, skip it and find a second empty entry for the next insertion.\n\nAll 3 of these solutions use a potentially expensive process to determine the next index to add a card. Either they use some sort of queue to recycle cards to the "bottom" of a deck, or they search for unused spots to fill.\n\nIf you look at the way the resulting "to be revealed" deck is constructed you can see a pattern. Basically, alternating entries contain the first few cards, but then it gets a little confusing with the rest of the spots in the deck. Really, the cards keep on alternating - skip a spot, then use a spot - but they do so only in the unused spots and keep wrapping around. I was going to try to draw pictures, but user [@votrubac](https://leetcode.com/votrubac) has already done so in his solution, so you can refer to that to see how the process looks: https://leetcode.com/problems/reveal-cards-in-increasing-order/discuss/201574/C++-with-picture-skip-over-empty-spaces\n\nIf you look at that process, it becomes obvious that the first pass is using every other element, so it is skipping by 2 spots for each card it places. The first pass then uses all of the even spots. On the next pass, it is only looking at the odd spots and it is using every other one of those, so it is jumping by 4 spots each time. When that second pass wraps around, the empty spots are 4 apart and it uses every 8th one to place a card. Then every other 8th spot is a jump of 16, then every other 16th spot is a jump of 32, and so on.\n\nThe only complication is when you wrap around, which spot do you use next? The answer depends on whether you wrapped around on a "skip this spot" step, or on a "use this next one to place the next card" step. If the spot you are going to "skip" is in the end of the array before you wrap, then the spot you use when you wrap around to place a card will be the first unused spot. If the spot you are going to skip is off the end of the array, then you wrap around, skip the first unused spot, and use the next one. Either way, for the next pass you will be jumping twice as far.\n\nTo implement this and to demonstrate that the iteration process can be computed without scanning the list of remaining cards or remaining empty slots, I implemented a numerical iterator ```ShuffleIterator``` and use it to make the card placement loop be a 1-line for loop. The iteration process is:\n\nInitial conditions:\n- ```index``` starts at 0, it tracks the spot we plan to insert the next card into\n- ```bump``` starts at 2 to alternate array spots, it is the distance between spots we plan to insert cards into\n- ```restart``` starts at 1, it tracks the first unused spot for the next pass - which is 1 because we used 0,2,4,6,... on the first pass\n- ```end``` is the only input and it is the size of the array\n\nTo increment the index:\n- Bump the index by the current bump amount - ```index += bump```\n- If the index overflowed the end of the array ```(index >= end)```, wrap around.\n - Determine if the wrap was "before the skipped spot" or between the skipped and filled spots ```(index - bump/2 < n)```\n - If only the filled spot is wrapped, use the existing ```restart``` spot for the next pass, and increment it by ```bump``` so it points at the next one we will skip\n - If both the skipped and filled slots wrap, then leave the ```restart``` pointer where it was (because we are skipping it again) and use the next slot after it - ```index = restart + bump```\n - (Also, for that case we have to deal with the case where the last remaining spot causes a second overflow - in that case we reset the ```index = restart```\n - double the bump amount for the new pass - ```bump *= 2```\n\nAnd now for the (hopefully not too ugly) ```ShuffleIterator``` code:\n\n```\nclass ShuffleIterator : public iterator<input_iterator_tag, int>\n{\n int index, bump, end, restart;\npublic:\n ShuffleIterator(int n) : index(0), bump(2), end(n), restart(1) {}\n ShuffleIterator(const ShuffleIterator& si) : index(si.index), bump(si.bump), end(si.end), restart(si.restart) {}\n ShuffleIterator& operator++() {\n index += bump;\n if (index >= end) {\n if (index - bump/2 < end) {\n index = restart;\n restart += bump;\n } else {\n index = restart + bump;\n if (index >= end) index = restart;\n }\n bump *= 2;\n }\n return *this;\n }\n ShuffleIterator operator++(int) {\n ShuffleIterator tmp(*this); operator++(); return tmp;\n }\n int operator*() { return index; }\n};\n```
6
0
[]
4
reveal-cards-in-increasing-order
Java find the right position
java-find-the-right-position-by-wangzi61-27x5
\n1. Sort the array.\n2. Start from the smallest element, find the right place.\n\ta. Maintain a Queue to store all available indices.\n\tb. Skip one available
wangzi6147
NORMAL
2018-12-02T04:05:17.686225+00:00
2018-12-02T04:05:17.686298+00:00
936
false
\n1. Sort the array.\n2. Start from the smallest element, find the right place.\n\ta. Maintain a Queue to store all available indices.\n\tb. Skip one available index, then put the element to the next available index.\n\nTime complexity: `O(NlogN)`\n\n```\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n int n = deck.length;\n int[] result = new int[n];\n Arrays.sort(deck);\n Queue<Integer> q = new LinkedList<>(); // Queue for all available indices\n for (int i = 0; i < n; i++) {\n q.offer(i);\n }\n int p = q.poll();\n for (int i = 0; i < n; i++) {\n result[p] = deck[i];\n if (i < n - 1) {\n q.offer(q.poll()); // Skip one available index\n p = q.poll(); // Next available index\n }\n }\n return result;\n }\n}\n```
6
3
[]
3
reveal-cards-in-increasing-order
✅ One Line Solution
one-line-solution-by-mikposp-oe1b
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1.1 - Basic Simulation\nTime complexity:
MikPosp
NORMAL
2024-04-10T10:02:14.894677+00:00
2024-04-10T15:14:57.835152+00:00
737
false
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1.1 - Basic Simulation\nTime complexity: $$O(n*log(n))$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def deckRevealedIncreasing(self, d: List[int]) -> List[int]:\n return (q:=deque(range(l:=len(d))),r:=[0]*l,any(setitem(r,q.popleft(),v) or q.rotate(-1) for v in sorted(d)))[1]\n```\n\n# Code #1.2 - Unwrapped\n```\nclass Solution:\n def deckRevealedIncreasing(self, d: List[int]) -> List[int]:\n q, r = deque(range(l:=len(d))), [0]*l\n for v in sorted(d):\n r[q.popleft()] = v\n q.rotate(-1)\n\n return r\n```\n\n# Code #1.3 - List Instead of Queue\nTime complexity: $$O(n^2)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def deckRevealedIncreasing(self, d: List[int]) -> List[int]:\n return (q:=[*range(l:=len(d))],r:=[0]*l,all((setitem(r,q[0],v),q:=q[2:]+q[1:2]) for v in sorted(d)))[1]\n```\n\n# Code #2.1 (seen [here](https://leetcode.com/problems/reveal-cards-in-increasing-order/solutions/5001419/coded-for-simplicity-5-lines-of-code-python/))\nTime complexity: $$O(n*log(n))$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def deckRevealedIncreasing(self, d: List[int]) -> List[int]:\n return (q:=deque(),any(q.rotate() or q.appendleft(v) for v in sorted(d)[::-1]))[0]\n```\n\n# Code #2.2 - Unwrapped\n```\nclass Solution:\n def deckRevealedIncreasing(self, d: List[int]) -> List[int]:\n q = deque()\n for v in sorted(d)[::-1]:\n q.rotate()\n q.appendleft(v)\n\n return q\n```\n\n# Code #3 - Recursive Calculation of Indices\nTime complexity: $$O(n^2)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def deckRevealedIncreasing(self, d: List[int]) -> List[int]:\n return any(map(setitem,repeat(r:=[0]*len(d)),(f:=lambda q:q and q[:1]+f(q[2:]+q[1:2]))([*range(len(d))]),sorted(d))) or r\n```\n\n# Code #4.1 - Concise\nTime complexity: $$O(n^2)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def deckRevealedIncreasing(self, d: List[int]) -> List[int]:\n return reduce(lambda q,v:[v]+q[-1:]+q[:-1],sorted(d)[::-1],[])\n```\n\n# Code #4.2 - Unwrapped\n```\nclass Solution:\n def deckRevealedIncreasing(self, d: List[int]) -> List[int]:\n q = []\n for v in sorted(d)[::-1]:\n q=[v]+q[-1:]+q[:-1]\n\n return q\n```\n\n(Disclaimer 2: all code above is just a product of fantasy, it is not claimed to be pure impeccable oneliners - please, remind about drawbacks only if you know how to make it better. PEP 8 is violated intentionally)
5
1
['Array', 'Queue', 'Sorting', 'Simulation', 'Python', 'Python3']
1
reveal-cards-in-increasing-order
[C++ / Go] Simulate the process for revealing order - O(nlogn) time + O(n) space solution
c-go-simulate-the-process-for-revealing-ydzx0
Approach\n- Sort the deck initially.\n- Simulate the process of revealing using Queue to determine the order in which cards are revealed.\n- Assign the cards fr
mikazuki4712
NORMAL
2024-04-10T02:13:02.106270+00:00
2024-04-10T07:40:10.122461+00:00
633
false
# Approach\n- Sort the deck initially.\n- Simulate the process of revealing using Queue to determine the order in which cards are revealed.\n- Assign the cards from the sorted deck according to the revealing order.\n\n# Complexity\n- Time complexity: $O(nlogn)$\n- Space complexity: $O(n)$\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n int n = deck.size();\n sort(deck.begin(), deck.end());\n \n vector<int> res(n, 0);\n queue<int> q;\n for (int i = 0; i < n; i++)\n q.push(i);\n\n for (int i = 0; i < n; i++) {\n int u = q.front();\n q.pop();\n\n res[u] = deck[i];\n\n if (!q.empty()) {\n q.push(q.front());\n q.pop();\n }\n }\n\n return res;\n }\n};\n```\n```Go []\nfunc deckRevealedIncreasing(deck []int) []int {\n\tn := len(deck)\n\tsort.Ints(deck)\n\n\tres := make([]int, n)\n\tqueue := make([]int, n)\n\n\tfor i := range queue {\n\t\tqueue[i] = i\n\t}\n\n\tfor _, card := range deck {\n\t\tidx := queue[0]\n\t\tqueue = queue[1:]\n\t\tres[idx] = card\n\n\t\tif len(queue) > 0 {\n\t\t\tqueue = append(queue, queue[0])\n\t\t\tqueue = queue[1:]\n\t\t}\n\t}\n\n\treturn res\n}\n```
5
0
['Queue', 'Sorting', 'Simulation', 'C++', 'Go']
4
reveal-cards-in-increasing-order
Beginner friendly [Python/JavaScript/Java] Solution
beginner-friendly-pythonjavascriptjava-s-jg1a
Python\n\nclass Solution(object):\n def deckRevealedIncreasing(self, deck):\n deck.sort(reverse=True)\n res = []\n for i in deck:\n
HimanshuBhoir
NORMAL
2022-10-01T03:58:48.582938+00:00
2022-10-01T03:58:48.582975+00:00
1,171
false
**Python**\n```\nclass Solution(object):\n def deckRevealedIncreasing(self, deck):\n deck.sort(reverse=True)\n res = []\n for i in deck:\n if len(res) > 0:\n res.insert(0, res.pop())\n res.insert(0, i)\n return res\n```\n**JavaScript**\n```\nvar deckRevealedIncreasing = function(deck) {\n deck.sort((a,b) => b-a)\n let res = []\n for(let i of deck){\n if(res.length > 0) res.unshift(res.pop())\n res.unshift(i)\n }\n return res\n};\n```\n**Java**\n```\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck);\n Queue<Integer> q = new LinkedList<>();\n for(int i=deck.length-1; i>=0; i--){\n if(q.size() > 0) q.add(q.poll());\n q.add(deck[i]);\n }\n int[] res = new int[deck.length];\n for(int i=deck.length-1; i>=0; i--)\n res[i] = q.poll();\n return res;\n }\n}\n```
5
0
['Python', 'Java', 'JavaScript']
0
reveal-cards-in-increasing-order
Simple C++ solution
simple-c-solution-by-caspar-chen-hku-lb9z
\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n int n = deck.size();\n queue<int> inds;\n sort(d
caspar-chen-hku
NORMAL
2020-05-22T15:31:31.866422+00:00
2020-05-22T15:31:31.866460+00:00
330
false
```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n int n = deck.size();\n queue<int> inds;\n sort(deck.begin(), deck.end());\n for (int i=0; i<n; i++){\n inds.push(i);\n }\n vector<int> result(n, 0);\n for (int i=0; i<n; i++){\n result[inds.front()] = deck[i];\n inds.pop();\n inds.push(inds.front());\n inds.pop();\n }\n return result;\n }\n};\n```
5
0
[]
3
reveal-cards-in-increasing-order
Python3, Simple 4 Lines with explanation, 99%, O(1) constant space
python3-simple-4-lines-with-explanation-sk0fq
In-place Solution\n\nclass Solution:\n def deckRevealedIncreasing(self, deck):\n deck.sort()\n for i in range(len(deck) - 2, 0, -1):\n
jimmyyentran
NORMAL
2019-01-18T00:50:34.565788+00:00
2019-01-18T00:50:34.565842+00:00
843
false
# In-place Solution\n```\nclass Solution:\n def deckRevealedIncreasing(self, deck):\n deck.sort()\n for i in range(len(deck) - 2, 0, -1):\n deck.insert(i, deck.pop())\n return deck\n```\nTime : *O(n^2)*\nSpace: *O(1)*\nNote: This solution, though more elegant, is slower than the deque solution below since `insert` in Python is an *O(n)* operation and we need to insert `n` times, hence *O(n^2)* time complexity.\n#### Explanation:\nConsider we\'ve sorted the array in-place. Using the example, it would look like this:\n`[2, 3, 5, 7, 11, 13, 17]`\nStarting from the second to last index `i`, we `pop` the array and insert it at the `i` position.\n```\n[2, 3, 5, 7, 11, 13, 17]\n\t ^\n[2, 3, 5, 7, 11, 13] pop() -> 17\n\t ^\n[2, 3, 5, 7, 11, 17, 13] insert()\n\t ^\n```\nAfter each iteration, index `i` is decreased until it reaches index 1\n```\n[2, 3, 5, 7, 13, 11, 17]\n\t ^\n[2, 3, 5, 17, 7, 13, 11]\n\t ^\n[2, 3, 11, 5, 17, 7, 13]\n\t ^\n[2, 13, 3, 11, 5, 17, 7]\n\t^\n```\n# Deque Solution\n```\nimport collections\nclass Solution:\n def deckRevealedIncreasing(self, deck):\n deck.sort()\n if len(deck) < 2: return deck\n dq = collections.deque([deck.pop()])\n dq.appendleft(deck.pop())\n while len(deck):\n dq.extendleft((dq.pop(), deck.pop()))\n return list(dq)\n```\nTime : *O(n log n)* to sort\nSpace: *O(n)*
5
0
[]
1
reveal-cards-in-increasing-order
Beats 100% || Easy to Understand || With Explanation 🔥
beats-100-easy-to-understand-with-explan-bm29
Please Upvote if you find the solution helpful.\n\n\n\n\n\n---\n\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requi
dhruvgaba
NORMAL
2024-04-10T10:16:24.517610+00:00
2024-04-10T23:13:14.364060+00:00
53
false
Please **Upvote** if you find the solution helpful.\n\n![LeetCode.png](https://assets.leetcode.com/users/images/9e833cb5-307b-4b98-a464-6dd0038921ce_1712743722.8313909.png)\n\n\n\n---\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires us to give an ordering of the deck that would reveal cards in increasing order, when they are revealed according to the order mentioned in the question. The solution follows a systematic approach to achieve the desired order by iterating through the sorted deck and placing the cards in the proper positions.\n\n\n---\n\n\n\n# Approach 1(Without Recursion)\n<!-- Describe your approach to solving the problem. -->\n1. Sort the input deck array.\n2. Initialize an array ans[] to store the revealed cards.\n3. Use pointers i and j to track deck and result array positions.\n4. Use a boolean variable skip to toggle between revealing and skipping cards in the result array.\n5. Iterate through the sorted deck:\n - If the current position in ans[] is empty, reveal the card from the deck.\n - Toggle between revealing and skipping cards using a boolean variable.\n6. Return the result array.\n\n\n---\n\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n---\n\n\n\n# Code\n```\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck);\n int ans[]=new int[deck.length];\n int i=0,j=0;\n boolean skip=false;\n while(i<deck.length){\n j=0;\n while(j<ans.length){\n if(ans[j]==0){\n if(!skip){\n ans[j]=deck[i];\n i++;\n }\n skip=!skip;\n }\n j++;\n }\n }\n return ans;\n }\n}\n```\n\n\n---\n\n\n---\n\n\n\n# Approach 2(With Recursion)\n<!-- Describe your approach to solving the problem. -->\n1. **Sort the deck:** First, sort the deck array in increasing order.\n2. **Initialize result array:** Create an empty array ans[] of the same length as the deck array to store the revealed cards.\n3. **Call the reveal method recursively:** Start the recursion by calling the reveal method with initial parameters.\n4. **Reveal cards recursively:** In the reveal method, iterate through the ans[] array and fill in the cards from the sorted deck based on the given pattern. \n5. Use a boolean variable skip to toggle between revealing and skipping cards in the result array.\n6. Use recursion to continue revealing cards until all cards are revealed.\n7. **Return the result array:** Once all cards are revealed, return the result array.\n\n\n---\n\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n---\n\n\n# Code\n```\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck);\n int ans[]=new int[deck.length];\n return reveal(deck,ans,0,0,false);\n }\n public static int[] reveal(int[] deck, int ans[], int ansIdx, int deckIdx, boolean skip){\n int n=deck.length;\n if(deckIdx==n){\n return ans;\n }\n while(ansIdx<n){\n if(ans[ansIdx]==0){\n if(!skip){\n ans[ansIdx]=deck[deckIdx];\n deckIdx++;\n }\n skip=!skip;\n }\n ansIdx++;\n }\n return reveal(deck,ans,0,deckIdx,skip);\n }\n}\n```\n\n---\n\n
4
0
['Array', 'Recursion', 'Queue', 'Sorting', 'Simulation', 'Java']
1
reveal-cards-in-increasing-order
✅Very Easy Solution🔥✅||Beginner Friendly✅🔥|| Explained🔥
very-easy-solutionbeginner-friendly-expl-98v2
Intuition\n\n\n1. Sorting the Deck: The first step is to sort the deck of cards in increasing order using Arrays.sort(deck);. This ensures that the cards are in
siddhesh11p
NORMAL
2024-04-10T08:19:39.021446+00:00
2024-04-10T08:19:39.021469+00:00
172
false
# Intuition\n\n\n1. **Sorting the Deck**: The first step is to sort the deck of cards in increasing order using `Arrays.sort(deck);`. This ensures that the cards are in the desired order for the revealing process.\n\n2. **Initializing Result Array**: An array `result` of the same length as the deck is created to store the revealed cards. Initially, all elements in `result` are set to 0.\n\n3. **Iterative Revealing Process**: The revealing process is carried out using a while loop that continues until all cards are revealed (`i < n`). Inside the loop:\n - **Skipping Cards**: The variable `skip` is used to determine whether to skip placing a card in the `result` array.\n - **Placing Cards**: If `skip` is false, the next card from the sorted deck (`deck[i]`) is placed in the `result` array at position `j`, and `i` is incremented to move to the next card in the deck.\n - **Toggling Skip**: After placing a card or skipping, `skip` is toggled to alternate between skipping and placing cards.\n - **Updating Index**: The index `j` is updated using `(j+1)%n`, ensuring that it cycles through the positions in the `result` array. This handles cases where cards need to be placed in previously skipped positions.\n\n4. **Returning Result**: Once all cards are revealed and placed in the `result` array, the array is returned as the output of the function.\n\n\n# Complexity\n- Time complexity:\n$$O(nlogn)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n\n Arrays.sort(deck);\n int n = deck.length;\n int []result= new int[n];\n int i = 0;\n int j = 0;\n boolean skip = false;\n \n\n while(i<n)\n {\n if(result[j]==0)\n {\n if(skip==false)\n {\n result[j]=deck[i];\n i++;\n }\n\n skip = !skip;\n\n }\n j = (j+1)%n;\n }\n return result;\n }\n}\n```
4
0
['Array', 'Queue', 'Sorting', 'Simulation', 'Java']
1
reveal-cards-in-increasing-order
Output Reversing Approach✅ | 99.63%🔥| DRY Run 🎯| Simple (8 lines) to understand💯Explained | Array
output-reversing-approach-9963-dry-run-s-nrp4
\n# Intuition\nsimple and straightforward, We are essentially reversing the process of revealing the cards to obtain the desired output. \n\nInitially, the deck
Prathamesh18X
NORMAL
2024-04-10T04:57:59.015520+00:00
2024-04-10T10:29:29.639778+00:00
419
false
\n# Intuition\nsimple and straightforward, We are essentially reversing the process of revealing the cards to obtain the desired output. \n\nInitially, the deck is sorted in `descending` order . Then, we reverse `b -> a` the steps to reconstruct the original output, its very very very simple , short , effective\uD83D\uDCA1 appproch\uD83D\uDCAF\n\nDont forget to upvote\u2B06\uFE0F ....!!!!!\uD83E\uDD72\n\n# Code \uD83C\uDFAF\n```javascript []\nvar deckRevealedIncreasing = function(deck) {\n deck.sort((a,b)=>b-a)\n var result = []\n for(let card of deck){\n if(result.length){\n result.unshift(result.pop())\n }\n result.unshift(card)\n }\n return result\n};\n```\n```cpp []\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(std::vector<int>& deck) {\n sort(deck.begin(), deck.end(), std::greater<int>());\n vector<int> result;\n for (int card : deck) {\n if (!result.empty()) {\n result.insert(result.begin(), result.back());\n result.pop_back();\n }\n result.insert(result.begin(), card);\n }\n return result;\n }\n};\n```\n```java []\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck);\n LinkedList<Integer> result = new LinkedList<>();\n for (int i = deck.length - 1; i >= 0; i--) {\n if (!result.isEmpty()) {\n result.addFirst(result.removeLast());\n }\n result.addFirst(deck[i]);\n }\n return result.stream().mapToInt(Integer::intValue).toArray();\n }\n}\n```\n```python []\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n deck.sort(reverse=True)\n result = deque()\n for card in deck:\n if result:\n result.appendleft(result.pop())\n result.appendleft(card)\n return list(result)\n```\n\n```kotlin []\nclass Solution {\n fun deckRevealedIncreasing(deck: IntArray): IntArray {\n deck.sortDescending()\n val result = mutableListOf<Int>()\n for (card in deck) {\n if (result.isNotEmpty()) {\n result.add(0, result.removeAt(result.size - 1))\n }\n result.add(0, card)\n }\n return result.toIntArray()\n }\n}\n\n```\n```ruby []\nclass Solution\n def deck_revealed_increasing(deck)\n deck.sort!.reverse!\n result = []\n deck.each do |card|\n unless result.empty?\n result.unshift(result.pop)\n end\n result.unshift(card)\n end\n result\n end\nend\n```\n\n\n# Approach \u2600\uFE0F\n1. **Sort the deck in descending order**: This step sorts the deck in descending order, ensuring that the largest cards are revealed first.\n \n2. **Iterate through the sorted deck**:\n \n - For each card in the sorted deck:\n - If the `result` array is not empty, move the last card in the `result` array to the front.\n - Add the current card to the front of the `result` array.\n3. **Return the final `result` array**: Once all cards have been processed, return the final `result` array, which represents the ordering of cards that would reveal them in increasing order.\n\n# DRY Run \uD83D\uDD25\n\n\n| Iteration | `deck` (after sorting) | `result` | Operation |\n|-----------|-------------------------|----------|------------------------------|\n| Initial | [17, 13, 11, 7, 5, 3, 2]| [] | |\n| 1 | [17, 13, 11, 7, 5, 3, 2]| [17] | Add 17 to the result |\n| 2 | [13, 11, 7, 5, 3, 2] | [13, 17] | Remove the top card 17, move it to the end, and add 13 to the front |\n| 3 | [11, 7, 5, 3, 2] | [11, 17, 13] | Add 11 to the front remove 13 to back |\n| 4 | [7, 5, 3, 2] | [7, 13, 11, 17] | Remove the top card 11, move it to the back, and add 7 to the front |\n| 5 | [5, 3, 2] | [5, 17, 7, 13, 11] | Add 5 to the front |\n| 6 | [3, 2] | [3, 11, 5, 17, 7, 13] | Remove the top card, move it to the front, and add 3 to the front |\n| 7 | [2] | [2, 13, 3, 11, 5, 17, 7] | Add 2 to the front |\n\nThe final result is `[2, 13, 3, 11, 5, 17, 7]`.\n\n# Complexity\n- Time complexity :`O(n.logn)`\n\n- Space complexity :`O(n)`\n\n
4
0
['Array', 'Queue', 'Sorting', 'Simulation', 'Python', 'C++', 'Java', 'Ruby', 'Kotlin', 'JavaScript']
1
reveal-cards-in-increasing-order
Time Complexity : O(NlogN) Space Complexity : O(N) [Diagrammatic Explanation]
time-complexity-onlogn-space-complexity-7xjvw
Intuition & Approach\n\n\n\n# Complexity\n- Time complexity: O( N log( N ) ), where N is the size of array deck [ ]\n\n- Space complexity: O( N ) : Auxiliary Sp
soyama_hakuji
NORMAL
2024-04-10T04:17:04.645483+00:00
2024-04-10T04:17:04.645517+00:00
311
false
# Intuition & Approach\n![potd.png](https://assets.leetcode.com/users/images/46cf2d4d-8382-4072-9e26-14ec8e20cd8e_1712722569.597676.png)\n\n\n# Complexity\n- Time complexity: O( N log( N ) ), where N is the size of array deck [ ]\n\n- Space complexity: O( N ) : Auxiliary Space\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n vector<int>res(deck.size(),0);\n sort(deck.begin(), deck.end());\n int i = 0, j=0, k=0;\n while(j<deck.size()){\n if(res[i%deck.size()]==0 && k==0){\n res[i%deck.size()]=deck[j++];\n k=1;\n }else if(res[i%deck.size()] && k==1){\n k=1;\n } else k=0;\n i++;\n }\n return res;\n }\n};\n```
4
0
['C++']
3
reveal-cards-in-increasing-order
C++ || Queue || Faster than 100%
c-queue-faster-than-100-by-abhijeet5000k-y8zi
\n\n# Code\n\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.begin(),deck.end());\n int n=deck
abhijeet5000kumar
NORMAL
2024-04-10T00:17:49.246693+00:00
2024-04-10T00:17:49.246726+00:00
754
false
![Screenshot 2024-04-10 054625.png](https://assets.leetcode.com/users/images/6952fb87-5504-4410-8cca-32eb3ecc2957_1712708229.4475226.png)\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.begin(),deck.end());\n int n=deck.size(),j=(deck.size()+1)/2;\n vector<int> ans(n);\n queue<int> q;\n\n for(int i=0;i<n;i++){\n if(i%2==0) {ans[i]=deck[i/2];}\n else q.push(i);\n }\n\n if(n%2!=0){\n q.push(q.front());\n q.pop();\n }\n\n while(!q.empty()){\n ans[q.front()]=deck[j++];\n q.pop();\n q.push(q.front());\n q.pop();\n }\n\n return ans;\n }\n};\n```
4
0
['Array', 'Queue', 'Simulation', 'C++']
3
reveal-cards-in-increasing-order
✔️✔️Simple Easy 🧨🧨Approach Java🔥🔥💣💣💣💣🔥🔥
simple-easy-approach-java-by-abinayaprak-2p7d
Intuition\n Describe your first thoughts on how to solve this problem. \nQueue concept is utilized.\n\n# Approach\n Describe your approach to solving the proble
Abinayaprakash
NORMAL
2024-04-10T00:12:21.803966+00:00
2024-04-10T02:49:50.695740+00:00
370
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nQueue concept is utilized.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sort the array of deck.\n2. Create a the array and push the elements from the index from the queue.\n3. add the poll element again to the queue.\n4. return answer;\n![upvote.PNG](https://assets.leetcode.com/users/images/d958145b-513b-43cb-87b5-ccdca992599e_1712707934.4953818.png)\n\n\n# Code\n```\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n int n=deck.length;\n Arrays.sort(deck);\n Queue<Integer> q=new LinkedList<>();\n for(int i=0;i<n;i++){\n q.add(i);\n }\n int[] res=new int[n];\n for(int i=0;i<n;i++){\n res[q.poll()]=deck[i];\n q.add(q.poll());\n }\n return res;\n \n }\n}\n```
4
0
['Array', 'Queue', 'Sorting', 'Simulation', 'Java']
1