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
binary-tree-zigzag-level-order-traversal
Binary Tree Zigzag Level Order Traversal [C++]
binary-tree-zigzag-level-order-traversal-g2x2
IntuitionThe problem involves traversing a binary tree in a zigzag (alternating) order, level by level. This can be thought of as a variation of the standard le
moveeeax
NORMAL
2025-01-26T04:19:53.400161+00:00
2025-01-26T04:19:53.400161+00:00
1,911
false
# Intuition The problem involves traversing a binary tree in a zigzag (alternating) order, level by level. This can be thought of as a variation of the standard level-order traversal with the additional requirement of reversing the order of nodes at alternate levels. # Approach 1. **Use a Queue for BFS Traversal**: - Perform a standard breadth-first search (BFS) using a queue to traverse the tree level by level. 2. **Track Direction**: - Use a boolean variable `leftToRight` to alternate the order of node insertion for each level. - If `leftToRight` is `true`, append nodes left to right. Otherwise, append nodes right to left. 3. **Reverse Nodes for Zigzag**: - Depending on the direction, either insert nodes directly into the result vector or insert them in reverse order for that level. # Complexity - **Time Complexity**: $$O(n)$$, where \(n\) is the number of nodes in the tree, as each node is processed exactly once. - **Space Complexity**: $$O(w)$$, where \(w\) is the maximum width of the tree, which is the largest number of nodes at any level. This space is used by the queue during BFS. # Code ```cpp class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { if (!root) return {}; vector<vector<int>> result; queue<TreeNode*> q; q.push(root); bool leftToRight = true; while (!q.empty()) { int levelSize = q.size(); vector<int> level(levelSize); for (int i = 0; i < levelSize; ++i) { TreeNode* node = q.front(); q.pop(); int index = leftToRight ? i : (levelSize - 1 - i); level[index] = node->val; if (node->left) q.push(node->left); if (node->right) q.push(node->right); } leftToRight = !leftToRight; result.push_back(level); } return result; } }; ```
11
0
['C++']
0
binary-tree-zigzag-level-order-traversal
[C++] [Using DEQUE] Runtime: 0 ms,Memory Usage: 12.2 MB.
c-using-deque-runtime-0-msmemory-usage-1-ildw
\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0)
gs_panwar
NORMAL
2021-05-31T10:45:16.543266+00:00
2021-05-31T10:45:38.452989+00:00
599
false
```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>> ans;\n if(!root)\n return ans;\n deque<TreeNode*> dq;\n dq.push_back(root);\n bool isLTR = true;\n while(!dq.empty()) {\n int n = dq.size();\n vector<int> currLevel;\n if(isLTR) {\n isLTR = false;\n for(int i=0;i<n;++i) {\n auto curr = dq.front();\n dq.pop_front();\n currLevel.push_back(curr->val);\n if(curr->left)\n dq.push_back(curr->left);\n if(curr->right)\n dq.push_back(curr->right);\n }\n } else {\n isLTR = true;\n for(int i=0;i<n;++i) {\n auto curr = dq.back();\n dq.pop_back();\n currLevel.push_back(curr->val);\n if(curr->right)\n dq.push_front(curr->right);\n if(curr->left)\n dq.push_front(curr->left);\n }\n }\n ans.push_back(currLevel);\n }\n return ans;\n }\n};\n```
11
0
['Queue', 'C']
0
binary-tree-zigzag-level-order-traversal
Easy to understand C++ 10 liner (no reverse used)
easy-to-understand-c-10-liner-no-reverse-9dbm
Idea\nAll you have to do is do the standard bfs(with two stacks instead) with two adjustments -\n\n1) instead of dequeueing from a queue, pop() from our first s
numbart
NORMAL
2020-10-04T01:52:53.950921+00:00
2020-10-04T02:05:36.947842+00:00
2,295
false
**Idea**\nAll you have to do is do the standard bfs(with two stacks instead) with two adjustments -\n\n1) instead of dequeueing from a queue, pop() from our first stack pointer. Simmilarly instead of enqueueing push to our second stack pointer.\n2) In queue you will push in left child then right child in every level. Here we alternately first push right and left (why? because you want to have level two in reverse order), then in second iteration left and right and so on.\n\nAt the end of each level just swap the stack pointers before moving to next level.\n\nI tried to keep it simple for you, hope I was able to do that. If I missed anything trying to do so, let me know in the comments would be happy to help.\n\n**Code**\n```cpp\n\t#define tn TreeNode\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>> ans; if(!root) return ans;\n stack<tn*> a, b;\n stack<tn*> *stk1 = &a, *stk2 = &b; a.push(root);\n while(!stk1->empty()){\n ans.push_back(vector<int> (0));\n while(!stk1->empty()){\n tn *cur = stk1->top();\n stk1->pop();\n ans.back().push_back(cur->val);\n if(stk1 != &b && cur->left) stk2->push(cur->left);\n if(cur->right)stk2->push(cur->right);\n if(stk1 == &b && cur->left) stk2->push(cur->left);\n }\n swap(stk1, stk2);\n }\n return ans;\n }\n```
11
1
['Stack', 'Breadth-First Search', 'C', 'C++']
1
binary-tree-zigzag-level-order-traversal
Fastest zigzag: 0 ms Beats 100.00% Analyze Complexity Memory 4.45 MB Beats 95.97%
fastest-zigzag-0-ms-beats-10000-analyze-c0qzx
ApproachRecursive approachComplexity Time complexity: 0 ms Beats 100.00% Space complexity: 4.45 MB Beats 95.97% Code
sushilmaxbhile
NORMAL
2025-04-01T04:57:40.986370+00:00
2025-04-01T04:57:40.986370+00:00
539
false
# Approach Recursive approach # Complexity - Time complexity: 0 ms Beats 100.00% - Space complexity: 4.45 MB Beats 95.97% # Code ```golang [] import "slices" /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func zigzagLevelOrder(root *TreeNode) [][]int { level, levelSlice, zigZagSlice := 0, [][]int{}, [][]int{} levelWiseOrder(root, &level, &levelSlice) streight := true for _, v := range levelSlice { if streight { streight = false } else { slices.Reverse(v) streight = true } zigZagSlice = append(zigZagSlice, v) } return zigZagSlice } func levelWiseOrder(root *TreeNode, level *int, levelSlice *[][]int) { if root == nil { return } if len(*levelSlice) < (*level) + 1 { *levelSlice = append(*levelSlice, []int{}) } (*levelSlice)[*level] = append((*levelSlice)[*level], root.Val) *level += 1 levelWiseOrder(root.Left, level, levelSlice) levelWiseOrder(root.Right, level, levelSlice) *level -= 1 } ```
10
0
['Go']
0
binary-tree-zigzag-level-order-traversal
[JAVA] easy solution with level order traversal using queue.
java-easy-solution-with-level-order-trav-g7tr
I traverse by level using queue.\nFor even level elements are reversed and the other uses original order.\n\n\nclass Solution {\n public static List<List<Int
duck67
NORMAL
2020-02-07T10:01:20.648111+00:00
2020-02-07T10:06:50.626734+00:00
999
false
I traverse by level using queue.\nFor even level elements are reversed and the other uses original order.\n\n```\nclass Solution {\n public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> res = new ArrayList<>();\n if(root == null) return res;\n \n Queue<TreeNode> queue = new LinkedList<>();\n queue.offer(root);\n int level = 0; // the number of level !!\n while(!queue.isEmpty()) {\n List<Integer> list = new ArrayList<>();\n int size = queue.size();\n for(int i=0; i<size; i++) {\n TreeNode node = queue.poll();\n list.add(node.val);\n if(node.left != null) queue.offer(node.left);\n if(node.right != null) queue.offer(node.right);\n }\n if(level % 2 == 1) { //reverse data\n Collections.reverse(list);\n }\n res.add(list);\n\n level++; // after traverse all member of element in same level, go next level\n }\n return res;\n }\n}\n```
10
0
['Queue', 'Java']
1
binary-tree-zigzag-level-order-traversal
C# queue
c-queue-by-bacon-wst8
\npublic class Solution {\n public IList<IList<int>> ZigzagLevelOrder(TreeNode root) {\n var result = new List<IList<int>>();\n if (root == nul
bacon
NORMAL
2019-05-04T05:15:13.404144+00:00
2019-05-04T05:15:13.404174+00:00
895
false
```\npublic class Solution {\n public IList<IList<int>> ZigzagLevelOrder(TreeNode root) {\n var result = new List<IList<int>>();\n if (root == null) return result;\n\n var queue = new Queue<TreeNode>();\n queue.Enqueue(root);\n\n while (queue.Any()) {\n var size = queue.Count;\n var oneResult = new List<int>();\n for (int s = 0; s < size; s++) {\n var cur = queue.Dequeue();\n oneResult.Add(cur.val);\n\n if (cur.left != null) {\n queue.Enqueue(cur.left);\n }\n\n if (cur.right != null) {\n queue.Enqueue(cur.right);\n }\n }\n\n if (result.Count % 2 == 1) {\n oneResult.Reverse();\n }\n result.Add(oneResult);\n }\n\n return result;\n }\n}\n```
10
0
[]
2
binary-tree-zigzag-level-order-traversal
ZigZag Traversal | No Reverse | Deque | 1 ms
zigzag-traversal-no-reverse-deque-1-ms-b-hr4k
IntuitionThe interviewer might be interested in actual zig zag traversal and may not care about reversing the level's elements based on level parity. We can sim
ramuked
NORMAL
2025-02-22T07:21:09.008200+00:00
2025-02-22T07:21:09.008200+00:00
1,689
false
# Intuition The interviewer might be interested in actual zig zag traversal and may not care about reversing the level's elements based on level parity. We can simulate actual level order traversal by using a deque. # Approach Based on level parity, we can add elements to either at the front of the deque or at the end. For even levels (left to right traversal): 1. Remove nodes from the front (pollFirst()). 2. Add child nodes from left to right (offerLast()). For odd levels (right to left traversal): 1. Remove nodes from the back (pollLast()). 2. Add child nodes from right to left (offerFirst()). # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n), n = number of nodes in the tree. - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(n), n = number of nodes in the tree. # Code ```java [] /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { if(root == null)return new ArrayList<>(); ArrayDeque<TreeNode> dq = new ArrayDeque<>(); dq.offer(root); List<List<Integer>> result = new ArrayList<>(); boolean leftToRight = true; while(!dq.isEmpty()){ List<Integer> currLevel = new ArrayList<>(); for(int i = dq.size(); i > 0; i--){ TreeNode curr = (leftToRight)?dq.pollFirst():dq.pollLast(); currLevel.add(curr.val); if(leftToRight){ if(curr.left != null) dq.offerLast(curr.left); if(curr.right != null) dq.offerLast(curr.right); } else{ if(curr.right != null) dq.offerFirst(curr.right); if(curr.left != null) dq.offerFirst(curr.left); } } leftToRight = !leftToRight; result.add(currLevel); } return result; } } ```
9
0
['Java']
0
binary-tree-zigzag-level-order-traversal
💥☠️🎯Easiest Simple⚡Tree🌲 C++✔️Python3🐍✔️Java✔️C✔️Python🐍✔️-Beats⚡🎯💯Simplified💢💢
easiest-simpletree-cpython3javacpython-b-63z4
Intuition\n\n\n\n\n\n# This is a simplemLevel order application check out the image + vedio solution.. of mine.. \nhttps://leetcode.com/problems/binary-tree-lev
Edwards310
NORMAL
2024-04-22T10:45:29.848845+00:00
2024-04-22T11:08:21.494779+00:00
962
false
# Intuition\n![0ehh83fsnh811.jpg](https://assets.leetcode.com/users/images/09fc34c1-dfc6-4dbe-8edb-8f9a23e5ee93_1713781228.5565534.jpeg)\n![Screenshot 2024-04-22 154139.png](https://assets.leetcode.com/users/images/62578198-ed5d-43c0-8deb-be8e4ef73114_1713781237.45546.png)\n![Screenshot 2024-04-22 154114.png](https://assets.leetcode.com/users/images/4c9bf93f-75f7-4101-bca3-2e265946b5db_1713781245.8786848.png)\n![Screenshot 2024-04-22 154102.png](https://assets.leetcode.com/users/images/58f201f7-abcc-4f48-83e1-e80d87784111_1713781264.177546.png)\n![Screenshot 2024-04-22 154042.png](https://assets.leetcode.com/users/images/c7431a63-f780-46b5-b887-a7c5e6d92930_1713781271.9973915.png)\n# This is a simplemLevel order application check out the image + vedio solution.. of mine.. \nhttps://leetcode.com/problems/binary-tree-level-order-traversal/solutions/5029725/easiest-solution-python3-c-java-c-python-detailed-explanation-with-images\n```C++ []\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),\n * right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n cout.tie(NULL);\n\n if (!root)\n return {};\n vector<vector<int>> res;\n queue<TreeNode*> q;\n q.push(root);\n while (!q.empty()) {\n int n = q.size();\n vector<int> temp;\n for (int i = 0; i < n; i++) {\n TreeNode* node = q.front();\n q.pop();\n temp.push_back(node->val);\n if (node->left)\n q.push(node->left);\n if (node->right)\n q.push(node->right);\n }\n res.push_back(temp);\n }\n for (int i = 0; i < res.size(); i++) {\n if (i & 1 != 0)\n reverse(res[i].begin(), res[i].end());\n }\n return res;\n }\n};\n```\n```python3 []\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n res = []\n q = collections.deque()\n q.append(root)\n while q:\n q_len = len(q)\n level = []\n for i in range(q_len):\n node = q.popleft()\n if node is not None:\n level.append(node.val)\n q.append(node.left)\n q.append(node.right)\n if level:\n res.append(level)\n #Simple does level order traversal and then do this\n for i in range(len(res)):\n #for every odd value-list reverse it..\n if i & 1 != 0:\n res[i].reverse()\n\n return res\n```\n```C []\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * struct TreeNode *left;\n * struct TreeNode *right;\n * };\n */\n/**\n * Return an array of arrays of size *returnSize.\n * The sizes of the arrays are returned as *returnColumnSizes array.\n * Note: Both returned array and *columnSizes array must be malloced, assume\n * caller calls free().\n */\nstruct Pair {\n struct TreeNode* node;\n int level;\n};\n\nstruct Queue {\n struct Pair data[3000];\n int size;\n int i;\n int j;\n};\n\nvoid qpush(struct Queue* q, struct Pair p) {\n q->size++;\n q->data[q->j] = p;\n q->j = (q->j + 1) % 3000;\n}\n\nstruct Pair qpop(struct Queue* q) {\n struct Pair r;\n q->size--;\n r = q->data[q->i];\n q->i = (q->i + 1) % 3000;\n return r;\n}\n\nint qempty(struct Queue* q) { return q->size == 0; }\n\nstruct Result {\n int** r;\n int* cols;\n int size;\n int cap;\n\n int* cur;\n int cur_size;\n int cur_cap;\n};\n\nvoid flush(struct Result* r) {\n if (r->cur == NULL) {\n return;\n }\n if (r->size >= r->cap) {\n r->cap = (r->cap + 1) * 2;\n r->r = realloc(r->r, r->cap * sizeof(int*));\n r->cols = realloc(r->cols, r->cap * sizeof(int));\n }\n r->r[r->size] = r->cur;\n r->cols[r->size] = r->cur_size;\n r->size++;\n r->cur = NULL;\n r->cur_size = r->cur_cap = 0;\n}\n\nvoid add(struct Result* r, int x) {\n if (r->cur_size >= r->cur_cap) {\n r->cur_cap = (r->cur_cap + 1) * 2;\n r->cur = realloc(r->cur, r->cur_cap * sizeof(int));\n }\n r->cur[r->cur_size++] = x;\n}\n\nvoid reverse(int* data, int size) {\n int i;\n for (i = 0; i < size / 2; i++) {\n int t = data[i];\n data[i] = data[size - i - 1];\n data[size - i - 1] = t;\n }\n}\n\n/**\n * Return an array of arrays of size *returnSize.\n * The sizes of the arrays are returned as *returnColumnSizes array.\n * Note: Both returned array and *columnSizes array must be malloced, assume\n * caller calls free().\n */\nint** zigzagLevelOrder(struct TreeNode* root, int* returnSize,\n int** returnColumnSizes) {\n struct Queue q;\n struct Result r;\n int level = 0, i;\n struct Pair c = {root, level};\n memset(&q, 0, sizeof(q));\n memset(&r, 0, sizeof(r));\n if (root) {\n qpush(&q, c);\n }\n while (!qempty(&q)) {\n struct Pair cur = qpop(&q);\n if (cur.level != level) {\n flush(&r);\n }\n add(&r, cur.node->val);\n if (cur.node->left) {\n struct Pair n = {cur.node->left, cur.level + 1};\n qpush(&q, n);\n }\n if (cur.node->right) {\n struct Pair n = {cur.node->right, cur.level + 1};\n qpush(&q, n);\n }\n level = cur.level;\n }\n flush(&r);\n\n *returnColumnSizes = r.cols;\n *returnSize = r.size;\n for (i = 1; i < r.size; i += 2) {\n reverse(r.r[i], r.cols[i]);\n }\n return r.r;\n}\n```\n```Java []\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> res = new ArrayList<>();\n if (root == null)\n return res;\n Queue<TreeNode> q = new LinkedList<>();\n q.add(root);\n while (!q.isEmpty()) {\n int n = q.size();\n List<Integer> temp = new LinkedList<>();\n for (int i = 0; i < n; i++) {\n TreeNode node = q.poll();\n temp.add(node.val);\n if (node.left != null)\n q.add(node.left);\n if (node.right != null)\n q.add(node.right);\n }\n res.add(temp);\n }\n for(int i = 0; i < res.size(); i++){\n if(i % 2 != 0)\n Collections.reverse(res.get(i));\n }\n return res;\n }\n}\n```\n```python []\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def zigzagLevelOrder(self, root):\n """\n :type root: TreeNode\n :rtype: List[List[int]]\n """\n if not root:\n return []\n \n nodes = collections.defaultdict(list)\n stack = [(root,0)]\n\n while stack:\n node,depth = stack.pop()\n nodes[depth].append(node.val)\n if node.right:\n stack.append((node.right,depth+1))\n if node.left:\n stack.append((node.left,depth+1))\n \n res = []\n for k, v in nodes.items():\n if k % 2 == 0:\n res.append(v)\n else:\n res.append(v[::-1])\n return res\n```\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n Simple Approach We just do level order traversal and then assuming we start with level - 0 (root node - level) then reverse every odd index level .. \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(n)\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),\n * right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n cout.tie(NULL);\n\n if (!root)\n return {};\n vector<vector<int>> res;\n queue<TreeNode*> q;\n q.push(root);\n while (!q.empty()) {\n int n = q.size();\n vector<int> temp;\n for (int i = 0; i < n; i++) {\n TreeNode* node = q.front();\n q.pop();\n temp.push_back(node->val);\n if (node->left)\n q.push(node->left);\n if (node->right)\n q.push(node->right);\n }\n res.push_back(temp);\n }\n for (int i = 0; i < res.size(); i++) {\n if (i & 1 != 0)\n reverse(res[i].begin(), res[i].end());\n }\n return res;\n }\n};\n```\n# Check this out and please upvote my solution..\n![th.jpeg](https://assets.leetcode.com/users/images/e0596cf3-e9be-45ba-86b3-3c2a125b1e70_1713782722.0346804.jpeg)\n
9
0
['C', 'Python', 'C++', 'Java', 'Python3']
3
binary-tree-zigzag-level-order-traversal
Two stack approach (c++ solution)
two-stack-approach-c-solution-by-femish_-bdt2
This can be solve using two stack current and next.\n\n\nclass Solution {\npublic:\n \n void solve(TreeNode* root,vector<vector<int>> &ans){\n if(r
Femish_20
NORMAL
2022-06-21T10:00:05.906489+00:00
2022-06-21T14:27:44.838645+00:00
404
false
This can be solve using two stack current and next.\n\n```\nclass Solution {\npublic:\n \n void solve(TreeNode* root,vector<vector<int>> &ans){\n if(root==NULL) return ;\n \n stack<TreeNode*> curr;\n stack<TreeNode*> next;\n \n bool leftToRight=true;\n \n\t\t//push root to the curr\n curr.push(root);\n vector<int> v;\n while(!curr.empty()){\n TreeNode* node=curr.top();\n curr.pop();\n if(node){\n v.push_back(node->val);\n\t\t\t\t\n\t\t\t\t//add data in the next according to the order (leftToRight)\n if(leftToRight){\n if(node->left){\n next.push(node->left);\n }\n if(node->right){\n next.push(node->right);\n }\n }\n else{\n if(node->right){\n next.push(node->right);\n }\n if(node->left){\n next.push(node->left);\n }\n }\n }\n \n if(curr.empty()){\n ans.push_back(v);\n leftToRight=!leftToRight;\n swap(curr,next);\n v.clear();\n }\n }\n }\n \n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>> ans;\n solve(root,ans);\n return ans;\n }\n};\n```\n\n\n**Time complexity:** **O(n)** (We are traversing through all nodes once )\n**Space complexity:** **O(n) + O(n)** (For two stacks curr and next)
9
0
['Stack', 'C++']
0
binary-tree-zigzag-level-order-traversal
O(n)time/BEATS 99.97% MEMORY/SPEED 0ms MAY 2022
ontimebeats-9997-memoryspeed-0ms-may-202-ps8o
\n\n\n(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, please upvote this post.)\nTake care broth
darian-catalin-cucer
NORMAL
2022-05-04T20:14:09.343851+00:00
2022-05-04T20:14:46.943796+00:00
2,268
false
```\n```\n\n(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, ***please upvote*** this post.)\n***Take care brother, peace, love!***\n\n```\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 38.2MB*** (beats 92.04% / 24.00%).\n* ***Java***\n```\npublic List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n TreeNode c=root;\n List<List<Integer>> ans =new ArrayList<List<Integer>>();\n if(c==null) return ans;\n Stack<TreeNode> s1=new Stack<TreeNode>();\n Stack<TreeNode> s2=new Stack<TreeNode>();\n s1.push(root);\n while(!s1.isEmpty()||!s2.isEmpty())\n {\n List<Integer> tmp=new ArrayList<Integer>();\n while(!s1.isEmpty())\n {\n c=s1.pop();\n tmp.add(c.val);\n if(c.left!=null) s2.push(c.left);\n if(c.right!=null) s2.push(c.right);\n }\n ans.add(tmp);\n tmp=new ArrayList<Integer>();\n while(!s2.isEmpty())\n {\n c=s2.pop();\n tmp.add(c.val);\n if(c.right!=null)s1.push(c.right);\n if(c.left!=null)s1.push(c.left);\n }\n if(!tmp.isEmpty()) ans.add(tmp);\n }\n return ans;\n}\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 7.0MB*** (beats 100.00% / 100.00%).\n* ***C++***\n```\nclass Solution {\npublic:\n void helper(TreeNode*root,vector<vector<int>>&res,int level)\n {\n if(!root) return; \n if(level>=res.size())\n res.push_back({});\n res[level].push_back(root->val);\n helper(root->left,res,level+1);\n helper(root->right,res,level+1);\n }\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>>res;\n if(!root) return res;\n helper(root,res,0); \n for(int i=1;i<res.size();i=i+2)\n {\n reverse(res[i].begin(),res[i].end());\n }\n return res;\n }\n};\n```\n\n```\n```\n\n```\n```\n\n\nThe best result for the code below is ***26ms / 12.2MB*** (beats 95.42% / 82.32%).\n* ***Python***\n```\ndef zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n\tif not root: return []\n\tqueue = collections.deque([root])\n\tres = []\n\teven_level = False\n\twhile queue:\n\t\tn = len(queue)\n\t\tlevel = []\n\t\tfor _ in range(n):\n\t\t\tnode = queue.popleft()\n\t\t\tlevel.append(node.val)\n\t\t\tif node.left:\n\t\t\t\tqueue.append(node.left)\n\t\t\tif node.right:\n\t\t\t\tqueue.append(node.right)\n\t\tif even_level:\n\t\t\tres.append(level[::-1])\n\t\telse:\n\t\t\tres.append(level)\n\t\teven_level = not even_level\n\treturn res\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***51ms / 34.2MB*** (beats 100.00% / 84.12%).\n* ***JavaScript***\n```\nfunction zigzagLevelOrder(root) {\n let res = [];\n go(root, 0, res);\n return res;\n}\n\nfunction go(node, l, res) { // l means level\n if (!node) return;\n\n if (res[l] == null) {\n res.push([]);\n }\n\n if (l % 2 === 0) {\n res[l].push(node.val);\n } else {\n res[l].unshift(node.val);\n }\n\n go(node.left, l + 1, res);\n go(node.right, l + 1, res);\n}\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***68ms / 44.2MB*** (beats 100.00% / 45.25%).\n* ***Kotlin***\n```\n fun zigzagLevelOrder(root: TreeNode?): List<List<Int>> {\n val queue : Queue<TreeNode> = LinkedList()\n val result = mutableListOf<LinkedList<Int>>()\n if (root == null) return result\n var leftToRight = true // if true, add elements in normally else add in reverse\n queue.add(root)\n while (queue.isNotEmpty()) {\n val thisLevel = LinkedList<Int>()\n var size = queue.size\n while (size > 0) {\n var current = queue.poll()\n if (leftToRight.not()) thisLevel.addFirst(current.`val`) // reverse\n else thisLevel.add(current.`val`) // normal\n current.left?.let { queue.offer(it) }\n current.right?.let { queue.offer(it) }\n --size\n }\n result.add(thisLevel)\n leftToRight = leftToRight.not()\n }\n return result\n }\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***12ms / 32.2MB*** (beats 95% / 84%).\n* ***Swift***\n```\nclass Solution {\n // - Complexity:\n // - time: O(n), where n is the number of nodes.\n // - space: O(n), where n is the number of nodes.\n\n func zigzagLevelOrder(_ root: TreeNode?) -> [[Int]] {\n var ans = [[Int]]()\n dfs(root, level: 0, ans: &ans)\n return ans\n }\n\n\n private func dfs(_ node: TreeNode?, level: Int, ans: inout [[Int]]) {\n guard let node = node else { return }\n if ans.count <= level { ans.append([Int]()) }\n\n if level % 2 == 0 {\n ans[level].append(node.val)\n } else {\n ans[level].insert(node.val, at: 0)\n }\n\n dfs(node.left, level: level + 1, ans: &ans)\n dfs(node.right, level: level + 1, ans: &ans)\n }\n\n}\n```\n\n```\n```\n\n```\n```\n\n***"Open your eyes. Expect us." - \uD835\uDCD0\uD835\uDCF7\uD835\uDCF8\uD835\uDCF7\uD835\uDD02\uD835\uDCF6\uD835\uDCF8\uD835\uDCFE\uD835\uDCFC***
9
0
['Breadth-First Search', 'Queue', 'Swift', 'C', 'Python', 'Java', 'Python3', 'Kotlin', 'JavaScript']
4
binary-tree-zigzag-level-order-traversal
Easy to understand | 2 Solution | DFS | BFS | Simple | Python solution
easy-to-understand-2-solution-dfs-bfs-si-xish
\n def recursive(self, root):\n #inspired by the solution somewhat\n out = []\n def rec(node, height):\n if node:\n
mrmagician
NORMAL
2020-05-21T00:13:04.711927+00:00
2020-05-21T00:13:04.711974+00:00
1,392
false
```\n def recursive(self, root):\n #inspired by the solution somewhat\n out = []\n def rec(node, height):\n if node:\n if len(out) <= height:\n out.append([])\n out[height].append(node.val)\n rec(node.left, height + 1)\n rec(node.right, height + 1)\n rec(root, 0)\n return [out[i] if i%2==0 else out[i][::-1] for i in range(len(out))]\n \n def iterative(self, root):\n # here, the stack should be replaced by queue but I guess, I am lazy ;)\n if not root: return []\n stack = [root]\n out = []\n reverse = True\n while len(stack):\n temp = []\n out.append([i.val for i in (stack if reverse else stack[::-1])])\n reverse = not reverse\n while len(stack):\n top = stack.pop(0)\n if top.left: temp.append(top.left)\n if top.right: temp.append(top.right)\n \n stack = temp\n return out\n```\n\n**I hope that you\'ve found the solution useful.**\n*In that case, please do upvote and encourage me to on my quest to document all leetcode problems\uD83D\uDE03*\nPS: Search for **mrmagician** tag in the discussion, if I have solved it, You will find it there\uD83D\uDE38
9
0
['Depth-First Search', 'Breadth-First Search', 'Python', 'Python3']
0
binary-tree-zigzag-level-order-traversal
Java, easy understand recursive methods, beats 96% (attach easy BFS methods)
java-easy-understand-recursive-methods-b-b227
//recursive method\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<LinkedList<Integer>> res = new ArrayList<>();\n
ruihuang
NORMAL
2016-04-09T16:38:32+00:00
2018-09-20T03:30:26.443192+00:00
2,288
false
//recursive method\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<LinkedList<Integer>> res = new ArrayList<>();\n \n helper(res,root,0);\n \n List<List<Integer>> finalRes = new ArrayList<>();\n finalRes.addAll(res);\n return finalRes;\n }\n \n public void helper(List<LinkedList<Integer>> res, TreeNode root, int level){\n if(root == null)\n return;\n if(res.size() <= level)\n res.add(new LinkedList<>());\n \n if((level + 1) % 2 != 0)\n res.get(level).add(root.val);\n else\n res.get(level).addFirst(root.val);\n \n helper(res,root.left,level + 1);\n helper(res,root.right,level + 1); \n }\n \n \n //BFS method\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> res = new ArrayList<>();\n if(root == null)\n return res;\n \n Queue<TreeNode> q = new LinkedList<>();\n q.offer(root);\n int level = 1;\n while(!q.isEmpty()){\n LinkedList<Integer> path = new LinkedList<>();\n int levelNums = q.size();\n \n for(int i = 0; i < levelNums; i++){\n root = q.poll();\n if(level % 2 != 0){\n path.add(root.val);\n }else{\n path.addFirst(root.val);\n }\n \n if(root.left != null)\n q.offer(root.left);\n if(root.right != null)\n q.offer(root.right);\n }\n res.add(path);\n level++;\n }\n \n return res;\n }
9
0
[]
0
binary-tree-zigzag-level-order-traversal
[C++] Clean Code
c-clean-code-by-alexander-pgv3
\n/**\n * -> 1->\n * <- 2 < 3 <-\n * -> 4 > 5 > 6 > 7 ->\n * <- 8 9 10 11 12 13 14 15 <-\n *\n * level % 2 = 0 - forward popping. push to
alexander
NORMAL
2017-09-30T13:52:35.245000+00:00
2017-09-30T13:52:35.245000+00:00
1,065
false
```\n/**\n * -> 1->\n * <- 2 < 3 <-\n * -> 4 > 5 > 6 > 7 ->\n * <- 8 9 10 11 12 13 14 15 <-\n *\n * level % 2 = 0 - forward popping. push to back: left + right\n * level % 2 = 1 - backward popping. push to front: right + left \n */\n```\n```\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n if (!root) return {};\n vector<vector<int>> lines;\n deque<TreeNode*> q;\n q.push_front(root);\n\n for (int l = 0; !q.empty(); l++) {\n lines.push_back({});\n for (int n = q.size(); n > 0; n--) {\n TreeNode* node = l % 2 == 0 ? q.front() : q.back();\n l % 2 == 0 ? q.pop_front() : q.pop_back();\n lines[l].push_back(node->val);\n if (l % 2 == 0) {\n if (node->left) q.push_back(node->left);\n if (node->right) q.push_back(node->right);\n }\n else {\n if (node->right) q.push_front(node->right);\n if (node->left) q.push_front(node->left);\n }\n }\n }\n\n return lines;\n }\n};\n```
9
0
[]
0
binary-tree-zigzag-level-order-traversal
"Optimal Zigzag Level Order Traversal"
optimal-zigzag-level-order-traversal-by-n6jyt
Intuition\nThe problem asks us to perform a zigzag (or spiral) level order traversal of a binary tree. This means traversing the tree level by level but alterna
santrupt_29
NORMAL
2024-10-07T17:45:07.968661+00:00
2024-10-07T17:45:07.968691+00:00
542
false
# Intuition\nThe problem asks us to perform a zigzag (or spiral) level order traversal of a binary tree. This means traversing the tree level by level but alternating the direction at each level:\n\nAt the first level, we traverse from left to right.\nAt the second level, we traverse from right to left.\nWe continue alternating the traversal direction for subsequent levels.\nTo achieve this, we can modify a standard Breadth-First Search (BFS) approach, where we use a queue to process nodes level by level, and adjust how we store the nodes\' values based on the current direction.\n\n# Approach\n1. Initial Setup:\n\nWe start by checking if the tree is empty. If it is, we return an empty result.\nWe use a queue to store nodes and perform level-order traversal (BFS).\n\n2. Level-by-Level Traversal:\n\nFor each level, we first check the number of nodes at that level (levelSize).\nWe create a temporary vector levelNodeData to hold the values of the nodes at this level.\n\n3. Zigzag Logic:\n\nIf the current level is traversing from left to right, we insert node values in the same order as they are processed.\nIf the current level is traversing from right to left, we insert node values in reverse order.\nThis is achieved by using the index i for left-to-right insertion and levelSize - i - 1 for right-to-left insertion.\n\n4. Queue Maintenance:\n\nAfter processing each node, we push its left and right children (if they exist) into the queue, so they can be processed in the next level.\n\n5. Alternate Direction:\n\nAfter each level, we toggle the leftToRight flag to switch between left-to-right and right-to-left traversal for the next level.\nFinal Step:\n\nOnce all levels are processed, the result vector contains the zigzag level order traversal of the tree.\n\n\n# Complexity\n* Time Complexity: O(n)\nWe process each node exactly once, and for each node, we perform constant-time operations such as queue insertion and accessing its children. Therefore, the time complexity is O(n), where n is the number of nodes in the tree.\n* Space Complexity: O(n)\nThe space complexity is dominated by the size of the queue. In the worst case, the queue can hold nodes from the largest level of the tree, which occurs when the tree is a balanced binary tree. Thus, the space complexity is O(n), where n is the number of nodes.\n# Code\n```cpp []\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n // Result vector to store nodes in zigzag order\n vector<vector<int>> zigzagList;\n\n // If the root is NULL, return an empty result\n if (root == NULL) return zigzagList;\n\n // Queue to store nodes for level-order traversal\n queue<TreeNode*> pendingNodes;\n pendingNodes.push(root);\n\n // Flag to alternate between left-to-right and right-to-left order\n bool leftToRight = true;\n\n // Loop until there are nodes to process\n while (!pendingNodes.empty()) {\n // Get the number of nodes at the current level\n int levelSize = pendingNodes.size();\n \n // Vector to store the current level\'s node values\n vector<int> levelNodeData(levelSize);\n\n // Process each node at the current level\n for (int i = 0; i < levelSize; i++) {\n TreeNode* frontNode = pendingNodes.front();\n pendingNodes.pop();\n\n // If leftToRight is true, fill values from left to right\n if (leftToRight) {\n levelNodeData[i] = frontNode->val;\n } \n // Otherwise, fill values from right to left\n else {\n levelNodeData[levelSize - i - 1] = frontNode->val;\n }\n\n // Add left and right children to the queue if they exist\n if (frontNode->left != NULL) pendingNodes.push(frontNode->left);\n if (frontNode->right != NULL) pendingNodes.push(frontNode->right);\n }\n\n // After processing the current level, add the values to the result\n zigzagList.push_back(levelNodeData);\n\n // Flip the direction for the next level\n leftToRight = !leftToRight;\n }\n\n return zigzagList;\n }\n};\n\n```
8
0
['C++']
0
binary-tree-zigzag-level-order-traversal
EASIEST JAVA SOLUTION😎✌️ || STEP BY STEP EXPLAINED😁
easiest-java-solution-step-by-step-expla-ia9e
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
abhiyadav05
NORMAL
2023-04-01T14:34:16.588710+00:00
2023-04-01T14:34:16.588764+00:00
473
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)$$ -->O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(N)\n![Screenshot_20230205_171246.png](https://assets.leetcode.com/users/images/967e082c-1572-4190-a249-35b49767a9a2_1680359653.9038227.png)\n\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n \n // Create a queue to store the tree nodes\n Queue<TreeNode> queue = new LinkedList<TreeNode>();\n\n // Create an array list to store the final result\n List<List<Integer>> wrapList = new ArrayList<>();\n \n // If the root node is null, return an empty list\n if(root == null){\n return wrapList;\n }\n \n // Add the root node to the queue\n queue.add(root);\n \n // Set the flag to true for left to right traversal\n boolean flag = true;\n \n // Traverse the tree level by level\n while(!queue.isEmpty()){\n \n // Get the number of nodes at the current level\n int size = queue.size();\n\n // Create an array list to store the nodes\' values at the current level\n List<Integer> subList = new ArrayList<>();\n \n // Traverse the nodes at the current level\n for(int i =0; i < size; i++){\n\n // Check the left and right child of the current node and add them to the queue if they are not null\n if(queue.peek().left != null){\n queue.add(queue.peek().left);\n }\n if(queue.peek().right != null){\n queue.add(queue.peek().right);\n }\n\n // For left to right traversal\n if(flag == true){\n // Add the node\'s value to the end of the subList\n subList.add(queue.poll().val);\n }\n // For right to left traversal\n else{\n // Add the node\'s value to the beginning of the subList\n subList.add(0,queue.poll().val);\n }\n }\n // Toggle the flag to switch between left to right and right to left traversal\n flag = !flag;\n \n // Add the subList to the wrapList\n wrapList.add(subList);\n }\n // Return the final result\n return wrapList;\n }\n}\n```
8
0
['Tree', 'Breadth-First Search', 'Queue', 'Binary Tree', 'Java']
1
binary-tree-zigzag-level-order-traversal
[Python3] Clean Solution using Queue Level Order Traversal
python3-clean-solution-using-queue-level-k507
\nclass Solution:\n def zigzagLevelOrder(self, root):\n \n res = []\n if not root: return res\n zigzag = True\n \n
SamirPaulb
NORMAL
2022-06-01T15:19:34.492329+00:00
2022-06-01T15:19:34.492370+00:00
1,012
false
```\nclass Solution:\n def zigzagLevelOrder(self, root):\n \n res = []\n if not root: return res\n zigzag = True\n \n q = collections.deque()\n q.append(root)\n \n while q:\n n = len(q)\n nodesOfThisLevel = []\n \n for i in range(n):\n node = q.popleft()\n nodesOfThisLevel.append(node.val)\n \n if node.left: q.append(node.left)\n if node.right: q.append(node.right)\n \n if zigzag:\n res.append(nodesOfThisLevel)\n zigzag = False\n else:\n res.append(nodesOfThisLevel[::-1])\n zigzag = True\n \n return res\n \n# Time: O(N)\n# Space: O(N)\n```
8
0
['Queue', 'Python', 'Python3']
0
binary-tree-zigzag-level-order-traversal
Easy to understand (Python Code)
easy-to-understand-python-code-by-vaibha-ugnb
\n def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n if root is None:\n return\n myqueue=queue.Queue()\n
vaibhavsharma30
NORMAL
2022-02-17T13:21:38.001378+00:00
2022-02-17T18:01:52.374611+00:00
291
false
```\n def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n if root is None:\n return\n myqueue=queue.Queue()\n myqueue.put(root)\n myqueue.put(None)\n final=[]\n small=[]\n left2right=True\n while myqueue.empty()==False:\n front=myqueue.get()\n if front is not None:\n if front.left!= None:\n myqueue.put(front.left)\n if front.right!=None:\n myqueue.put(front.right) \n small.append(front.val)\n else:\n if myqueue.empty()==True:\n if left2right:\n final.append(small)\n else:\n final.append(small[-1::-1])\n break\n else:\n if left2right:\n final.append(small)\n left2right=False\n else:\n rev=small[-1::-1]\n final.append(rev)\n left2right=True\n small=[]\n myqueue.put(None)\n return final \n \n```
8
0
['Queue', 'Binary Tree', 'Python']
0
binary-tree-zigzag-level-order-traversal
Swift BFS
swift-bfs-by-diegostamigni-ehmt
The idea here is to simply proceed our level order traverse left to right but append items to end or to begin of sub arrays following current swapping direction
diegostamigni
NORMAL
2019-05-01T16:21:19.475523+00:00
2019-05-01T16:29:23.405032+00:00
574
false
The idea here is to simply proceed our level order traverse left to right but append items to end or to begin of sub arrays following current swapping direction.\n```\nclass Solution {\n private enum Direction {\n case right\n case left\n }\n\n func zigzagLevelOrder(_ root: TreeNode?) -> [[Int]] {\n var ans = [[Int]]()\n guard let root = root else { return ans }\n var queue = [root]\n var direction = Direction.left\n while !queue.isEmpty {\n let count = queue.count\n var sub = [Int]()\n for i in 0..<count {\n let curr = queue.removeFirst()\n switch direction {\n case .right:\n sub.append(curr.val)\n case .left:\n sub.insert(curr.val, at: 0)\n }\n if let right = curr.right {\n queue.append(right)\n }\n if let left = curr.left {\n queue.append(left)\n }\n }\n ans.append(sub)\n direction = direction == .left ? .right : .left\n }\n return ans\n }\n}\n```
8
0
['Breadth-First Search', 'Swift']
0
binary-tree-zigzag-level-order-traversal
Clean C++ Solution with Queue, Easy to Understand and beats 100% Users
clean-c-solution-with-queue-easy-to-unde-9fh9
Intuition\nThe idea is to traverse the tree level by level, using a queue to manage nodes at each level. For every level, nodes\' values are collected, and for
_sxrthakk
NORMAL
2024-07-09T14:32:58.834312+00:00
2024-07-09T14:32:58.834373+00:00
374
false
# Intuition\nThe idea is to traverse the tree level by level, using a queue to manage nodes at each level. For every level, nodes\' values are collected, and for odd levels, the collected values are reversed to achieve the zigzag pattern.\n\n# Approach\n1. **Initial Checks and Setup :**\n- If the root is null, return an empty vector.\n \n- Initialize a queue to store the nodes to be processed at each level, starting with the root.\n \n2. **Level Order Traversal :**\n- Use a while loop to process nodes level by level until the queue is empty.\n \n- For each level, determine the number of nodes at that level (l = q.size()).\n- Use a for loop to iterate through all nodes at the current level:\na) Pop the front node from the queue.\nb) Append its value to a temporary vector (ans).\nc) Push its left and right children to the queue if they exist.\n\n3. **Collecting Results :**\n- Append the temporary vector (ans) containing the current level\'s node values to the result vector (v).\n\n4. **Zigzag Pattern :**\n- After completing the level order traversal, iterate through the result vector.\n- Reverse the node values for every odd-indexed level to achieve the zigzag pattern.\n\n5. **Return the Result :**\n- Return the result vector (v) containing the zigzag level order traversal.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> v;\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n if(!root) return v;\n queue<TreeNode*> q;\n q.push(root);\n \n while(q.size()>0){\n vector<int> ans;\n int l=q.size();\n for(int i=0;i<l;i++){\n TreeNode* temp=q.front();\n q.pop();\n ans.push_back(temp->val);\n if(temp->left) q.push(temp->left);\n if(temp->right) q.push(temp->right);\n }\n v.push_back(ans);\n }\n for(int i=0;i<v.size();i++){\n if(i%2==1) reverse(v[i].begin(),v[i].end());\n }\n return v;\n }\n};\n```
7
0
['Array', 'Tree', 'Breadth-First Search', 'Queue', 'Binary Tree', 'C++']
1
binary-tree-zigzag-level-order-traversal
PuTtA EaSY Solution C++ ✅ | Beats 100% 🔥Runtime 0ms 🔥| Funday
putta-easy-solution-c-beats-100-runtime-ire71
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nUsing Queue , placing t
Saisreeramputta
NORMAL
2023-02-19T11:08:02.928284+00:00
2023-02-19T11:08:29.577964+00:00
1,026
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing Queue , placing the values at right indexes .\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n queue<TreeNode*> q;\n q.push(root);\n vector<vector<int>> ans; // answer vector\n bool left = false;\n if(root == NULL) return ans; //if tree is empty\n while(!q.empty()){ //level order traversal\n int n= q.size();\n vector<int> ans1(n); \n for(int i=0;i<n;i++){\n TreeNode* temp = q.front();\n if(left == false) ans1[i] = temp->val;\n else ans1[n-i-1] = temp->val;\n q.pop();\n // pushing next level into queue\n if(temp->left != NULL) q.push(temp->left);\n if(temp->right != NULL) q.push(temp->right);\n }\n left = !left; // changing the zig-Zag order\n ans.push_back(ans1);\n }\n return ans;\n }\n};\n```\n![Screenshot (8).png](https://assets.leetcode.com/users/images/90f6f168-24b2-4a18-8cb7-2521712a6b38_1676804866.9230862.png)\n
7
0
['Tree', 'Breadth-First Search', 'Binary Tree', 'C++']
2
binary-tree-zigzag-level-order-traversal
🐍Python || ✅C++ || 💥Simple Solution Using BFS✔ || 🚀Iterative Manner using queue
python-c-simple-solution-using-bfs-itera-8jm7
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
santhosh1608
NORMAL
2023-02-19T04:07:32.043450+00:00
2023-02-19T04:07:32.043498+00:00
1,234
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code Upvote Please \uD83D\uDE4C\n```\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def zigzagLevelOrder(self, root):\n """\n :type root: TreeNode\n :rtype: List[List[int]]\n """\n result=[]\n if not root:\n return []\n queue = [root]\n level=0\n while queue:\n rev = []\n for i in range(len(queue)):\n curr = queue.pop(0)\n rev.append(curr.val)\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n if level%2:\n result.append(rev[::-1])\n else: \n result.append(rev)\n level += 1\n return result\n```\n\n# Find Helpful Please Upvote \uD83E\uDD1E\uD83D\uDE09
7
1
['Tree', 'Breadth-First Search', 'Binary Tree', 'Python']
0
binary-tree-zigzag-level-order-traversal
C++✅✅ | Level Order Traversal + BFS | Faster🧭 than 100%🔥 | Clean & Concise Code |
c-level-order-traversal-bfs-faster-than-tdikn
\n\n# Code\n# Please Do Upvote!!!!\n##### Connect with me on Linkedin -> https://www.linkedin.com/in/md-kamran-55b98521a/\n\n\n\nclass Solution {\npublic:\n\n
mr_kamran
NORMAL
2022-12-20T10:08:39.714549+00:00
2023-02-19T02:29:28.324814+00:00
1,087
false
\n\n# Code\n# Please Do Upvote!!!!\n##### Connect with me on Linkedin -> https://www.linkedin.com/in/md-kamran-55b98521a/\n```\n\n\nclass Solution {\npublic:\n\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n \n vector<vector<int>>res;\n\n if(root == NULL) return res;\n\n queue<TreeNode*>q;\n q.push(root);\n int cnt = -1;\n\n while(!q.empty())\n {\n int n = q.size();\n\n vector<int>l;\n\n for(int i = 0; i < n; ++i)\n {\n \n auto temp = q.front();\n q.pop();\n\n if(temp->left!=NULL) q.push(temp->left);\n if(temp->right!=NULL) q.push(temp->right);\n\n l.push_back(temp->val);\n\n }\n\n cnt++;\n \n if(cnt % 2 != 0) reverse(l.begin(),l.end());\n\n res.push_back(l);\n \n }\n\n return res;\n }\n};\n\n\n\n```\n![b62ab1be-232a-438f-9524-7d8ca4dbd5fe_1675328166.1161866.png](https://assets.leetcode.com/users/images/98b7adbc-5abf-45f7-9b5b-538574194654_1676344687.6513524.png)
7
0
['C++']
1
binary-tree-zigzag-level-order-traversal
Intuitive Solution using Deque with clean code and Visual Representation of the Deque
intuitive-solution-using-deque-with-clea-1m32
Approach:\n\n When we have to print in right direction: We take the nodes from the front of the deque and push the children in the back of the deque\n When we h
achitj
NORMAL
2021-07-23T12:11:13.328638+00:00
2021-07-23T12:11:13.328768+00:00
153
false
### Approach:\n\n* **When we have to print in right direction**: We take the nodes from the front of the deque and push the children in the back of the deque\n* **When we have to print in left direction**: We take the nodes from the back of the deque and push the children in the front of the deque in reverse order since we are traversing the current elements in reverse itself.\n\n\n![image](https://assets.leetcode.com/users/images/54da592b-6f25-44ba-9e05-f1e57a870e70_1627041938.234792.png)\n\n```\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) \n { \n vector<vector<int>> ans;\n \n if(!root)\n return ans;\n \n deque<TreeNode*> nodes;\n \n bool right = true;\n \n TreeNode *levelEnd = new TreeNode(-1);\n \n nodes.push_back(root);\n nodes.push_back(levelEnd);\n \n vector<int> currAns;\n \n while(nodes.size() > 1)\n {\n if(right)\n {\n TreeNode *currNode = nodes.front();\n \n if(currNode == levelEnd)\n {\n ans.push_back(currAns);\n currAns.clear();\n\n right = !right;\n }\n else\n {\n nodes.pop_front();\n \n currAns.push_back(currNode->val);\n \n if(currNode->left)\n nodes.push_back(currNode->left);\n \n if(currNode->right)\n nodes.push_back(currNode->right);\n }\n }\n \n else\n {\n TreeNode *currNode = nodes.back();\n \n if(currNode == levelEnd)\n {\n ans.push_back(currAns);\n currAns.clear();\n\n right = !right;\n }\n else\n {\n nodes.pop_back();\n \n currAns.push_back(currNode->val);\n\n if(currNode->right)\n nodes.push_front(currNode->right);\n \n if(currNode->left)\n nodes.push_front(currNode->left);\n }\n }\n }\n ans.push_back(currAns); \n \n return ans;\n }\n};\n```
7
0
[]
0
binary-tree-zigzag-level-order-traversal
javascript clean solution
javascript-clean-solution-by-jiakang-g4wv
\nvar zigzagLevelOrder = function(root) {\n let res = [];\n helper(root, 0, res);\n return res;\n};\n\nvar helper = function(node, level, res){\n if
jiakang
NORMAL
2018-09-06T22:31:01.587655+00:00
2018-10-23T18:53:10.812219+00:00
823
false
```\nvar zigzagLevelOrder = function(root) {\n let res = [];\n helper(root, 0, res);\n return res;\n};\n\nvar helper = function(node, level, res){\n if(!node) return;\n if(!res[level]) res[level] = [];\n level % 2 ? res[level].unshift(node.val) : res[level].push(node.val);\n helper(node.left, level + 1, res);\n helper(node.right, level + 1, res);\n}\n```
7
2
[]
2
binary-tree-zigzag-level-order-traversal
Consice recursive C++ solution
consice-recursive-c-solution-by-elogeel-ig5g
The idea is to solve the problem normally if it was about traversing every level separately then reverse odd rows.\n\n class Solution {\n public:\n
elogeel
NORMAL
2015-07-14T01:38:10+00:00
2015-07-14T01:38:10+00:00
967
false
The idea is to solve the problem normally if it was about traversing every level separately then reverse odd rows.\n\n class Solution {\n public:\n void build(TreeNode* n, vector<vector<int>>& R, int d) {\n if (!n) return;\n if (d == R.size()) R.push_back(vector<int>());\n R[d].push_back(n->val);\n build(n->left, R, d + 1);\n build(n->right, R, d + 1);\n }\n \n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>> R;\n build(root, R, 0);\n for (int i = 1; i < R.size(); i += 2) reverse(R[i].begin(), R[i].end());\n return R;\n }\n };
7
0
[]
0
binary-tree-zigzag-level-order-traversal
Accepted C++ recursive solution with no queues
accepted-c-recursive-solution-with-no-qu-s7d7
Simple algorithm: \n\n 1. do depth first recursive tree search\n 2. populate all vectors for each tree level from left to right\n 3. reverse even levels to conf
paul7
NORMAL
2014-10-29T06:56:28+00:00
2014-10-29T06:56:28+00:00
4,159
false
Simple algorithm: \n\n 1. do depth first recursive tree search\n 2. populate all vectors for each tree level from left to right\n 3. reverse even levels to conform with zigzar requirement\n\n.\n\n class Solution {\n vector<vector<int> > result;\n public:\n vector<vector<int> > zigzagLevelOrder(TreeNode *root) {\n \n if(root!=NULL)\n {\n traverse(root, 0);\n }\n \n for(int i=1;i<result.size();i+=2)\n {\n vector<int>* v = &result[i];\n std:reverse(v->begin(), v->end());\n }\n return result;\n }\n \n void traverse(TreeNode* node, int level)\n {\n if(node == NULL) return;\n \n vector<int>* row = getRow(level);\n row->push_back(node->val);\n \n traverse(node->left, level+1);\n traverse(node->right, level+1);\n }\n \n vector<int>* getRow(int level)\n {\n if(result.size()<=level)\n {\n vector<int> newRow;\n result.push_back(newRow);\n }\n return &result[level];\n }\n };
7
0
[]
3
binary-tree-zigzag-level-order-traversal
4ms Concise DFS C++ Implementation
4ms-concise-dfs-c-implementation-by-alle-tz0l
1 Calculate depth in each recursion.\n2 Switch directions for adding current value based on (depth % 2).\n\n vector> zigzagLevelOrder(TreeNode root) {\n
allenwow
NORMAL
2016-01-11T02:13:43+00:00
2016-01-11T02:13:43+00:00
1,608
false
1 Calculate depth in each recursion.\n2 Switch directions for adding current value based on (depth % 2).\n\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>> rst;\n traverse(root, 0, rst);\n return rst;\n }\n \n void traverse(TreeNode* root, int depth, vector<vector<int>> & rst) {\n if (!root)\n return;\n if (rst.size() == depth) {\n vector<int> temp;\n rst.push_back(temp);\n }\n if (depth % 2 == 0) \n rst[depth].push_back(root ->val);\n else{\n rst[depth].insert(rst[depth].begin(), root -> val); \n }\n traverse(root -> left, depth + 1, rst); \n traverse(root -> right, depth +1, rst);\n }
7
0
['C++']
4
binary-tree-zigzag-level-order-traversal
Simple Java Solution. Same as level order traversal with a flag. No recursion
simple-java-solution-same-as-level-order-nzpy
\npublic List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> result = new ArrayList<>();\n if(root==null) return result;\n
prateek470
NORMAL
2016-10-22T09:05:47.258000+00:00
2016-10-22T09:05:47.258000+00:00
924
false
```\npublic List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> result = new ArrayList<>();\n if(root==null) return result;\n \n Queue<TreeNode> q = new LinkedList<>();\n q.add(root);\n Boolean reverse = false;\n while(!q.isEmpty()){\n int size = q.size();\n List<Integer> temp = new ArrayList<>();\n for(int i=0;i<size;i++){\n TreeNode node = q.poll();\n if(!reverse)\n temp.add(node.val);\n else\n temp.add(0,node.val);\n if(node.left!=null) q.add(node.left);\n if(node.right!= null) q.add(node.right);\n }\n result.add(temp);\n reverse=!reverse;\n }\n return result;\n }\n```
7
0
[]
3
binary-tree-zigzag-level-order-traversal
Big Brain Approach || JAVA || 200 IQ
big-brain-approach-java-200-iq-by-armaan-wdrz
Intuition\nI just took the normal level order traversal, stored each level in a different list, inside the main list and then reversed all the alternate lists.\
ArmaanSharma_19
NORMAL
2024-10-22T05:32:14.886876+00:00
2024-10-22T05:32:59.728535+00:00
947
false
# Intuition\nI just took the normal level order traversal, stored each level in a different list, inside the main list and then reversed all the alternate lists.\n\n# Approach\n1. Use a queue to perform a level order traversal of the tree. This allows us to process each level of the tree one at a time.\n2. For each level, store the node values in a list and add that list to the result.\n3. After obtaining the result, iterate through the lists in the result. For every alternate list (i.e., indices 1, 3, 5, etc.), reverse the list to achieve the zigzag order.\n4. Return the final list of lists.\n\n# Complexity\n- Time complexity: $$O(n)$$, where $$n$$ is the number of nodes in the binary tree. We visit each node once during the traversal.\n \n- Space complexity: $$O(n)$$ for storing the result and the queue, which may contain up to $$n$$ nodes in the worst case.\n\n# Code\n```java\nclass Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> ans = ques(root);\n\n for (int i = 1; i < ans.size(); i += 2) {\n Collections.reverse(ans.get(i)); \n }\n \n return ans;\n }\n \n public List<List<Integer>> ques(TreeNode root) {\n List<List<Integer>> result = new ArrayList<>();\n \n if (root == null) {\n return result;\n }\n \n Queue<TreeNode> queue = new LinkedList<>();\n queue.offer(root);\n\n while (!queue.isEmpty()) {\n int size = queue.size();\n List<Integer> currentLevel = new ArrayList<>();\n\n for (int i = 0; i < size; i++) {\n TreeNode currentNode = queue.poll();\n currentLevel.add(currentNode.val);\n\n if (currentNode.left != null) {\n queue.offer(currentNode.left);\n }\n if (currentNode.right != null) {\n queue.offer(currentNode.right);\n }\n }\n\n result.add(currentLevel);\n }\n\n return result;\n }\n}\n\n```\n![image.png](https://assets.leetcode.com/users/images/880e765d-0c21-441c-b0c3-6ebd5d3f89a8_1729575116.0965846.png)\n\n\n\n
6
0
['Java']
1
binary-tree-zigzag-level-order-traversal
✅💯🔥Simple Code🚀📌|| 🔥✔️Easy to understand🎯 || 🎓🧠Beats 100%🔥|| Beginner friendly💀💯
simple-code-easy-to-understand-beats-100-ftrm
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
atishayj4in
NORMAL
2024-08-01T20:17:00.940908+00:00
2024-08-01T20:17:00.940925+00:00
917
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n List<List<Integer>> ans = new ArrayList<>();\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n if(root==null){\n return ans;\n }\n Queue<TreeNode> q = new LinkedList<>();\n q.add(root);\n q.add(null);\n int i=1;\n List<Integer> subans= new ArrayList<>();\n while(!q.isEmpty()){\n TreeNode curr = q.remove();\n if(curr==null){\n if(i%2==0){\n Collections.reverse(subans);\n ans.add(subans);\n }else{\n ans.add(subans);\n }\n i++;\n if(q.isEmpty()){\n break;\n } else{\n q.add(null);\n subans=new ArrayList<>();\n }\n }else{\n subans.add(curr.val);\n if(curr.left!=null){\n q.add(curr.left);\n }\n if(curr.right!=null){\n q.add(curr.right);\n }\n }\n }\n return ans; \n }\n}\n```\n![7be995b4-0cf4-4fa3-b48b-8086738ea4ba_1699897744.9062278.jpeg](https://assets.leetcode.com/users/images/fe5117c9-43b1-4ec8-8979-20c4c7f78d98_1721303757.4674635.jpeg)
6
1
['Tree', 'Breadth-First Search', 'C', 'Binary Tree', 'Python', 'C++', 'Java']
0
binary-tree-zigzag-level-order-traversal
Easy and Optimized code Best Explanation🔥🔥| TC-O(N).
easy-and-optimized-code-best-explanation-5wow
PLZ UPVOTE\n\n# Intuition\nThe code uses a breadth-first search (BFS) approach to traverse the binary tree level by level. It maintains a boolean variable flag
rohitkumar9897
NORMAL
2023-12-27T18:34:20.891913+00:00
2023-12-28T05:47:27.814277+00:00
453
false
# **PLZ UPVOTE**\n\n# Intuition\nThe code uses a breadth-first search (BFS) approach to traverse the binary tree level by level. It maintains a boolean variable flag to determine whether to add elements from left to right or right to left in each level. If flag is true, elements are added from left to right, and if flag is false, elements are added from right to left.\n\n# Approach\n1. The code uses a queue to perform level order traversal. The queue is initially populated with the root of the tree.\n2. Inside the loop, it processes each level:\n- It calculates the size of the current level and creates a list arr2 to store the values of the nodes at that level.\n- For each node in the level, it adds its left and right children to the queue if they exist.\n- Depending on the value of the flag, it either adds the value of the node to the end of the arr2 list or adds it to the beginning (in reverse order).\n- After processing all nodes at the current level, it toggles the value of the flag for the next level.\n- The arr2 list is then added to the result list arr.\n3. The process continues until all levels of the tree are processed.\n\n# Complexity\n- Time complexity:\nThe time complexity of the code is O(N), where N is the number of nodes in the binary tree. In the worst case, every node is visited once. The inner loop, which processes each level, runs in O(N) time overall. The queue operations and list manipulations are constant time for each node.\n\n- Space complexity: O(N) because only queue of size n is taken as extra space.\n\n# Code\n```Java []\nclass Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> arr= new ArrayList<>();\n if(root==null){\n return arr;\n }\n Queue<TreeNode> q= new LinkedList<>();\n q.add(root);\n boolean flag=true;\n while(!q.isEmpty()){\n int n= q.size();\n List<Integer> arr2= new ArrayList<>(n);\n for(int i=0; i<n; i++){\n if(q.peek().left!=null){\n q.add(q.peek().left);\n }\n if(q.peek().right!=null){\n q.add(q.peek().right);\n }\n if(flag){\n arr2.add(q.poll().val);\n }else{\n arr2.add(0,q.poll().val);\n }\n }\n flag=!flag;\n arr.add(arr2);\n }\n return arr;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>> result;\n if (root == nullptr) {\n return result;\n }\n\n queue<TreeNode*> q;\n q.push(root);\n bool flag = true;\n\n while (!q.empty()) {\n int n = q.size();\n vector<int> levelValues(n);\n\n for (int i = 0; i < n; ++i) {\n if (q.front()->left != nullptr) {\n q.push(q.front()->left);\n }\n if (q.front()->right != nullptr) {\n q.push(q.front()->right);\n }\n\n if (flag) {\n levelValues[i] = q.front()->val;\n } else {\n levelValues[n - 1 - i] = q.front()->val;\n }\n\n q.pop();\n }\n\n flag = !flag;\n result.push_back(levelValues);\n }\n\n return result;\n }\n};\n```\n```Python []\nclass Solution:\n def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n result = []\n if not root:\n return result\n\n queue = deque([root])\n flag = True\n\n while queue:\n n = len(queue)\n level_values = [0] * n\n\n for i in range(n):\n node = queue.popleft()\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n\n if flag:\n level_values[i] = node.val\n else:\n level_values[n - 1 - i] = node.val\n\n flag = not flag\n result.append(level_values)\n\n return result\n```\n![upvote.jpg](https://assets.leetcode.com/users/images/c3ace874-43d2-43f4-a629-efaef82c532b_1703742442.869688.jpeg)\n\n
6
0
['Breadth-First Search', 'Queue', 'Python', 'C++', 'Java']
1
binary-tree-zigzag-level-order-traversal
C++ (Easy Approach) | Binary Tree Zigzag Level Order Traversal | LeetCode Solution
c-easy-approach-binary-tree-zigzag-level-gqqf
Intuition\nFor printing zigzag traversal we have to follow level order printing techniques, hence we can use bfs traversal technique for the level order printin
Darshil_Thakkar
NORMAL
2023-12-01T17:35:12.201115+00:00
2023-12-01T17:58:45.658148+00:00
240
false
# Intuition\nFor printing zigzag traversal we have to follow level order printing techniques, hence we can use bfs traversal technique for the level order printing which we can implement using queue data structure.\n# Approach\nWe\'ll take queue data structure which stores the TreeNode pointer and at the very first we will pass root to the queue. then for until our queue is non-empty we will take all the elements which are size of queue and add them into our level vector. now for the zigzag part we can take one flag boolean variable to identify whether the current allocation is left to right or it is right to left, and we\'ll remove that node and add left pointer and right pointer of that node. after completing this process we\'ll add this level vector to the resulting vector and switch the flag boolean variable for the zigzag.\n\n# Complexity\n- Time complexity: O(N) (Queue will visit every node)\n\n- Space complexity: O(N) (Queue will visit every node -> O(N) + 2-D Vector -> O(N))\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>> ans;\n if(root == NULL) return ans;\n bool flag = true;\n queue<TreeNode*> q;\n q.push(root);\n while(!q.empty())\n {\n int size = q.size();\n vector<int> temp(size);\n for(int i = 0; i < size; i++)\n {\n TreeNode* node = q.front();\n q.pop();\n int val = node->val;\n if(flag)\n {\n temp[i] = val;\n }\n else\n {\n temp[size - i - 1] = val;\n }\n if(node->left) q.push(node->left);\n if(node->right) q.push(node->right);\n }\n ans.push_back(temp);\n flag = !flag;\n }\n return ans;\n }\n};\n```
6
0
['Tree', 'Breadth-First Search', 'Queue', 'C++']
2
binary-tree-zigzag-level-order-traversal
Intutive C++ solution (PLEASE UPVOTE)
intutive-c-solution-please-upvote-by-bai-1o4y
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
baibhavsingh07
NORMAL
2023-05-12T15:36:48.566399+00:00
2023-05-12T15:36:48.566431+00:00
459
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n queue<TreeNode*> q;\n int c=0;\n vector<vector<int>>v;\n if(!root)\n return {};\n\n q.push(root);\n \n\n while(!q.empty()){\n vector<int>a;\n int size=q.size();\n c++;\n\n while(size--){\n TreeNode* curr=q.front();\n q.pop();\n\n \n\n a.push_back(curr->val);\n if(curr->left)\n q.push(curr->left);\n\n if(curr->right)\n q.push(curr->right);\n }\n if(c%2==0)\n reverse(a.begin(),a.end());\n v.push_back(a);\n\n }\n return v;\n \n }\n};\n```
6
0
['Tree', 'Breadth-First Search', 'Binary Tree', 'C++']
0
binary-tree-zigzag-level-order-traversal
[C++] 3 Methods ||2queue->1queue||
c-3-methods-2queue-1queue-by-gauravsharm-bhjq
\n\n# Method-1 -> By 2 Stacks\n\n\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n if(root==NULL)return {};\n
gauravsharma459
NORMAL
2023-02-19T07:08:00.562573+00:00
2023-02-19T07:08:32.132148+00:00
640
false
\n\n# Method-1 -> By 2 Stacks\n```\n\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n if(root==NULL)return {};\n stack<TreeNode*>st1,st2;\n st1.push(root);\n vector<vector<int>>res;\n while(!st1.empty()){\n vector<int>t;\n while(!st1.empty()){\n TreeNode*p=st1.top();\n st1.pop();\n t.push_back(p->val);\n if(p->left)st2.push(p->left);\n if(p->right)st2.push(p->right);\n }\n if(t.size()) res.push_back(t);\n t={};\n while(!st2.empty()){\n TreeNode*p=st2.top();\n st2.pop();\n t.push_back(p->val);\n if(p->right)st1.push(p->right);\n if(p->left)st1.push(p->left);\n }\n if(t.size()) res.push_back(t);\n }\n return res;\n }\n};\n```\n# Method-2 ->By 2queue\n\n```\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n if(!root) return {};\n queue<TreeNode*>q1; //this will use for even levels\n queue<TreeNode*>q2; //this will use for odd levels\n q1.push(root);\n q2.push(root);\n int lvl=0;\n vector<vector<int>>res;\n while(!q1.empty()){\n int size=q1.size();\n vector<int>tmp;\n for(int i=0;i<size;i++){\n TreeNode*front1=q1.front();\n TreeNode*front2=q2.front();\n q1.pop();\n q2.pop();\n if(lvl%2==0) tmp.push_back(front1->val); \n \n else tmp.push_back(front2->val);\n \n \n if(front1->left)q1.push(front1->left);\n if(front1->right)q1.push(front1->right);\n //second queue is for odd levels so first we insert right child then left \n if(front2->right)q2.push(front2->right);\n if(front2->left)q2.push(front2->left);\n \n }\n res.push_back(tmp);\n lvl++;\n }\n return res;\n }\n};\n```\n# Method-3 By 1 queue\n```\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n if(root==NULL)return {};\n //optimised one by one queue\n queue<TreeNode*>q;\n q.push(root);\n vector<vector<int>>res;\n bool islefttoright=true;\n while(!q.empty()){\n int s=q.size();\n vector<int>t;\n for(int i=0;i<s;i++){\n TreeNode*front=q.front();\n q.pop();\n t.push_back(front->val);\n if(front->left)q.push(front->left);\n if(front->right)q.push(front->right);\n }\n if(!islefttoright){\n reverse(t.begin(),t.end());\n }\n res.push_back(t);\n islefttoright=!islefttoright;\n \n }\n\n return res;\n }\n};\n```
6
0
['Stack', 'Queue', 'C++']
0
binary-tree-zigzag-level-order-traversal
✅Python3 30ms 🔥🔥 easiest solution
python3-30ms-easiest-solution-by-shivam_-666m
Intuition\n Describe your first thoughts on how to solve this problem. \nUsing BFS level order traversal we can solve this.\n\n# Approach\n Describe your approa
shivam_1110
NORMAL
2023-02-19T05:04:24.151847+00:00
2023-02-19T05:16:56.914515+00:00
1,144
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing BFS level order traversal we can solve this.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- very simple approach.\n- traverse left most node then right nodes.\n- while traversing keep track of level.\n- if level % 2 == 1 then we do right to left, else left to right.\n- while traversing if we\'re on odd level then use stack like structure, like append element at initial index.\n- while traversing if we\'re on even level then use queue like structure and append element at last index.\n- that\'s it.\n- now return values of of dictionary we made in list form.\n\n# Complexity\n- Time complexity: O(height of tree+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 def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n ans = dict()\n def bfs(curr=root, level = 0):\n nonlocal ans\n if curr != None:\n if level % 2 == 1: # go right to left, used stack\n if level in ans.keys():\n ans[level].insert(0, curr.val)\n else:\n ans[level] = [curr.val]\n else: #go left to right, used queue\n if level in ans.keys():\n ans[level].append(curr.val)\n else:\n ans[level] = [curr.val]\n bfs(curr.left, level + 1)\n bfs(curr.right, level + 1)\n return\n bfs()\n return ans.values()\n```\n# Please Like and comment below.\n# (>\u203F\u25E0)\u270C
6
0
['Tree', 'Depth-First Search', 'Breadth-First Search', 'Binary Tree', 'Python3']
1
binary-tree-zigzag-level-order-traversal
C++ | BFS | Reverse | Easy | ~93% Space ~41% Time
c-bfs-reverse-easy-93-space-41-time-by-a-xs9q
\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>> ans;\n if(!root) return {};\n queue
amanswarnakar
NORMAL
2023-02-19T03:40:14.229365+00:00
2023-02-19T03:46:49.530229+00:00
738
false
```\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>> ans;\n if(!root) return {};\n queue<TreeNode *> q;\n q.emplace(root);\n while(!q.empty()){\n int sz = q.size();\n vector<int> temp;\n for(int i = 0; i < sz; i++){\n auto qf = q.front(); q.pop();\n temp.emplace_back(qf->val);\n if(qf->left) q.emplace(qf->left);\n if(qf->right) q.emplace(qf->right);\n }\n ans.emplace_back(temp);\n }\n for(int i = 0; i < ans.size(); i++){\n if(i % 2) reverse(ans[i].begin(), ans[i].end());\n }\n return ans;\n }\n};\n```
6
2
['Breadth-First Search', 'Queue', 'C', 'C++']
1
binary-tree-zigzag-level-order-traversal
✅C++ || ✅O(N) - 100% fast using LEVEL ORDER TRAVERSAL || Explained using comments✅||
c-on-100-fast-using-level-order-traversa-04hh
\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nWe will do Level Order Traversal for each level.\nTake a integer and for each incr
shakya_kr_02
NORMAL
2023-02-17T14:15:26.007928+00:00
2023-02-17T14:15:26.007966+00:00
112
false
\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWe will do Level Order Traversal for each level.\nTake a integer and for each increasing level we will also increment this integer and also push elements of level in a 1D vector and when this integer is divisible by 2, we will reverse the vector and then push back this vector to the 2D vector. \n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n) for queue and vector\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) \n {\n int i=0;\n vector<vector<int>> v;\n // <<IF THE ROOT IS null>>\n if(root==NULL)\n return v;\n queue<TreeNode*> q;\n TreeNode* t=root;\n // <<PUSH THE ROOT NODE IN THE QUEUE>>\n q.push(root);\n while(!q.empty())\n {\n // INCREMENT THE INTEGER FOR EVERY LEVEL\n i++;\n vector<int> v1;\n int s=q.size();\n // <<ITERATING OVER THE CURRENT SIZE OF THE QUEUE>>\n for(int i=0;i<s;i++)\n {\n t=q.front();\n v1.push_back(t->val);\n q.pop();\n if(t->left)q.push(t->left);\n if(t->right)q.push(t->right);\n }\n // <<IF THE INT IS DIVISIBLE BY 2 THEN REVERSE THE 1D VECTOR>>\n if(i%2==0)\n reverse(v1.begin(),v1.end());\n // <<PUSHING 1D VECTOR IN FINAL 2D VECTOR>>\n v.push_back(v1);\n }\n return v;\n }\n};\n```
6
0
['Queue', 'Binary Tree', 'C++']
0
binary-tree-zigzag-level-order-traversal
JavaScript || Easy and well explained code
javascript-easy-and-well-explained-code-s83iz
Explanation:\n\n1. If the root is null, return an empty array.\n1. Initialize a result array result, a queue q to store nodes and a level counter level.\n1. Whi
AdnanAd
NORMAL
2023-01-30T20:05:49.210174+00:00
2023-01-30T20:05:49.210222+00:00
732
false
# Explanation:\n\n1. If the root is null, return an empty array.\n1. Initialize a result array result, a queue q to store nodes and a level counter level.\n1. While the queue q is not empty, do the following:\n1. Get the size of the queue, and initialize an array currLevel to store the current level\'s values.\n1. Loop size times, dequeue the first node node from the queue, push its value to currLevel.\n1. If node has a left child, add it to the queue q.\n1. If node has a right child, add it to the queue q.\n1. If the level is odd, reverse currLevel, and push it to the result array.\n1. Increment the level counter level.\n1. Return the result array.\n- This solution has a time complexity of O(n) and a space complexity of O(n), where n is the number of nodes in the tree.\n\n\n\n\n\n# Code\n```\nvar zigzagLevelOrder = function(root) {\n if (!root) return [];\n \n let result = [], q = [root], level = 0;\n \n while (q.length) {\n let size = q.length, currLevel = [];\n for (let i = 0; i < size; i++) {\n let node = q.shift();\n currLevel.push(node.val);\n if (node.left) q.push(node.left);\n if (node.right) q.push(node.right);\n }\n if (level % 2 === 1) currLevel.reverse();\n result.push(currLevel);\n level++;\n }\n return result;\n};\n\n```\n\nThere are several ways to optimize this solution further:\n\n- Reusing the same array for different levels, instead of creating a new array for each level. This will reduce the memory footprint of the solution.\n\n- Using a queue for the breadth-first search, instead of recursion. This will reduce the call stack size and avoid the risk of stack overflow for large trees.\n\n- Using a stack for reversing the order of the levels, instead of reversing the array after each level. This will reduce the time complexity and the memory usage of the solution.\n
6
0
['Tree', 'Breadth-First Search', 'Binary Tree', 'JavaScript']
0
binary-tree-zigzag-level-order-traversal
✅Easy Java solution||Straight Forward||Beginner Friendly🔥
easy-java-solutionstraight-forwardbeginn-aioh
If you really found my solution helpful please upvote it, as it motivates me to post such kind of codes and help the coding community, if you have some queries
deepVashisth
NORMAL
2022-09-14T19:44:25.604150+00:00
2022-09-14T19:44:25.604183+00:00
357
false
**If you really found my solution helpful please upvote it, as it motivates me to post such kind of codes and help the coding community, if you have some queries or some improvements please feel free to comment and share your views.**\n```\nclass Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> ans = new ArrayList<>();\n if(root == null){\n return ans;\n }\n Queue<TreeNode> q = new LinkedList<>();\n int j = 0;\n q.offer(root);\n while(!q.isEmpty()){\n int size = q.size();\n ArrayList<Integer> al = new ArrayList<>();\n for(int i = 0 ; i < size; i ++){\n TreeNode node = q.poll();\n al.add(node.val);\n if(node.left != null){\n q.offer(node.left);\n }\n if(node.right != null){\n q.offer(node.right);\n }\n }\n if(j%2 == 1){\n Collections.reverse(al);\n }\n ans.add(new ArrayList<>(al));\n j++;\n }\n return ans;\n }\n}\n```
6
0
['Java']
0
binary-tree-zigzag-level-order-traversal
Java DFS based solution || Beats 100%
java-dfs-based-solution-beats-100-by-san-ddbt
Using dfs to generate level order traversal and then reversing every odd level.\n\npublic List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<Li
sanchayharjai37
NORMAL
2021-11-16T12:29:01.164350+00:00
2021-11-16T12:29:01.164396+00:00
132
false
Using dfs to generate level order traversal and then reversing every odd level.\n```\npublic List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> ans = new ArrayList<>();\n dfs(root,0,ans);\n for(int i = 0; i < ans.size(); i++) if((i&1) == 1) Collections.reverse(ans.get(i));\n return ans;\n }\n public void dfs(TreeNode root,int level,List<List<Integer>> list){\n if(root == null) return;\n if(list.size() == level) list.add(new ArrayList<>());\n list.get(level).add(root.val);\n dfs(root.left,level+1,list);\n dfs(root.right,level+1,list);\n }\n```
6
0
[]
0
binary-tree-zigzag-level-order-traversal
My C++ 0ms (faster than 100%) solution with simple explanation.
my-c-0ms-faster-than-100-solution-with-s-18ka
One thing to notice is that whenever we encounter a problem having something related to level order than BFS must come in our mind. Hence by using queue we can
QsR11
NORMAL
2021-09-24T09:48:00.892696+00:00
2021-09-24T13:27:20.344367+00:00
244
false
One thing to notice is that whenever we encounter a problem having something related to level order than BFS must come in our mind. Hence by using queue we can push all children level by level and do the required thing as asked in problem statement.\n\nHere we can see that on zero level we want ans vector to have elements from left to right , on one level we need elements from right to left and so on the pattern continues.\n\nSo our approach will be to store elements from left to right on even level and right to left on odd level.\n\nBelow is the code which will explain the above things with implementation :\n\n```\nclass Solution\n{\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root)\n {\n vector<vector<int>> ans; // Storing answer\n map<int, deque<int>> m; // Storing level wise elements and taking Deque to store elemets from left to right or vice versa\n\n if(root == NULL) // Handling edge cases right upfront\n return ans;\n\n queue<pair<TreeNode*, int>> q; // queue to store address and id(level) of node\n q.push({root, 0}); // Root node with id = 0\n\n while(q.size())\n {\n TreeNode* cur = q.front().F;\n int id = q.front().S;\n q.pop();\n\n if(id % 2) // if level is odd then we need elements from right to left\n m[id].push_front(cur->val);\n\n else // if level is even then we need elements from left to right\n m[id].push_back(cur->val);\n\n // pushing right and left child if they are not null with incrementing id(level)\n\n if(cur->left)\n q.push({cur->left, id + 1});\n\n if(cur->right)\n q.push({cur->right, id + 1});\n\n }\n\n for(auto it = m.begin(); it != m.end(); it++)\n {\n vector<int> mid;\n\n while(i->second.size()) // retrieving elements from deque\n {\n mid.P_B(i->second.front());\n i->second.pop_front();\n\n }\n\n ans.push_back(mid); // pushing into answer vector\n\n }\n\n return ans;\n\n }\n};\n```
6
0
['Breadth-First Search', 'Queue']
0
binary-tree-zigzag-level-order-traversal
BFS C++ 0ms(simple solution)
bfs-c-0mssimple-solution-by-vp-yxyf
This is not the best solution to this problem. This is just an approach in which I am using a bool variable for the zigzag traversal along with an eliminator fo
Vp-
NORMAL
2021-06-29T18:52:54.014909+00:00
2021-06-29T18:52:54.014993+00:00
182
false
This is not the best solution to this problem. This is just an approach in which I am using a bool variable for the zigzag traversal along with an eliminator for clearing out temp before reaching next level.\n \n vector<vector<int>> zigzagLevelOrder(TreeNode* root)\n {\n \n\t\tif(root == NULL)\n return {};\n\t\t\t\n vector<vector<int> > ans;\n deque<TreeNode*> deque;\n TreeNode* eliminator = new TreeNode(404);\n bool right = true;\n vector<int> temp;\n \n deque.push_back(root);\n deque.push_back(eliminator);\n \n while(deque.size() > 1)\n { \n if(right)\n {\n TreeNode* front = deque.front();\n \n if(front == eliminator)\n {\n ans.push_back(temp);\n right = !right;\n temp.clear();\n }\n \n else\n {\n temp.push_back(front->val);\n deque.pop_front(); \n \n if(front->left)\n deque.push_back(front->left);\n if(front->right)\n deque.push_back(front->right); \n }\n }\n \n else\n {\n TreeNode* back = deque.back();\n \n if(back == eliminator)\n {\n ans.push_back(temp);\n right = !right;\n temp.clear();\n }\n \n else\n {\n temp.push_back(back->val);\n deque.pop_back();\n \n if(back->right)\n deque.push_front(back->right); \n if(back->left)\n deque.push_front(back->left);\n }\n }\n }\n ans.push_back(temp);\n return ans;\n }
6
0
[]
0
binary-tree-zigzag-level-order-traversal
Java solution using BFS with Comments: Time and Space: O(n)
java-solution-using-bfs-with-comments-ti-od0c
This is a typical level order traversal with the only difference being that we need to keep track of the direction in which our node values in each level will b
annedevies
NORMAL
2021-05-27T03:18:18.589884+00:00
2021-05-27T03:18:18.589921+00:00
590
false
This is a typical level order traversal with the only difference being that we need to keep track of the direction in which our node values in each level will be returned. If we want a left to right result, we insert values at the end of the list. Otherwise, we insert values at the beginning of the list to achieve a right to left result. For this, we will use a boolean variable to keep track of the direction to traverse.\n\nTime Complexity: O(n)\nSpace Complexity: O(n)\n\n```\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n // initialize an empty result list\n List<List<Integer>> result = new ArrayList<List<Integer>>();\n \n // edge case\n if (root == null) return result;\n \n // boolean variable to keep track of the direction to traverse nodes in a level\n boolean leftToRight = true;\n \n // we\'ll be doing a BFS traversal\n // so declare an empty queue\n Queue<TreeNode> queue = new LinkedList<>();\n queue.offer(root);\n \n while (!queue.isEmpty()) {\n int levelSize = queue.size();\n \n // we\'ll use LinkedList here instead of ArrayList\n // since for right to left traversal\n // we will insert node values at the beginning\n // and with LinkedList we won\'t have to shift elements to the right when we do so\n // which is the case in ArrayList\n List<Integer> currentLevel = new LinkedList<>();\n \n for (int i = 0; i < levelSize; i++) {\n TreeNode currentNode = queue.poll();\n \n if (leftToRight) {\n // add node value to end of list\n currentLevel.add(currentNode.val);\n } else {\n // add node value to beginning of list\n currentLevel.add(0, currentNode.val);\n }\n \n // add the children of the node to the queue\n if (currentNode.left != null) {\n queue.offer(currentNode.left);\n }\n \n if (currentNode.right != null) {\n queue.offer(currentNode.right);\n }\n }\n \n result.add(currentLevel);\n \n // reverse the direction for next level\n leftToRight = !leftToRight;\n }\n \n return result;\n }
6
0
['Breadth-First Search', 'Queue', 'Java']
1
binary-tree-zigzag-level-order-traversal
Python with Queue
python-with-queue-by-sunjppp-87vo
\nclass Solution:\n def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n if not root:\n return []\n \n res = []\n
sunjppp
NORMAL
2019-06-25T22:26:06.183534+00:00
2019-06-26T20:35:00.416801+00:00
851
false
```\nclass Solution:\n def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n if not root:\n return []\n \n res = []\n queue = []\n \n queue.append((root,1))\n while queue:\n n = len(queue)\n nodeList = []\n for _ in range(n):\n curNode, level = queue.pop(0)\n if level%2 == 1:\n nodeList.append(curNode.val)\n else:\n nodeList.insert(0,curNode.val)\n \n if curNode.left: queue.append((curNode.left,level+1))\n if curNode.right: queue.append((curNode.right,level+1))\n \n res.append(nodeList)\n \n return res\n\t```
6
0
['Python']
2
binary-tree-zigzag-level-order-traversal
Java Four Solutions With Explanations
java-four-solutions-with-explanations-by-b3ti
Four solutions can be used to solve this problem that are:\n\n- Deque\n- Queue with Linked List\n- Recursive\n- Double Stack\n\nPlease check below for details.\
steve027
NORMAL
2019-03-12T05:09:50.300198+00:00
2019-03-12T05:09:50.300260+00:00
258
false
Four solutions can be used to solve this problem that are:\n\n- Deque\n- Queue with Linked List\n- Recursive\n- Double Stack\n\nPlease check below for details.\n\n### Solution 1: Deque\n**Idea:**\n- If direction is left->right, poll nodes from end, offer left and right childs to the front\n- If direction is right->left, poll nodes from front, offer right and left childs to the end\n\n**Code:**\n```java\nclass Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> result = new ArrayList<>();\n if (root == null) {\n return result;\n }\n Deque<TreeNode> deque = new LinkedList<>();\n deque.offerLast(root);\n boolean direction = true; // true: left->right, false: right->left\n while (!deque.isEmpty()) {\n int length = deque.size(); // Level length\n List<Integer> line = new ArrayList<>();\n while (length-- > 0) {\n TreeNode node = direction ? deque.pollLast() : deque.pollFirst();\n line.add(node.val);\n if (direction) {\n if (node.left != null) {\n deque.offerFirst(node.left);\n }\n if (node.right != null) {\n deque.offerFirst(node.right);\n }\n } else {\n if (node.right != null) {\n deque.offerLast(node.right);\n }\n if (node.left != null) {\n deque.offerLast(node.left);\n }\n }\n }\n direction = !direction;\n result.add(line);\n }\n return result;\n }\n}\n```\n\n### Solution 2: Queue with Linked List\n**Idea:**\n- Poll nodes from queue\n- If direction is left->right, add values to list\'s tail\n- If direction is right->left, add valus to list\'s head\n\n**Reference:**\n- https://leetcode.com/explore/interview/card/top-interview-questions-medium/108/trees-and-graphs/787/discuss/33814/A-concise-and-easy-understanding-Java-solution\n\n**Code:**\n```java\nclass Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> result = new ArrayList<>();\n if (root == null) {\n return result;\n }\n Queue<TreeNode> queue = new LinkedList<>();\n queue.offer(root);\n boolean direction = true; // true: left->right, false: right->left\n while (!queue.isEmpty()) {\n int length = queue.size(); // Level length\n List<Integer> line = new LinkedList<>(); // Use linked list so that add(0, node.val) is O(1)\n while (length-- > 0) {\n TreeNode node = queue.poll();\n if (direction) {\n line.add(node.val); // Add to tail\n } else {\n line.add(0, node.val); // Add to head\n }\n if (node.left != null) {\n queue.offer(node.left);\n }\n if (node.right != null) {\n queue.offer(node.right);\n }\n }\n result.add(line);\n direction = !direction;\n }\n return result;\n }\n}\n```\n\n### Solution 3: Recursive\n**Idea:**\n- When traversing the tree recursively, keep track of the current visting level (**beginning from 0**)\n- If level is odd, add nodes to the list head\n- If level is even, add nodes to the list tail\n\n**Reference:**\n- https://leetcode.com/explore/interview/card/top-interview-questions-medium/108/trees-and-graphs/787/discuss/33815/My-accepted-JAVA-solution\n\n```java\nclass Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> result = new ArrayList<>();\n zigzagTraverse(root, result, 0); // Level begins from 0\n return result;\n }\n \n private void zigzagTraverse(TreeNode root, List<List<Integer>> result, int level) {\n if (root == null) {\n return;\n }\n if (level == result.size()) {\n result.add(new LinkedList<>()); // Use linked list so that add(0, val) is O(1)\n }\n if ((level & 1) == 1) { // Odd level\n result.get(level).add(0, root.val);\n } else {\n result.get(level).add(root.val);\n }\n zigzagTraverse(root.left, result, level+1);\n zigzagTraverse(root.right, result, level+1);\n }\n}\n```\n\n### Solution 4: Double Stack\n**Idea:**\n- Travese two stacks seperatedly, and add child nodes to the other stack\n- When traversing stack1, push childs left to right\n- When traversing stack2, push childs right to left\n\n**Reference:**\n- https://leetcode.com/explore/interview/card/top-interview-questions-medium/108/trees-and-graphs/787/discuss/33904/JAVA-Double-Stack-Solution\n\n```java\nclass Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> result = new ArrayList<>();\n if (root == null) {\n return result;\n }\n Stack<TreeNode> stack1 = new Stack<>();\n Stack<TreeNode> stack2 = new Stack<>();\n stack1.push(root);\n while (!stack1.isEmpty() || !stack2.isEmpty()) {\n List<Integer> line = new ArrayList<>();\n TreeNode node;\n while (!stack1.isEmpty()) { // Traverse stack1 and push childs to stack2 left to right\n node = stack1.pop();\n line.add(node.val);\n if (node.left != null) {\n stack2.push(node.left);\n }\n if (node.right != null) {\n stack2.push(node.right);\n }\n }\n if (!line.isEmpty()) {\n result.add(line);\n }\n line = new ArrayList<>();\n while (!stack2.isEmpty()) { // Traverse stack2 and push childs to stack1 right to left\n node = stack2.pop();\n line.add(node.val);\n if (node.right != null) {\n stack1.push(node.right);\n }\n if (node.left != null) {\n stack1.push(node.left);\n }\n }\n if (!line.isEmpty()) {\n result.add(line);\n }\n }\n return result;\n }\n}\n```
6
0
[]
0
binary-tree-zigzag-level-order-traversal
Optimal Approach | 0ms 100% beats | BFS Approach 💯
optimal-approach-0ms-100-beats-bfs-appro-8byf
Complexity Time complexity:O(n) Space complexity:O(n) Code
azhan-born-to-win
NORMAL
2025-02-22T03:42:07.706824+00:00
2025-02-22T03:42:07.706824+00:00
1,313
false
# Complexity - Time complexity: $$O(n)$$ - Space complexity: $$O(n)$$ # Code ```python3 [] # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: if not root: return [] result = [] q = deque([root]) ltr = True while q: size = len(q) temp = [0] * size for i in range(size): node = q.popleft() index = i if ltr else (size - 1 - i) temp[index] = node.val if node.left: q.append(node.left) if node.right: q.append(node.right) ltr = not ltr result.append(temp) return result ```
5
0
['Tree', 'Breadth-First Search', 'Binary Tree', 'Python3']
0
binary-tree-zigzag-level-order-traversal
Efficient BFS solution!
efficient-bfs-solution-by-soberrrj-tbsn
IntuitionThe zigzag level order traversal is a variation of the level order traversal (BFS). The key difference is alternating the order of nodes at each level:
SoberrrJ_
NORMAL
2024-12-13T04:45:30.052760+00:00
2024-12-13T04:45:30.052760+00:00
977
false
# Intuition\nThe zigzag level order traversal is a variation of the level order traversal (BFS). The key difference is alternating the order of nodes at each level: left-to-right for one level and right-to-left for the next. We can achieve this by traversing each level normally and reversing the values on alternating levels.\n\n# Approach\n1. Use a `deque` to perform a BFS traversal of the tree.\n2. Maintain a boolean flag `zigzag` to track whether the current level should be reversed.\n3. For each level:\n - Traverse all the nodes in the current level, appending their values to a temporary list.\n - If `zigzag` is `True`, reverse the list before appending it to the final result.\n - Add the children of the nodes to the queue for the next level.\n4. Toggle the `zigzag` flag after processing each level.\n5. Return the final result containing all levels in the desired zigzag order.\n\n# Complexity\n- Time complexity:\nO(n), where \\(n\\) is the number of nodes in the tree.\n\n- Space complexity:\nThe queue can hold up to \\(O(n)\\) nodes when the tree is completely balanced at its last level.\n\n\n# Code\n```python3 []\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n if root is None: return []\n\n queue = deque()\n queue.append(root)\n ans = []\n zigzag = False\n\n while queue:\n level = []\n n = len(queue)\n\n for i in range(n):\n node = queue.popleft()\n level.append(node.val)\n\n if node.left: queue.append(node.left)\n if node.right: queue.append(node.right)\n \n if zigzag:\n level.reverse()\n \n ans.append(level)\n zigzag = not zigzag\n\n return ans\n\n```
5
0
['Python3']
0
binary-tree-zigzag-level-order-traversal
Accepted C++ solution using deque
accepted-c-solution-using-deque-by-harsh-c3vy
\n\n# Approach\n Describe your approach to solving the problem. \nAfter seeing the test cases, we can see a pattern that when we are at odd level (assuming leve
harshsri1602
NORMAL
2024-03-27T00:39:11.913640+00:00
2024-03-27T00:39:11.913669+00:00
28
false
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAfter seeing the test cases, we can see a pattern that when we are at odd level (assuming level of root to be 0), we are taking the Node from the front of the deque and pushing the it\'s right and left node at back of the deque. After seeing this , i.e., insertion and deletion from both ends, we can get the intuition of using a deque.\nThe exact opposite would be true for the nodes at even level.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n- O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n if (!root) return {};\n vector<vector<int>> res;\n deque<TreeNode*> q;\n q.push_back(root); // Pushing the root node to the back of the deque\n int j = 0; // this will help in making the zigzag pattern\n while (!q.empty()) {\n int n = q.size();\n vector<int> temp;\n for (int i = 0; i < n; i++) {\n TreeNode* node;\n if (j & 1) {\n node = q.front();\n q.pop_front();\n } else {\n node = q.back();\n q.pop_back();\n }\n temp.push_back(node->val);\n if (j & 1) {\n if (node->right) {\n q.push_back(node->right); // Pushing right child to the back of the deque\n }\n if (node->left) {\n q.push_back(node->left); // Pushing left child to the back of the deque\n }\n } else {\n if (node->left) {\n q.push_front(node->left); // Pushing left child to the front of the deque\n }\n if (node->right) {\n q.push_front(node->right); // Pushing right child to the front of the deque\n }\n }\n }\n j++;\n res.push_back(temp);\n }\n return res;\n }\n};\n```
5
0
['C++']
0
binary-tree-zigzag-level-order-traversal
Zigzag Level Order Traversal of Binary Tree c++
zigzag-level-order-traversal-of-binary-t-77su
Intuition\nThe intuition behind this code is to traverse a binary tree in a zigzag manner, where each level of the tree is traversed alternately from left to ri
Stella_Winx
NORMAL
2024-03-11T12:10:16.087760+00:00
2024-03-11T12:10:16.087785+00:00
375
false
# Intuition\nThe intuition behind this code is to traverse a binary tree in a zigzag manner, where each level of the tree is traversed alternately from left to right and right to left.\n This zigzag traversal allows us to create a 2D vector where each inner vector represents a level of the tree, and the values within each inner vector are ordered based on the zigzag traversal.\n\n# Approach\nInitialization: \nInitialize an empty 2D vector to store the zigzag level order traversal results. Also, initialize a queue for level order traversal.\n\nLevel Order Traversal with Zigzag Order:\n->Enqueue the root node into the queue.\n->Begin a loop that continues until the queue is empty.\n->Inside the loop, for each level:\nDetermine the number of nodes in the current level.\nInitialize an empty vector to store the values of the nodes in this level.\n->Iterate through all the nodes in the current level:\nDequeue a node from the front of the queue.\nStore its value in the current level\'s vector.\nPush its left and right children (if they exist) for the next level.\n->Push the vector representing the current level into the 2D vector.\n\nZigzag Ordering:\nAfter completing the traversal, go through the 2D vector representing the levels.\nFor every odd-indexed level (0-indexed), reverse the order of elements.\n\nReturn Result: Return the 2D vector containing the zigzag level order traversal results.\n\n\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>>v;\n queue<TreeNode*>q;\n\n if(root==NULL)\n {\n return v;\n }\n q.push(root);\n while(!q.empty())\n {\n int n=q.size();\n //inner list to store curr lvl of elements\n vector<int>in;\n\n //Doing 2 steps\n for(int i=1;i<=n;i++)\n {\n //remove front after storing it\n TreeNode* temp=q.front();\n q.pop();\n in.push_back(temp->val);\n\n //add next lvl elements\n if(temp->left!=NULL)\n {\n q.push(temp->left);\n }\n if(temp->right!=NULL)\n {\n q.push(temp->right);\n }\n }\n v.push_back(in);\n }\n for(int i=0;i<v.size();i++)\n {\n if(i%2!=0)\n {\n reverse(v[i].begin(),v[i].end());\n }\n }\n return v;\n }\n};\n```
5
0
['C++']
1
binary-tree-zigzag-level-order-traversal
Recursion without using reverse(), Beats 100%
recursion-without-using-reverse-beats-10-mi4k
Intuition\n Describe your first thoughts on how to solve this problem. The given problem is like the level order traversal with a slight change.\nHere, every ev
Kartik79
NORMAL
2024-01-11T18:39:04.889111+00:00
2024-01-11T18:39:04.889137+00:00
291
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->The given problem is like the level order traversal with a slight change.\nHere, every even level is reversed.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInstead of using reverse() function we initialse a variable order which decides whether we goto left child first or the right child first.\nAfter each iteration the order variable is negated.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n int height(TreeNode* root) {\n if(!root) return 0;\n int lheight=height(root->left);\n int rheight=height(root->right);\n return max(lheight,rheight)+1;\n }\n void currentlevel(TreeNode* root,int level,bool order,vector<int>& ans) {\n if(!root) return;\n if(level==1) {\n ans.push_back(root->val);\n return;\n }\n if(order) {\n currentlevel(root->left,level-1,order,ans);\n currentlevel(root->right,level-1,order,ans);\n }\n else {\n currentlevel(root->right,level-1,order,ans);\n currentlevel(root->left,level-1,order,ans);\n }\n }\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n int h=height(root);\n vector<vector<int>> res;\n bool order=true;\n for(int i=1; i<h+1; i++) {\n vector<int> ans;\n currentlevel(root,i,order,ans);\n res.push_back(ans);\n order=!order;\n }\n return res;\n }\n};\n```
5
0
['Recursion', 'C++']
0
binary-tree-zigzag-level-order-traversal
✅Easy & Clear Solution Python 3✅
easy-clear-solution-python-3-by-moazmar-qfp1
\n\n# Code\n\nclass Solution:\n def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n res=[]\n def add(i,tree):\n
moazmar
NORMAL
2023-04-04T06:06:43.496511+00:00
2023-04-04T06:06:43.496550+00:00
1,957
false
\n\n# Code\n```\nclass Solution:\n def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n res=[]\n def add(i,tree):\n if len(res)<=i:\n res.append([tree.val])\n else:\n res[i].append(tree.val)\n i+=1\n if tree.left: add(i,tree.left)\n if tree.right: add(i,tree.right)\n if root: \n add(0,root)\n for i in range(len(res)):\n if i%2==1:\n res[i].reverse()\n return res\n \n```
5
0
['Recursion', 'Python3']
0
binary-tree-zigzag-level-order-traversal
🚀️🔥️ Java/Kotlin 2 simple BFS approaches, both O(n) time & space
javakotlin-2-simple-bfs-approaches-both-pu1gr
Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Approach 1\nJust do the classic BFS and on every odd distance reverse the iterated level.
Klemo1997
NORMAL
2023-02-19T18:12:13.854790+00:00
2023-02-19T18:12:13.854838+00:00
233
false
# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Approach 1\nJust do the classic BFS and on every odd distance reverse the iterated level. A bit slower, but quite simple.\n\n```kotlin []\nclass Solution {\n fun zigzagLevelOrder(root: TreeNode?): List<List<Int>> {\n if (root == null) return listOf()\n\n val queue = LinkedList<TreeNode>()\n val ans = arrayListOf<List<Int>>()\n var dist = 0\n queue.addLast(root)\n\n while (queue.isNotEmpty()) {\n val size = queue.size\n val list = arrayListOf<Int>()\n\n for (i in 0 until size) {\n val current = queue.removeFirst()\n current.left?.let { queue.addLast(it) }\n current.right?.let { queue.addLast(it) }\n list.add(current.`val`)\n }\n if (dist % 2 == 1) list.reverse()\n ans.add(list)\n dist++\n }\n\n return ans\n }\n}\n```\n```java []\nclass Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n Queue<TreeNode> queue = new LinkedList<>();\n List<List<Integer>> ans = new ArrayList<>();\n int dist = 0;\n queue.add(root);\n\n while (!queue.isEmpty()) {\n int size = queue.size();\n List<Integer> list = new ArrayList<>();\n\n for (int i = 0; i < size; i++) {\n TreeNode current = queue.poll();\n\n if (current.left != null) queue.add(current.left);\n if (current.right != null) queue.add(current.right);\n list.add(current.val);\n }\n if (list.isEmpty()) break;\n if (dist % 2 == 1) Collections.reverse(list);\n ans.add(list);\n dist++;\n }\n\n return ans;\n }\n}\n```\n\n# Approach 2\nThere goes some linked list magic. We can use different ends for even/odd levels and then just read the opposite end each time.\n\nSteps:\n1. Add root to LL\n2. Then in while loop: if the current dist is even, do the classic - remove from top, insert to last (left, then right child)\n3. if the current dist is odd, then remove from end of list and insert to first (right, then left since we go in reverse)\n\n```kotlin []\nclass Solution {\n fun zigzagLevelOrder(root: TreeNode?): List<List<Int>> {\n if (root == null) return listOf()\n\n val queue = LinkedList<TreeNode>()\n val ans = arrayListOf<List<Int>>()\n var dist = 0\n queue.addLast(root)\n\n while (queue.isNotEmpty()) {\n val size = queue.size\n val list = arrayListOf<Int>()\n\n for (i in 0 until size) {\n if (dist % 2 == 0) {\n val current = queue.removeFirst()\n\n current.left?.let { queue.addLast(it) }\n current.right?.let { queue.addLast(it) }\n list.add(current.`val`)\n } else {\n val current = queue.removeLast()\n\n current.right?.let { queue.addFirst(it) }\n current.left?.let { queue.addFirst(it) }\n list.add(current.`val`)\n }\n }\n\n ans.add(list)\n dist++\n }\n\n return ans\n }\n}\n```\n```java []\nclass Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> ans = new ArrayList<>();\n\n if (root == null) return ans;\n\n LinkedList<TreeNode> queue = new LinkedList<>();\n int dist = 0;\n queue.add(root);\n\n while (!queue.isEmpty()) {\n int size = queue.size();\n List<Integer> list = new ArrayList<>();\n\n for (int i = 0; i < size; i++) {\n if (dist % 2 == 0) {\n TreeNode current = queue.removeFirst();\n\n if (current.left != null) queue.addLast(current.left);\n if (current.right != null) queue.addLast(current.right);\n list.add(current.val);\n } else {\n TreeNode current = queue.removeLast();\n\n if (current.right != null) queue.addFirst(current.right);\n if (current.left != null) queue.addFirst(current.left);\n list.add(current.val);\n }\n }\n\n ans.add(list);\n dist++;\n }\n\n return ans;\n }\n}\n```\n\n
5
0
['Linked List', 'Breadth-First Search', 'Java', 'Kotlin']
1
binary-tree-zigzag-level-order-traversal
BFS Level Order Traversal C++
bfs-level-order-traversal-c-by-heisenber-exy9
Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;
Heisenberg2003
NORMAL
2023-02-19T09:41:18.342491+00:00
2023-02-19T09:41:18.342536+00:00
8,617
false
# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n int level=0;\n queue<TreeNode*>tobetraversed;\n void Traverse(vector<vector<int>>&ans)\n {\n int thisiteration=tobetraversed.size();\n vector<int>values;\n while(thisiteration--)\n {\n if(tobetraversed.front()==NULL)\n {\n tobetraversed.pop();\n continue;\n }\n if(tobetraversed.front()->left!=NULL)\n {\n tobetraversed.push(tobetraversed.front()->left);\n }\n if(tobetraversed.front()->right!=NULL)\n {\n tobetraversed.push(tobetraversed.front()->right);\n }\n values.push_back(tobetraversed.front()->val);\n tobetraversed.pop();\n }\n if(level%2==1)\n {\n reverse(values.begin(),values.end());\n }\n level++;\n ans.push_back(values);\n if(tobetraversed.size()!=0)\n {\n Traverse(ans);\n }\n return;\n }\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>>ans;\n if(root==NULL)\n {\n return ans;\n }\n tobetraversed.push(root);\n Traverse(ans);\n return ans;\n }\n};\n```
5
0
['C++']
0
binary-tree-zigzag-level-order-traversal
📌📌Python3 || ⚡26 ms, faster than 97.08% of Python3
python3-26-ms-faster-than-9708-of-python-s90u
\n\nclass Solution:\n def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n if not root:\n return []\n\n queue
harshithdshetty
NORMAL
2023-02-19T04:33:58.330007+00:00
2023-02-19T04:33:58.330036+00:00
977
false
![image](https://assets.leetcode.com/users/images/3ac0be42-4841-44a1-87f0-a32a71f4b453_1676781049.3290617.png)\n```\nclass Solution:\n def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n if not root:\n return []\n\n queue = deque([root])\n result, direction = [], 1\n\n while queue:\n level = [node.val for node in queue]\n if direction == -1:\n level.reverse()\n result.append(level)\n direction *= -1\n\n for i in range(len(queue)):\n node = queue.popleft()\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n\n return result\n```\n\nHere is a step-by-step description of how it works:\n1. The input to the function is a binary tree, represented by its root node.\n1. The function first checks if the root node is None, in which case it returns an empty list. This is a special case to handle the situation where the tree is empty.\n1. If the root node is not None, the function initializes a queue with the root node and a list to store the final result.\n1. The variable "direction" is also initialized to 1, which is used to alternate the direction of the level traversal between left-to-right and right-to-left.\n1. The function enters a loop that continues until the queue is empty.\n1. Inside the loop, a list "level" is created using a list comprehension. It contains the values of all the nodes in the current level of the tree.\n1. If the direction is -1, the list "level" is reversed, to produce the zigzag traversal effect.\n1. The list "level" is appended to the final result list "result".\n1. The "direction" variable is then multiplied by -1 to alternate the direction of the level traversal in the next iteration.\n1. A nested loop is used to iterate through all the nodes in the current level of the tree.\n1. If a node has a left child, it is added to the queue.\n1. If a node has a right child, it is added to the queue.\n1. The loop continues until all the nodes in the current level have been processed.\n1. The outer loop then repeats the above process for the next level of the tree, until the queue is empty.\n1. The final result list, containing the zigzag level order traversal of the binary tree, is returned.
5
0
['Breadth-First Search', 'Queue', 'Python', 'Python3']
0
binary-tree-zigzag-level-order-traversal
[Python] - BFS - Clean & Simple
python-bfs-clean-simple-by-yash_visavadi-fhuo
\n# Code\nPython [1]\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val
yash_visavadia
NORMAL
2023-02-19T04:13:28.307886+00:00
2023-02-19T04:13:28.307941+00:00
724
false
\n# Code\n``` Python [1]\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n if not root:\n return []\n ans = []\n queue = [root]\n cnt = 0\n while queue:\n temp = queue\n queue = []\n level = []\n for node in temp:\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n level.append(node.val)\n cnt += 1\n if cnt & 1 == 1:\n ans.append(level)\n else:\n ans.append(level[::-1])\n return ans\n\n```
5
0
['Python3']
0
binary-tree-zigzag-level-order-traversal
Binary Tree Zigzag Level Order Traversal with step by step explanation
binary-tree-zigzag-level-order-traversal-gfgo
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nTo traverse the binary tree in a zigzag manner, we can use a breadth-firs
Marlen09
NORMAL
2023-02-16T05:24:26.883577+00:00
2023-02-16T05:24:26.883630+00:00
1,358
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTo traverse the binary tree in a zigzag manner, we can use a breadth-first search (BFS) approach. We can use a queue to store the nodes of the binary tree, and we can use a flag to indicate the direction of the zigzag traversal.\n\nIf the flag is set to left-to-right, we can append the node values from left to right to the current level list. Otherwise, if the flag is set to right-to-left, we can append the node values from right to left to the current level list.\n\nOnce we have appended all the node values for the current level, we can update the flag to switch the direction of the zigzag traversal and append the current level list to the result list.\n\n# Complexity\n- Time complexity:\nThe time complexity of this solution is O(N), where N is the number of nodes in the binary tree, since we need to traverse all the nodes. \n\n- Space complexity:\nThe space complexity of this solution is O(N), since we need to store all the nodes in the queue.\n\n# Code\nHere is the Python3 code with comments explaining each step:\n```\nclass Solution:\n def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n if not root:\n return []\n \n # Initialize the queue with the root node\n queue = [root]\n \n # Initialize the flag to indicate the direction of the zigzag traversal\n is_left_to_right = True\n \n # Initialize the result list\n result = []\n \n while queue:\n # Initialize the current level list\n level = []\n \n # Get the size of the current level\n size = len(queue)\n \n for i in range(size):\n # Remove the first node from the queue\n node = queue.pop(0)\n \n # Append the node value to the current level list\n level.append(node.val)\n \n # Add the left and right children of the node to the queue\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n \n # Update the flag to switch the direction of the zigzag traversal\n if is_left_to_right:\n is_left_to_right = False\n else:\n is_left_to_right = True\n level = level[::-1] # Reverse the current level list if the flag is set to right-to-left\n \n # Append the current level list to the result list\n result.append(level)\n \n return result\n\n```
5
0
['Tree', 'Breadth-First Search', 'Binary Tree', 'Python', 'Python3']
1
binary-tree-zigzag-level-order-traversal
Using two stacks, optimised solution, C++, Commented and Easy to Understand
using-two-stacks-optimised-solution-c-co-relm
Intuition\n Describe your first thoughts on how to solve this problem. \nI\'m using two stacks for this problem as it would take lesser time as each node will g
iaadityaa
NORMAL
2023-01-28T13:00:11.288226+00:00
2023-02-01T12:47:08.916761+00:00
538
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI\'m using two stacks for this problem as it would take lesser time as each node will go inside the stack once and come out of the stack once. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe will create two stacks, one stack will contain the elements in the level order transversal format i.e. left to right and another will contain in the reverse form. \nFurther explanation is in the code itself.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(n)\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>> res;\n if(!root)\n return res; // if root is empty just return empty vector\n stack<TreeNode*> s1,s2; // initialise two stacks\n s1.push(root); // put root inside the first stack\n vector<int> curr; // a vector to contain the elements in the current level\n while(!s1.empty() || !s2.empty()){ // run loop till both of them are empty\n curr.resize(0); // keep the size 0 before going and after coming from a stack\n while(!s1.empty()){ // run a loop till first stack is empty\n TreeNode* temp=s1.top(); // create a node with the top ele. of stack1\n curr.push_back(temp->val); //push the value in curr vector\n s1.pop(); // remove the topmost ele.\n if(temp->left) // if it has left root push inside stack2 \n s2.push(temp->left); // *notice left child is entered first if present*\n if(temp->right) // similarly for right child\n s2.push(temp->right);\n }\n if(s1.empty() && curr.size()>0) // if curr size > 0 only then push curr vector otherwise an empty array will be pushed which we don\'t want\n res.push_back(curr); //push one level\n \n curr.resize(0); // this is important as we\'ve to resize this vector to 0 for another level now\n while(!s2.empty()){ // loop runs exactly the same as stack1 loop \n TreeNode* temp=s2.top();\n curr.push_back(temp->val);\n s2.pop();\n if(temp->right) // * only difference is we will push the right child first if present to maintain a zig zag order*\n s1.push(temp->right);\n if(temp->left)\n s1.push(temp->left);\n }\n if(s2.empty() && curr.size()>0)\n res.push_back(curr); // push this level\n }\n return res; // return the result vector\n }\n};\n```\n\n# Please upvote if you found it helpful.\n
5
0
['C++']
1
binary-tree-zigzag-level-order-traversal
fastest C++ solution
fastest-c-solution-by-tanayhacks08-zwoh
class Solution {\npublic:\n vector> zigzagLevelOrder(TreeNode* root) {\n \n vector> v;\n \n if(root==NULL)\n return v;\n
tanayhacks08
NORMAL
2021-11-29T18:56:26.491990+00:00
2021-11-29T18:56:26.492036+00:00
144
false
class Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n \n vector<vector<int>> v;\n \n if(root==NULL)\n return v;\n queue <TreeNode *>q;\n q.push(root);int flag=0;\n while(!q.empty())\n { int n=q.size();\n vector<int> ans;\n for(int i=0;i<n;i++){\n \n TreeNode *temp=q.front();\n q.pop();\n \n if(temp->left)q.push(temp->left);\n if(temp->right)q.push(temp->right);\n ans.push_back(temp->val);\n }\n \n \n \n if(flag==1)\n {\n reverse(ans.begin(),ans.end());\n flag=0;\n }\n else\n {\n flag=1;\n }\n v.push_back(ans);\n \n \n }\n return v;\n }\n};
5
0
[]
3
binary-tree-zigzag-level-order-traversal
C++ Simple Solution || Space and time less than 82.08% || BFS
c-simple-solution-space-and-time-less-th-y1jq
In this question , we again use BFS for level order traversal , and as we can predict from output that levels on odd layers are being reversed . So thats the te
kush980
NORMAL
2021-05-16T08:07:16.782024+00:00
2021-05-16T08:07:16.782055+00:00
479
false
In this question , we again use **BFS** for level order traversal , and as we can predict from output that levels on odd layers are being reversed . So thats the technique we have used here.\n\n```\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n queue<TreeNode *> q; //Initialising queue , (for bfs mostly we use queue) \n vector<vector<int>> ans; //ans 2D vector\n int c=0; //count variable\n if(!root)\n return ans; //To handle the edge test case i.e. if NULL tree is provided\n q.push(root); //now we push the whole root node in the queue\n while(!q.empty())\n {\n int s = q.size(); //we take the size beforehand so that the changes made inside the loop doesnt affect , how many times it will run\n vector<int> vec; //1D vector to store values \n c++; //we increase count vector every time we go to one layer deep \n for(int i=1;i<=s;i++)\n {\n TreeNode *t = q.front(); \n q.pop();\n vec.push_back(t->val); //we push the value of the current node to the 1D vector\n if(t->left)\n q.push(t->left); //if the left node of the root node is present , then push the left node in the queue\n if(t->right)\n q.push(t->right); //if the right node of the root node is present , then push the right node in the queue\n }\n if(c%2==0) \n reverse(vec.begin(),vec.end()); //now , we took the count variable because there was a pattern in the output that the 1D vector in the 2D vector at even counts are reversed and thats how it was zigzag , so we check the condition and reverse it. \n ans.push_back(vec); //here we push the 1D vector in the ans.\n }\n return ans; //returning the 2D vector as our ans \n }\n};\n```\n**IF you LIKE the solution , DO UPVOTE\nHAPPY CODING;**
5
0
['Breadth-First Search', 'C', 'C++']
0
binary-tree-zigzag-level-order-traversal
Concise Java Solution with BFS
concise-java-solution-with-bfs-by-charle-pqyz
\nclass Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n \n List<List<Integer>> result = new ArrayList<>();\n
CharlesFly
NORMAL
2020-09-01T21:11:23.944655+00:00
2020-09-01T21:11:23.944704+00:00
152
false
```\nclass Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n \n List<List<Integer>> result = new ArrayList<>();\n \n if (root == null)\n return result;\n \n boolean reversed = false;\n Queue<TreeNode> queue = new LinkedList<>();\n queue.offer(root);\n \n while (!queue.isEmpty())\n {\n int size = queue.size();\n List<Integer> list = new ArrayList<>();\n \n for (int i = 0; i < size; i++)\n {\n TreeNode node = queue.poll();\n \n if (reversed)\n list.add(0, node.val);\n else\n list.add(node.val);\n \n if (node.left != null)\n queue.offer(node.left);\n \n if (node.right != null)\n queue.offer(node.right);\n }\n \n reversed = !reversed;\n result.add(list);\n }\n \n return result;\n }\n}\n```
5
0
[]
1
number-of-good-pairs
JAVA | STORY BASED | 0ms | SINGLE PASS | EASY TO UNDERSTAND | SIMPLE | HASHMAP
java-story-based-0ms-single-pass-easy-to-cysx
\n# HANDSHAKES IN GATHERING\n\n# YOU ALL CAN BUY ME A *BEER \uD83C\uDF7A AT \uD83D\uDC47*\n\nhttps://www.buymeacoffee.com/deepakgupta\n\nImagine this problem li
deepak08
NORMAL
2021-09-11T16:59:02.946611+00:00
2023-05-13T11:28:43.596847+00:00
28,009
false
\n# HANDSHAKES IN GATHERING\n\n# **YOU ALL CAN BUY ME A ******BEER \uD83C\uDF7A****** AT \uD83D\uDC47**\n\n**https://www.buymeacoffee.com/deepakgupta**\n\nImagine this problem like, There is a gathering organized by some guy, the guest list is [1,2,3,1,1,3].\nThe problem with the guest is they only handshake with like minded people. (Like minded here is basically the digit should be same , for example, 1 will handshake with 1 only, 2 will handshake with 2 only and so on)\n\n\n\n**So, finally we just need to count number of handshakes in the gathering. \uD83D\uDCAF \uD83D\uDCAF**\n\n(To distinguish , multiple 1\'s and 3\'s , a,b,c,d... letters are used)\n\n**\uD83D\uDD25 the day of arrival \uD83D\uDD25** \n\none by one guests are arriving at the gathering\n\n\u2705 first guest: 1\n\n\u2705 second guest: 2\n(at this moment, in gathering hall we have **1** (2 is about to enter) , since they are not like minded they wont shake hands)\n\n\u2705 third guest:3\n(at this moment, in gathering hall we have **1 ,2** (3 is about to enter), since they are not like minded they wont shake hands)\n\n\u2705 fourth guest : 1\n(at this moment, fourth guest will see in gathering hall , there is **one like minded guy** ie(1) , so he will handshake with him)\ntherefore totalHandShake = 1\n\n\u2705 fifth guest : 1\n(at this moment, fifth guest will see in gathering hall, there are **two like minded guys** ie(1,1) , so he will handshake with them)\ntherefore totalHandShake = 1(last handshake between 1a-1b ) + 2(current handshake between 1a-1c, 1b-1c) = 3\n\n\u2705 sixth guest : 3\n(at this moment, sixth guest will see in gathering hall, there is **one like minded guy** ie(3) , so he will handshake with him)\ntherefore totalHandShake = 3(last handshake) + 1(3a-3b) = 4 \n\n\nHere, in code we can imagine\n\n**given array as guest list.\nHashmap as gathering hall\nans as totalHandshakes.**\n\n# IF YOU GUYS ENJOYED THIS, PLEASE UPVOTE AND COMMENT, THIS GIVES ME HUGE MOTIVATION.\n# **YOU ALL CAN BUY ME A BEER \uD83C\uDF7A AT \uD83D\uDC47**\n\n**https://www.buymeacoffee.com/deepakgupta**\n\n\n\n```\nclass Solution {\n public int numIdenticalPairs(int[] guestList) {\n HashMap<Integer, Integer> hm = new HashMap<>();\n \n int ans = 0;\n \n for(int friend:guestList)\n {\n int friendCount = hm.getOrDefault(friend,0);\n ans+=friendCount;\n hm.put(friend,friendCount+1);\n }\n \n \n return ans;\n }\n}\n```\n\n**SPACE : O(N)\nTIME : O(N)**\n\n\n\n\n
426
3
['Java']
34
number-of-good-pairs
[Java/C++/Python] Count
javacpython-count-by-lee215-b15l
Explanation\ncount the occurrence of the same elements.\nFor each new element a,\nthere will be more count[a] pairs,\nwith A[i] == A[j] and i < j\n\n\n## Comple
lee215
NORMAL
2020-07-12T04:01:37.640818+00:00
2020-07-13T15:35:24.118977+00:00
59,356
false
## **Explanation**\n`count` the occurrence of the same elements.\nFor each new element `a`,\nthere will be more `count[a]` pairs,\nwith `A[i] == A[j]` and `i < j`\n<br>\n\n## **Complexity**\nTime `O(N)`\nSpace `O(N)`\n<br>\n\n**Java:**\n```java\n public int numIdenticalPairs(int[] A) {\n int res = 0, count[] = new int[101];\n for (int a: A) {\n res += count[a]++;\n }\n return res;\n }\n```\n\n**C++:**\n```cpp\n int numIdenticalPairs(vector<int>& A) {\n int res = 0;\n unordered_map<int, int> count;\n for (int a: A) {\n res += count[a]++;\n }\n return res;\n }\n```\n**C++**\n1-line from @generationx2020\n```cpp\n int numIdenticalPairs(vector<int>& A) {\n return accumulate(A.begin(), A.end(), 0, [count = unordered_map<int, int> {}] (auto a, auto b) mutable {\n return a + count[b]++;\n });\n }\n```\n**Python:**\n```py\n def numIdenticalPairs(self, A):\n return sum(k * (k - 1) / 2 for k in collections.Counter(A).values())\n```\n
410
29
[]
86
number-of-good-pairs
✅one line|BEATS 100% Runtime||Explanation✅
one-linebeats-100-runtimeexplanation-by-hf919
Intution\nwe have to count the occurrence of the same elements\nwithA[i] == A[j] and i < j\n\n# Approach\n- We will intiliaze ans with 0 and an emptyunordered m
vishnoi29
NORMAL
2023-10-03T00:04:12.645446+00:00
2023-10-03T06:31:48.946664+00:00
45,850
false
# Intution\nwe have to count the occurrence of the same elements\nwith` A[i] == A[j]` and `i < j`\n\n# Approach\n- We will `intiliaze ans with 0` and an empty` unordered map` to store the occurrence of the element \n- For each element in the given array:\n- Here there will be 2 cases\n 1. if element/number is `present in the map` that means for example at any time in unordered map we saw count of num(element) 1 is 2 thats means currunt element can form 2 pair with previous 1, so at that time `we will add this count in answer` and also` increase the count of the element in out map`\n 2. If element/number is `not present in the map`, it means this is the first time we\'re seeing this number, so we `initialize its count to 1.`\n- At last we will return our answer\n\n# Complexity\n- Time complexity : `O(N)`\n- Space complexity : `O(N)`\n# Codes\n```C++_one_line []\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& A) {\n return accumulate(A.begin(), A.end(), 0, [count = unordered_map<int, int> {}] (auto x, auto y) mutable {\n return x + count[y]++;\n });\n }\n};\n```\n```C++ []\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& A) {\n int ans = 0;\n unordered_map<int, int> cnt;\n for (int x: A) {\n ans += cnt[x]++;\n }\n return ans;\n }\n};\n```\n```java []\nclass Solution {\n public int numIdenticalPairs(int[] A) {\n int ans = 0, cnt[] = new int[101];\n for (int a: A) {\n ans += cnt[a]++;\n }\n return ans;\n }\n}\n```\n```Python []\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n return sum([math.comb(n, 2) for n in collections.Counter(nums).values()]) \n```\n```C# []\n\npublic class Solution\n{\n public int NumIdenticalPairs(int[] A)\n {\n int ans = 0;\n Dictionary<int, int> cnt = new Dictionary<int, int>();\n foreach (int x in A)\n {\n if (cnt.ContainsKey(x))\n ans += cnt[x]++;\n else\n cnt[x] = 1;\n }\n return ans;\n }\n}\n\n```\n```Rust []\n\nuse std::collections::HashMap;\nimpl Solution {\n pub fn num_identical_pairs(a: Vec<i32>) -> i32 {\n let mut ans = 0;\n let mut cnt = HashMap::new();\n \n for x in a.iter() {\n ans += cnt.get(x).unwrap_or(&0);\n *cnt.entry(*x).or_insert(0) += 1;\n }\n \n ans\n }\n}\n\n```\n```ruby []\ndef num_identical_pairs(a)\n ans = 0\n cnt = Hash.new(0)\n \n a.each do |x|\n ans += cnt[x]\n cnt[x] += 1\n end\n \n ans\nend\n\n```\n```javascript []\nfunction numIdenticalPairs(A) {\n let ans = 0;\n const cnt = {};\n \n for (let x of A) {\n ans += cnt[x] || 0;\n cnt[x] = (cnt[x] || 0) + 1;\n }\n \n return ans;\n}\n\n\n```\n```Go []\npackage main\n\nfunc numIdenticalPairs(A []int) int {\n ans := 0\n cnt := make(map[int]int)\n \n for _, x := range A {\n ans += cnt[x]\n cnt[x]++\n }\n \n return ans\n}\n\n```\n```PHP []\nclass Solution {\n\n /**\n * @param Integer[] $nums\n * @return Integer\n */\n function numIdenticalPairs($A) {\n $ans = 0;\n $cnt = [];\n \n foreach ($A as $x) {\n $ans += $cnt[$x] ?? 0;\n $cnt[$x] = ($cnt[$x] ?? 0) + 1;\n }\n \n return $ans;\n}\n\n}\n```\n\n\nIf you really found my solution helpful **please upvote it**, as it motivates me to post such kind of codes.\n**Let me know in comment if i can do better.**\nLet\'s Connect on **[LINKDIN](https://www.linkedin.com/in/mahesh-vishnoi-a4a47a193)**\n\n![upvote.jfif](https://assets.leetcode.com/users/images/b0bf2fa1-1680-41fc-be3f-3ba1c8745505_1675216604.7695017.jpeg)\n\n\n\n
342
4
['Hash Table', 'PHP', 'C++', 'Java', 'Go', 'Python3', 'Rust', 'Ruby', 'JavaScript', 'C#']
23
number-of-good-pairs
[Python] Simple O(n) Solution
python-simple-on-solution-by-eellaup-r9bd
Solution Idea\nThe idea is storing the number of repeated elements in a dictionary/hash table and using mathmatics to calculate the number of combinations.\n\nF
eellaup
NORMAL
2020-07-14T23:29:16.575613+00:00
2020-07-16T18:40:48.861074+00:00
30,200
false
**Solution Idea**\nThe idea is storing the number of repeated elements in a dictionary/hash table and using mathmatics to calculate the number of combinations.\n\n**Fundamental Math Concept (Combinations)**\nThe "# of pairs" can be calculated by summing each value from range 0 to n-1, where n is the "# of times repeated". So the "# of pairs" for the 5 repeated values, would be 0+1+2+3+4 = 10.\n\nAnother way to think about it is:\n\nNotice in the table below how the number of pairs increments by adding the previous "# of times repeated" to the previous "# of pairs."\n\nFor example: to get the "# of pairs" for 3 repeated values, you would add the previous "# of times repeated" (which is 2) with the previous "# of pairs" (which is 1). Therefore, the "# of pairs for 3 repeated values is 2+1=3. In this method, you don\'t peform the same computations multiple times.\n\nExample Table of # of repeated items with their corresponding # of pairs\n<table>\n\t<tr>\n <th># of times repeated</th>\n <th># of pairs</th>\n </tr>\n <tr>\n <td>2</td>\n <td>1</td>\n </tr>\n <tr>\n <td>3</td>\n <td>3</td>\n </tr>\n <tr>\n <td>4</td>\n <td>6</td>\n </tr>\n <tr>\n <td>5</td>\n <td>10</td>\n </tr>\n <tr>\n <td>6</td>\n <td>15</td>\n </tr>\n</table>\n\n**My Code Solution**\n1. Dictionary/Hash Table to store the number of times an element is repeated\n2. Record total number of pairs (num)\n3. Iterate through the nums list\n4. Check to see if each element has already been seen, if not add it to the Hash Table\n5. If it has been seen, but only once, just add 1 to "num"\n6. If it has been seen, multiple times. Add the number of repeated times to "num"\n7. Increment the number of reapeated times by 1.\n7. Move onto next element\n\n```\nclass Solution:\n \n # search for duplicate numbers\n def numIdenticalPairs(self, nums: List[int]) -> int:\n \n # number of good pairs\n repeat = {}\n num = 0\n \n # for every element in nums\n for v in nums:\n \n # number of repeated digits\n if v in repeat:\n \n # count number of pairs based on duplicate values\n if repeat[v] == 1:\n num += 1\n else:\n num += repeat[v]\n \n # increment the number of counts\n repeat[v] += 1\n # number has not been seen before\n else:\n repeat[v] = 1\n # return\n return num\n```
166
2
['Hash Table', 'Math', 'Python', 'Python3']
17
number-of-good-pairs
Java 100% faster | 100% space easy solution
java-100-faster-100-space-easy-solution-ju5lz
Method - 1: We can use two for loops and check is nums[i] = nums[j] and i < j and simply increase count by one every time. I think it will give error of time
hardik_ahir
NORMAL
2020-07-13T03:52:39.324901+00:00
2020-07-13T03:52:52.986792+00:00
15,328
false
Method - 1: We can use two for loops and check is <b> nums[i] = nums[j] </b> and i < j and simply increase count by one every time. I think it will give error of time limit exceeded.\n\nMethod - 2 : First we can count the frequency of each numbers using array. If a number appears n times, then n * (n \u2013 1) / 2 pairs can be made with this number.\n\n```\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n \n int ans = 0;\n int[] count = new int[101];\n \n for(int n: nums)\n count[n]++;\n \n for(int n: count)\n ans += (n * (n - 1))/2;\n \n return ans;\n }\n}\n```
132
3
['Java']
35
number-of-good-pairs
Python O(n) simple dictionary solution
python-on-simple-dictionary-solution-by-j57vr
\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n hashMap = {}\n res = 0\n for number in nums: \n
arturo001
NORMAL
2020-07-22T10:39:55.935855+00:00
2020-10-12T22:23:57.502513+00:00
10,357
false
```\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n hashMap = {}\n res = 0\n for number in nums: \n if number in hashMap:\n res += hashMap[number]\n hashMap[number] += 1\n else:\n hashMap[number] = 1\n return res\n```\n\n- If the value already exists in the hashMap that means the number of new pairs is equal to the frequency since the current value can be paired with each prior occurrence . \n
110
0
['Python3']
8
number-of-good-pairs
Java HashMap O(n)
java-hashmap-on-by-hobiter-knx7
for each i, finds all j where, j < i && nums[j] == nums[i];\n\n public int numIdenticalPairs(int[] nums) {\n int res = 0;\n Map<Integer, Integ
hobiter
NORMAL
2020-07-12T04:01:59.268703+00:00
2020-08-26T02:58:10.172941+00:00
9,705
false
for each i, finds all j where, j < i && nums[j] == nums[i];\n```\n public int numIdenticalPairs(int[] nums) {\n int res = 0;\n Map<Integer, Integer> map = new HashMap<>();\n for (int n : nums) {\n map.put(n, map.getOrDefault(n, 0) + 1);\n res += map.get(n) - 1; // addtional pair can be formed btw n and all previous v == n;\n }\n return res;\n }\n```
69
9
[]
10
number-of-good-pairs
✅98.44%🔥Easy Solution🔥Array & Math🔥
9844easy-solutionarray-math-by-mrake-snfs
Problem\n#### The problem you described is a classic counting problem that asks you to find the number of "good pairs" in an array of integers. A good pair is d
MrAke
NORMAL
2023-10-03T01:38:43.859563+00:00
2023-10-03T01:38:43.859582+00:00
12,898
false
# Problem\n#### The problem you described is a classic counting problem that asks you to find the number of "good pairs" in an array of integers. A good pair is defined as a pair of indices (i, j) where i < j and the elements at those indices in the array are equal (nums[i] == nums[j]).\n---\n# Solution\n#### The given solution uses a nested loop to iterate through all possible pairs of indices (i, j) where i < j. For each pair, it checks whether the elements at those indices are equal, and if they are, it increments the count variable. Finally, it returns the count, which represents the number of good pairs in the array.\n\n##### 1. Initialize a variable count to 0. This variable will be used to keep track of the number of good pairs.\n\n##### 2. Use a for loop to iterate through each index i in the array nums. This loop represents the first element of a potential pair.\n\n##### 3. Within the outer loop, use another for loop to iterate through each index j in the array nums, where j is greater than i. This loop represents the second element of the pair and ensures that i < j.\n\n##### 4. Inside the inner loop, check if nums[i] is equal to nums[j]. If they are equal, it means you\'ve found a good pair, so increment the count variable by 1.\n\n##### 5. Continue this process, checking all possible pairs in the array.\n\n##### 6. After both loops have finished, the count variable will hold the total number of good pairs.\n\n##### 7. Finally, return the count as the result.\n\n#### This solution has a time complexity of O(n^2) because it uses nested loops to compare all possible pairs of elements in the array. For larger arrays, this can be inefficient, so there are more optimized approaches to solving this problem with a time complexity of O(n).\n---\n# Code\n```python []\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n count = 0\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n if nums[i] == nums[j]:\n count += 1\n return count\n```\n```C# []\npublic class Solution {\n public int NumIdenticalPairs(int[] nums) {\n int count = 0;\n for (int i = 0; i < nums.Length; i++) {\n for (int j = i + 1; j < nums.Length; j++) {\n if (nums[i] == nums[j]) {\n count++;\n }\n }\n }\n return count;\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n int count = 0;\n for (int i = 0; i < nums.size(); i++) {\n for (int j = i + 1; j < nums.size(); j++) {\n if (nums[i] == nums[j]) {\n count++;\n }\n }\n }\n return count;\n }\n};\n\n```\n```C []\nint numIdenticalPairs(int* nums, int numsSize) {\n int count = 0;\n \n for (int i = 0; i < numsSize; i++) {\n for (int j = i + 1; j < numsSize; j++) {\n if (nums[i] == nums[j]) {\n count++;\n }\n }\n }\n \n return count;\n}\n\n```\n```Java []\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int count = 0;\n for (int i = 0; i < nums.length; i++) {\n for (int j = i + 1; j < nums.length; j++) {\n if (nums[i] == nums[j]) {\n count++;\n }\n }\n }\n return count;\n }\n}\n\n```\n```javascript []\nvar numIdenticalPairs = function(nums) {\n let count = 0;\n \n for (let i = 0; i < nums.length; i++) {\n for (let j = i + 1; j < nums.length; j++) {\n if (nums[i] === nums[j]) {\n count++;\n }\n }\n }\n \n return count;\n};\n\n```\n\n![9c6f9412-c860-47d6-9a2e-7fcf37ff3321_1686334926.180891.png](https://assets.leetcode.com/users/images/fc3ef886-5fc5-4b2d-aa6c-41e84a7c65dc_1696297073.543429.png)\n
63
2
['Array', 'Hash Table', 'Math', 'C', 'Python', 'C++', 'Java', 'Python3', 'JavaScript', 'C#']
8
number-of-good-pairs
【Video】How we think about a solution - Python, JavaScript, Java, C++
video-how-we-think-about-a-solution-pyth-gw0w
Welcome to my post! This post starts with "How we think about a solution". In other words, that is my thought process to solve the question. This post explains
niits
NORMAL
2025-01-14T16:07:41.716551+00:00
2025-01-14T17:53:48.686841+00:00
2,239
false
Welcome to my post! This post starts with "How we think about a solution". In other words, that is my thought process to solve the question. This post explains how I get to my solution instead of just posting solution codes or out of blue algorithms. I hope it is helpful for someone. # Intuition Using HashMap --- # Solution Video ### ⭐️⭐️ Don't forget to subscribe to my channel! ⭐️⭐️ https://youtu.be/QCL9vE4_k0s ■ Timeline of the video `0:00` Read the question of Number of Good Pairs `0:17` How we think about a solution `1:54` Demonstrate solution with an example. `4:48` Coding `6:05` Time Complexity and Space Complexity **■ Subscribe URL** http://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1 Subscribers: 2,582 My initial goal is 10,000 Thank you for your support! --- # Approach ### How we think about a solution I think the simplest way to solve this question is brute force like this. ``` class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: count = 0 for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] == nums[j]: count += 1 return count ``` Space compelxity is $$O(1)$$ but time complexity is $$O(n^2)$$. Actually this brute force passed all test cases and got success. In real interview, $$O(n^2)$$ is not good for the most cases. Can we improve time complexity? That's how I started thinking $$O(n)$$ time. To improve time, I thought I need to keep number of occurrence of each previous number. In that case, what data structure do you use? --- ⭐️ Points My answer is to use `HashMap` to keep number of occurrence of each previous number. Key is each number and value is the cumulative numbers of each value that I found before. - Why do we need cumulative numbers of each value? That's because when we find new same number in later index, we are sure we can create number of occurrence of the same number pairs with the number we found this time. --- Let's think about a simple example. ``` Input: [1,1,1] Output: 3 ``` From `index 0`, we can create two pairs `(0, 1)` and `(0, 2)` and from `index 1`, we can create one pair `(1, 2)`. That's why we should return `3`(pairs). Let's see inside of `HashMap` We are now `index 0` If we have the same key in `HashMap`, calculate `count`(return value) with `cumulative numbers of current value so far` ``` count = 0, because no data in HashMap ``` then add `current value` as a key and `cumulative numbers of current value so far + 1` as a value ``` HashMap = {1: 1} ``` `+1` is coming from a current value, because we found it this time. At `index 1`, we have `1` in `HashMap`, so calculate `count` with `cumulative numbers of current value so far`. ``` count = 1, coming from HashMap = {1: 1} ``` This indicates `(1, 1)` coming from `index 0` and `index 1` then add `current value` as a key and `cumulative numbers of current value so far + 1` as a value ``` HashMap = {1: 2} ``` At `index 2`, we have `1` in `HashMap`, so calculate `count` with `cumulative numbers of current value so far`. ``` count = 3, coming from HashMap = {1: 2} ``` This indicates `(1, 1)` coming from `index 0` and `index 2` and `(1, 1)` coming from `index 1` and `index 2` ``` Output: 3 ``` Although I was thinking of providing more examples, I believe this should be sufficient for understanding. Let's proceed to review a real algorithm. ### Algorithm Overview: 1. Create a dictionary `pairs` to store the counts of occurrences of each number. 2. Initialize a variable `count` to 0 to keep track of the number of good pairs. 3. Iterate through the input array `nums`. 4. For each element in `nums`, check if it's already in the `pairs` dictionary. 5. If the element is in `pairs`, update the `count` by adding the current count of that element from the `pairs` dictionary. 6. Update the count of the current element in the `pairs` dictionary. 7. Return the total count of good pairs. ### Detailed Explanation: 1. Create an empty dictionary `pairs` to keep track of the counts of each number. 2. Initialize a variable `count` to 0, which will store the count of good pairs. 3. Iterate through the input array `nums` using a `for` loop, using the loop variable `i` to index the elements. 4. Inside the loop, check if the current element `nums[i]` is already a key in the `pairs` dictionary. 5. If `nums[i]` is a key in `pairs`, increment the `count` by the value associated with `nums[i]` in the `pairs` dictionary. This is because for every occurrence of `nums[i]`, it forms a good pair with each previous occurrence. 6. Update the count of occurrences of the current element `nums[i]` in the `pairs` dictionary using `pairs.get(nums[i], 0) + 1`. If `nums[i]` is not a key in `pairs`, this sets its count to 1. If it's already a key, it increments its count. 7. After processing all elements in `nums`, return the total count of good pairs, which is stored in the `count` variable. # Complexity - Time complexity: $$O(n)$$ - Space complexity: $$O(n)$$ For `HashMap`. It depends on size of input array. ```python [] class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: pairs = {} count = 0 for i in range(len(nums)): if nums[i] in pairs: count += pairs[nums[i]] pairs[nums[i]] = pairs.get(nums[i], 0) + 1 return count ``` ```javascript [] /** * @param {number[]} nums * @return {number} */ var numIdenticalPairs = function(nums) { const pairs = {}; let count = 0; for (let i = 0; i < nums.length; i++) { if (nums[i] in pairs) { count += pairs[nums[i]]; } pairs[nums[i]] = (pairs[nums[i]] || 0) + 1; } return count; }; ``` ```java [] class Solution { public int numIdenticalPairs(int[] nums) { Map<Integer, Integer> pairs = new HashMap<>(); int count = 0; for (int i = 0; i < nums.length; i++) { if (pairs.containsKey(nums[i])) { count += pairs.get(nums[i]); } pairs.put(nums[i], pairs.getOrDefault(nums[i], 0) + 1); } return count; } } ``` ```C++ [] class Solution { public: int numIdenticalPairs(vector<int>& nums) { unordered_map<int, int> pairs; int count = 0; for (int i = 0; i < nums.size(); i++) { if (pairs.find(nums[i]) != pairs.end()) { count += pairs[nums[i]]; } pairs[nums[i]] = pairs[nums[i]] + 1; } return count; } }; ``` --- Thank you for reading my post. ⭐️ Please upvote it and don't forget to subscribe to my channel! ⭐️ Subscribe URL http://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1 https://youtu.be/pCc4kR-TdYs
61
0
['Array', 'Hash Table', 'Math', 'Counting', 'C++', 'Java', 'Python3', 'JavaScript']
2
number-of-good-pairs
💯Faster✅💯 Lesser✅4 Methods🔥HashMap🔥Using Combination🔥Two-Pointers Approach🔥Simple Math
faster-lesser4-methodshashmapusing-combi-yjsf
\uD83D\uDE80 Hi, I\'m Mohammed Raziullah Ansari, and I\'m excited to share 4 ways to solve this question with detailed explanation of each approach:\n\n# Proble
Mohammed_Raziullah_Ansari
NORMAL
2023-10-03T02:58:04.170242+00:00
2023-10-03T02:58:04.170265+00:00
5,648
false
# \uD83D\uDE80 Hi, I\'m [Mohammed Raziullah Ansari](https://leetcode.com/Mohammed_Raziullah_Ansari/), and I\'m excited to share 4 ways to solve this question with detailed explanation of each approach:\n\n# Problem Explaination: \n\nThe "Number of Good Pairs" problem is a common coding problem in which we are given an array of integers, and we need to find the number of pairs of indices (i, j) such that the elements at those indices are equal (i.e., nums[i] == nums[j]) and i < j. In simpler terms, you\'re looking for pairs of numbers in the array that have the same value and where the first number appears before the second number in the array.\n\n# \uD83D\uDD0D Methods To Solve This Problem:\nI\'ll be covering four different methods to solve this problem:\n1. Brute Force\n2. Using a Hash Map\n3. Using an Array to Store Frequencies\n4. Using Combinations\n\n# 1. Brute Force: \n- Initialize a variable count to 0.\n- Use two nested loops to iterate through all possible pairs of indices (i, j) where i < j.\n- If nums[i] is equal to nums[j], increment the count by 1.\n- After both loops finish, return the count.\n# Complexity\n- \u23F1\uFE0F Time Complexity: O(n^2) - because of the nested loops.\n\n- \uD83D\uDE80 Space Complexity: O(1) - no additional data structures are used.\n\n# Code\n```Python []\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n count = 0\n n = len(nums)\n for i in range(n):\n for j in range(i + 1, n):\n if nums[i] == nums[j]:\n count += 1\n return count\n```\n```Java []\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int count = 0;\n int n = nums.length;\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n if (nums[i] == nums[j]) {\n count++;\n }\n }\n }\n return count;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n int count = 0;\n int n = nums.size();\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n if (nums[i] == nums[j]) {\n count++;\n }\n }\n }\n return count;\n }\n};\n\n```\n```C []\nint numIdenticalPairs(int* nums, int numsSize) {\n int count = 0;\n for (int i = 0; i < numsSize; i++) {\n for (int j = i + 1; j < numsSize; j++) {\n if (nums[i] == nums[j]) {\n count++;\n }\n }\n }\n return count;\n}\n```\n# 2. Using a Hash Map:\n- Initialize an empty hash map num_count.\nInitialize a variable count to 0.\n- Iterate through the array nums from left to right.\n- For each element num, check if it exists in the num_count hash map.\n- If it exists, increment count by the value associated with num in the hash map, and increment the value by 1.\n- If it doesn\'t exist, add num to the hash map with a value of 1.\n- After iterating through the array, return count.\n# Complexity\n- \u23F1\uFE0F Time Complexity: O(n) - because we iterate through the array once.\n\n- \uD83D\uDE80 Space Complexity: O(n) - in the worst case, we may store all distinct elements in the hash map.\n\n# Code\n```Python []\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n num_count = {}\n count = 0\n for num in nums:\n if num in num_count:\n count += num_count[num]\n num_count[num] += 1\n else:\n num_count[num] = 1\n return count\n```\n```Java []\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n HashMap<Integer, Integer> numCount = new HashMap<>();\n int count = 0;\n for (int num : nums) {\n if (numCount.containsKey(num)) {\n count += numCount.get(num);\n numCount.put(num, numCount.get(num) + 1);\n } else {\n numCount.put(num, 1);\n }\n }\n return count;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n unordered_map<int, int> num_count;\n int count = 0;\n for (int num : nums) {\n if (num_count.find(num) != num_count.end()) {\n count += num_count[num];\n num_count[num]++;\n } else {\n num_count[num] = 1;\n }\n }\n return count;\n }\n};\n```\n```C []\nint numIdenticalPairs(int* nums, int numsSize) {\n int count = 0;\n int num_count[numsSize];\n memset(num_count, 0, sizeof(num_count));\n \n for (int i = 0; i < numsSize; i++) {\n if (num_count[nums[i]]) {\n count += num_count[nums[i]];\n num_count[nums[i]]++;\n } else {\n num_count[nums[i]] = 1;\n }\n }\n return count;\n}\n```\n# 3. Using an Array to Store Frequencies:\n - Initialize an array freq of size 101 (assuming the range of elements in nums is between 1 and 100) and initialize all elements to 0.\n - Initialize a variable count to 0.\n - Iterate through the array nums.\n - For each element num, increment count by the value at index num in the freq array, and then increment the value at index num by 1.\n - After iterating through the array, return count. \n# Complexity\n- \u23F1\uFE0F Time Complexity: O(n) - because we iterate through the array once.\n\n- \uD83D\uDE80 Space Complexity: O(1) - the size of the freq array is fixed at 101.\n\n# Code\n```Python []\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n freq = [0] * 101 \n count = 0\n for num in nums:\n count += freq[num]\n freq[num] += 1\n return count\n```\n```Java []\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int[] freq = new int[101];\n int count = 0;\n for (int num : nums) {\n count += freq[num];\n freq[num]++;\n }\n return count;\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n vector<int> freq(101, 0); \n int count = 0;\n for (int num : nums) {\n count += freq[num];\n freq[num]++;\n }\n return count;\n }\n};\n\n```\n```C []\nint numIdenticalPairs(int* nums, int numsSize) {\n int freq[101] = {0};\n int count = 0;\n for (int i = 0; i < numsSize; i++) {\n count += freq[nums[i]];\n freq[nums[i]]++;\n }\n return count;\n}\n\n```\n# 4. Using Combinations:\n - Initialize a variable count to 0.\n - Iterate through the array nums and for each unique element num, calculate its frequency freq.\n - Calculate the number of pairs that can be formed from freq elements using the formula (freq * (freq - 1)) / 2 (since each pair contributes to the count).\n - Add the result from step 3 to the count.\n - After iterating through the array, return count.\n# Complexity\n- \u23F1\uFE0F Time Complexity: O(n) - because we iterate through the array once to calculate frequencies.\n\n- \uD83D\uDE80 Space Complexity: O(1) - no additional data structures are used.\n\n\n# Code\n```Python []\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n count = 0\n num_freq = collections.Counter(nums)\n for freq in num_freq.values():\n count += (freq * (freq - 1)) // 2\n return count\n\n```\n```Java []\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int count = 0;\n Map<Integer, Integer> numFreq = new HashMap<>();\n for (int num : nums) {\n numFreq.put(num, numFreq.getOrDefault(num, 0) + 1);\n }\n for (int freq : numFreq.values()) {\n count += (freq * (freq - 1)) / 2;\n }\n return count;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n int count = 0;\n unordered_map<int, int> num_freq;\n for (int num : nums) {\n num_freq[num]++;\n }\n for (const auto& entry : num_freq) {\n int freq = entry.second;\n count += (freq * (freq - 1)) / 2;\n }\n return count;\n }\n};\n\n```\n```C []\nint numIdenticalPairs(int* nums, int numsSize) {\n int count = 0;\n int max_num = 0; // Variable to store the maximum element in nums\n for (int i = 0; i < numsSize; i++) {\n if (nums[i] > max_num) {\n max_num = nums[i];\n }\n }\n \n int num_freq[max_num + 1]; // Corrected size based on the maximum element\n memset(num_freq, 0, sizeof(num_freq));\n for (int i = 0; i < numsSize; i++) {\n num_freq[nums[i]]++;\n }\n\n for (int i = 0; i <= max_num; i++) {\n if (num_freq[i] > 1) {\n count += (num_freq[i] * (num_freq[i] - 1)) / 2;\n }\n }\n return count;\n}\n\n```\n# \uD83C\uDFC6Conclusion: \nMethod 3, which uses an array to store frequencies, is the most efficient in terms of both time and space complexity for this problem. Method 2 is also efficient and is particularly useful when the range of elements in nums is large, as it doesn\'t assume a fixed range.\n\n# \uD83D\uDCA1 I invite you to check out my profile for detailed explanations and code for each method. Happy coding and learning! \uD83D\uDCDA
60
2
['Array', 'Hash Table', 'Math', 'Two Pointers', 'C', 'Counting', 'C++', 'Java', 'TypeScript', 'Python3']
11
number-of-good-pairs
Simplest C++ Explanation O(n2) and O(n)
simplest-c-explanation-on2-and-on-by-sac-7r8s
\nO(n2) [100% less memory usage] [75% less time usage]\n\nint numIdenticalPairs(vector<int>& nums) {\n\tint counter = 0;\n\tfor(int i=0;i<nums.size()-1;++i)\n\t
sachuverma
NORMAL
2020-07-12T04:44:46.521090+00:00
2020-07-12T17:42:11.274727+00:00
6,233
false
\n**O(n2)** [100% less memory usage] [75% less time usage]\n```\nint numIdenticalPairs(vector<int>& nums) {\n\tint counter = 0;\n\tfor(int i=0;i<nums.size()-1;++i)\n\t for(int j=i+1;j<nums.size();++j)\n\t\tif(nums[i]==nums[j]) counter++;\n\treturn counter;\n}\n```\n\n\n**O(n)** [100% less memory usage] [100% less time usage]\n```\nint numIdenticalPairs(vector<int>& nums) {\n\tint count[101] = {};\n\tfor (auto n: nums)\n\t\t++count[n];\n\treturn accumulate(begin(count), end(count), 0, [](int s, int i)\n\t\t{ return s + i * (i - 1) / 2; });\n}\n```
59
17
[]
8
number-of-good-pairs
✅ 95.45% Easy Count
9545-easy-count-by-vanamsen-scwe
Intuition\nWhen confronted with the problem of identifying pairs of identical numbers, it\'s natural to consider tracking the occurrences of each number. By kno
vanAmsen
NORMAL
2023-10-03T00:12:12.429807+00:00
2023-10-03T01:07:44.678309+00:00
9,048
false
# Intuition\nWhen confronted with the problem of identifying pairs of identical numbers, it\'s natural to consider tracking the occurrences of each number. By knowing how many times a number has appeared before, we can infer how many pairs can be made with this number.\n\n## Live Coding & Explain\nhttps://youtu.be/87-uryNoEkA?si=1g4SyYuTKdEr5SYr\n\n# Approach\n1. **Initialization**: \n - We create a dictionary, `count`, to maintain the number of occurrences of each number.\n - We also maintain a `result` variable initialized to 0 to count the number of good pairs.\n\n2. **Traversing the List**:\n - For each `num` in the list `nums`:\n - If `num` is already in the dictionary `count`, it means we\'ve seen this number before. \n - Every time we see a repeated number, it can form a pair with its previous occurrences. So, if a number has appeared `k` times before, it can form `k` pairs with this occurrence. We increase the `result` by the count of this number (`count[num]`).\n - We then increase the count of this number in the dictionary.\n - If `num` is not in the dictionary, it means this is the first time we\'re seeing this number, so we initialize its count to 1.\n\n3. **Return Result**:\n - Finally, we return the `result`, which represents the number of good pairs.\n\n# Why It Works\nThis logic works because each time we encounter a repeated number, we know it can form pairs with its previous occurrences. By maintaining a count of each number\'s occurrences, we can quickly determine the number of pairs it can form without having to explicitly enumerate them.\n\n# What We Learned\nThis problem teaches us the power of hashing and its utility in efficiently tracking occurrences or frequencies. By leveraging hash maps (dictionaries in Python), we can achieve solutions that are more efficient than naive approaches, such as nested loops.\n\n# Complexity\n- **Time complexity**: $$O(n)$$ \n - We traverse the list once, and dictionary operations (checking existence, updating value) are generally $$O(1)$$ on average.\n \n- **Space complexity**: $$O(n)$$\n - In the worst case, every number in the list is unique, leading to a dictionary size that is proportional to the size of the list.\n\n# Code\n``` Python []\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n count = {}\n result = 0\n \n for num in nums:\n if num in count:\n result += count[num]\n count[num] += 1\n else:\n count[num] = 1\n \n return result\n```\n``` C++ []\nclass Solution {\npublic:\n int numIdenticalPairs(std::vector<int>& nums) {\n std::unordered_map<int, int> count;\n int result = 0;\n\n for (int num : nums) {\n if (count.find(num) != count.end()) {\n result += count[num];\n count[num]++;\n } else {\n count[num] = 1;\n }\n }\n\n return result;\n }\n};\n```\n``` Java []\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n HashMap<Integer, Integer> count = new HashMap<>();\n int result = 0;\n\n for (int num : nums) {\n count.put(num, count.getOrDefault(num, 0) + 1);\n result += count.get(num) - 1;\n }\n\n return result;\n }\n}\n```\n``` C# []\nusing System.Collections.Generic;\n\npublic class Solution {\n public int NumIdenticalPairs(int[] nums) {\n Dictionary<int, int> count = new Dictionary<int, int>();\n int result = 0;\n\n foreach (int num in nums) {\n if (count.ContainsKey(num)) {\n result += count[num];\n count[num]++;\n } else {\n count[num] = 1;\n }\n }\n\n return result;\n }\n}\n```\n``` Rust []\nuse std::collections::HashMap;\n\nimpl Solution {\n pub fn num_identical_pairs(nums: Vec<i32>) -> i32 {\n let mut count = HashMap::new();\n let mut result = 0;\n\n for &num in &nums {\n let entry = count.entry(num).or_insert(0);\n result += *entry;\n *entry += 1;\n }\n\n result\n }\n}\n```\n``` Go []\nfunc numIdenticalPairs(nums []int) int {\n count := make(map[int]int)\n result := 0\n\n for _, num := range nums {\n if _, exists := count[num]; exists {\n result += count[num]\n count[num]++\n } else {\n count[num] = 1\n }\n }\n\n return result\n}\n```\n``` JavaScript []\nvar numIdenticalPairs = function(nums) {\n let count = {};\n let result = 0;\n\n for (let num of nums) {\n if (num in count) {\n result += count[num];\n count[num]++;\n } else {\n count[num] = 1;\n }\n }\n\n return result;\n};\n```\n``` PHP []\nclass Solution {\n function numIdenticalPairs($nums) {\n $count = [];\n $result = 0;\n\n foreach ($nums as $num) {\n if (isset($count[$num])) {\n $result += $count[$num];\n $count[$num]++;\n } else {\n $count[$num] = 1;\n }\n }\n\n return $result;\n }\n}\n```\n\n## Performance\n| Language | Execution Time (ms) | Memory (MB) |\n|--------------|---------------------|-------------|\n| Rust | 0 | 2.1 |\n| Java | 0 | 40.6 |\n| Go | 1 | 2 |\n| C++ | 3 | 7.6 |\n| PHP | 11 | 19 |\n| Python3 | 33 | 16.2 |\n| JavaScript | 49 | 41.5 |\n| C# | 60 | 38.3 |\n\n![vn.png](https://assets.leetcode.com/users/images/ac230a79-27a3-4222-9d5b-039817dbae2b_1696295253.9515915.png)\n\n
55
9
['Hash Table', 'PHP', 'C++', 'Java', 'Go', 'Python3', 'Rust', 'JavaScript', 'C#']
7
number-of-good-pairs
C++/Java O(n)
cjava-on-by-votrubac-xxsf
We can just count each value. Then, n elements with the same value can form n * (n - 1) / 2 pairs.\n\n> Why? The first element forms n - 1 pairs, the second - n
votrubac
NORMAL
2020-07-12T04:04:21.389859+00:00
2020-07-12T19:21:24.974125+00:00
8,742
false
We can just count each value. Then, `n` elements with the same value can form `n * (n - 1) / 2` pairs.\n\n> Why? The first element forms `n - 1` pairs, the second - `n - 2` pairs and so on. So the sum of the [1, n - 1] progression is `n * (n - 1) / 2`.\n\n**C++**\n```cpp\nint numIdenticalPairs(vector<int>& nums) {\n int cnt[101] = {};\n for (auto n: nums)\n ++cnt[n];\n return accumulate(begin(cnt), end(cnt), 0, [](int s, int i)\n { return s + i * (i - 1) / 2; });\n}\n```\n**Java**\n```java\npublic int numIdenticalPairs(int[] nums) {\n int cnt[] = new int[101], res = 0;\n for (var n: nums)\n ++cnt[n];\n for (int i = 0; i <= 100; ++i)\n res += cnt[i] * (cnt[i] - 1) / 2;\n return res; \n}\n```\n\nWe can also simplify the logic a bit by combining the counting and progression.\n\n**C++**\n```cpp\nint numIdenticalPairs(vector<int>& nums) {\n int cnt[101] = {}, res = 0;\n for (auto n: nums)\n res += cnt[n]++;\n return res;\n}\n```\n\n**Java**\n```java\npublic int numIdenticalPairs(int[] nums) {\n int cnt[] = new int[101], res = 0;\n for (var n: nums)\n res += cnt[n]++;\n return res;\n}\n```
55
3
[]
8
number-of-good-pairs
Clean JavaScript Solution
clean-javascript-solution-by-shimphillip-g8uu
\n// time O(N^2) space O(1)\n var numIdenticalPairs = function(nums) {\n let count = 0\n \n for(let i=0; i<nums.length; i++) {\n for(let j=i+
shimphillip
NORMAL
2020-10-26T23:36:59.924842+00:00
2020-11-13T05:34:17.546126+00:00
5,958
false
```\n// time O(N^2) space O(1)\n var numIdenticalPairs = function(nums) {\n let count = 0\n \n for(let i=0; i<nums.length; i++) {\n for(let j=i+1; j<nums.length; j++) {\n if(nums[i] === nums[j]) {\n count++\n }\n }\n }\n \n return count\n };\n```\n\n```\n// time O(N) space O(N)\nvar numIdenticalPairs = function(nums) {\n const map = {}\n let count = 0\n \n for (const number of nums) {\n if (map[number]) {\n count += map[number];\n map[number] += 1;\n } else {\n map[number] = 1;\n }\n }\n return count\n};\n```
51
0
['JavaScript']
5
number-of-good-pairs
WEEB EXPLAINS PYTHON(BEATS 97.65%)
weeb-explains-pythonbeats-9765-by-skywal-p9ei
\nfirst try btw and its already 97%\n\nOkay, my code looks weird at first glance but its actually pretty easy, just plug in the formula for quadratic sequence\n
Skywalker5423
NORMAL
2021-05-11T07:56:39.770316+00:00
2021-06-23T03:51:39.542439+00:00
3,577
false
![image](https://assets.leetcode.com/users/images/6a27264b-cfe3-42e3-92e0-bfcee79d7d1e_1620717462.3697262.png)\nfirst try btw and its already 97%\n\nOkay, my code looks weird at first glance but its actually pretty easy, just plug in the formula for quadratic sequence\n\t\n\tclass Solution:\n\t\tdef numIdenticalPairs(self, nums: List[int]) -> int:\n\t\t\tnums, memo = sorted(nums), {} # sort to get the total number of digits that have duplicates\n\t\t\tfor i in range(len(nums)-1): # lets say nums = [1,1,1,1,2,2,2,3] the total digits with duplicates is 7\n\t\t\t\tif nums[i] == nums[i+1]: # because nums has 4 ones and 3 twos so it adds up to 7\n\t\t\t\t\tif nums[i] not in memo: # 3 is not counted because there are no duplicates of it\n\t\t\t\t\t\tmemo[nums[i]] = 1\n\t\t\t\t\tmemo[nums[i]] = memo[nums[i]] + 1 \n\t\t\t# nums = [1,1,1,1,2,2,2,3]\n\t\t\t# so now memo = {1 : 4, 2: 3} which means we have 4 ones and 3 twos\n\t\t\tanswer = 0\n\t\t\tfor n in memo.values(): # this is the hard part, please refer to my beautiful drawing to understand this\n\t\t\t\tanswer += (n**2 - n)//2 # after looking at the drawing, we repeat with each n value in memo\n\n\t\t\treturn answer\n\n![image](https://assets.leetcode.com/users/images/62dfbc6c-2157-4b97-bebb-aa4cc1978ac6_1620719423.0946832.png)\n![image](https://assets.leetcode.com/users/images/d3bba77d-366c-4380-a2e6-8e6844184e97_1620719531.481281.png)\n\nDamn, this took some time to do, please give me an upvote if u find it helpful\n\nAnways, i want to recommend an anime called **Karakai Jouzu no Takagi-san(Teasing Master Takagi-san)**\n\n# Episodes: 24 + 1 OVA\n# Genres: Romantic comedy, Slice of life\n\nI love this anime, its wholesome so go check it out!\n
47
1
['Python', 'Python3']
11
number-of-good-pairs
[Java 1 PASS] - One Pass Solution + Intuitive Explanation
java-1-pass-one-pass-solution-intuitive-snn12
1512. Number of Good Pairs\n\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n HashMap<Integer,Integer> map = new HashMap<Integer,Integ
allenjue
NORMAL
2020-11-17T22:34:02.860239+00:00
2020-12-28T01:02:53.451394+00:00
3,497
false
**1512. Number of Good Pairs**\n```\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();\n int answer = 0;\n for(int i: nums){\n if(map.containsKey(i)){ // if number has occurred before\n int temp = map.get(i);\n answer += temp; // add number of occurrences to the answer\n map.put(i,temp+1); // increment number of occurrences\n } else {\n map.put(i,1); // if it is the first time, add it to the map\n }\n }\n return answer;\n }\n}\n```\n**PROBLEM OVERVIEW**\nThe basic premise of the prolem is to find of many times nums[i] == nums[j], where j > i\nWe are esentially tasked with finding the number of repeats after first occurence of each number.\n\n**ASSESSING SOLUTIONS**\nA hashmap is great for this solution as we can looop through the array of numbers and have 1 of 2 states:\n\n* if it exists, then add the number of currently stores and subsequently increment it\n* otherwise, set that value as 1 (it exists)\n\nThe code is O(n), as it iterates through the entire array\n\n**EXPLANATIONS**\nHere\'s a way to visualize it. If I have [1,1], then there is only **1** "good pair," which is the first and second 1. **(0+1 = 1)**\nIf I have [1,1,1] then there are **3** "good pairs" ([first,second], [second,third,], [first,third]). **The first 1 has 0 pairs, the second 1 has 1 pair, and the third 1 has 2 pairs. (0+1+2 = 3)!**\nLikeswise for [1,1,1,1] there are **6** "good pairs" **(0+1+2+3 = 6)**\n\nFrom this, we can conclude the pattern is **for every subsequent repeat of a number, the number of combinations increases by the current number of appearances of that number.**\n\nIn the code, we demonstrate this by incrementing the value in the map by one everytime, signaling the next occurence to add to "answers" one more combination than before.
44
0
['Java']
3
number-of-good-pairs
C++ {Speed,Mem} = {O(n), O(n)} w/o Map + Video
c-speedmem-on-on-wo-map-video-by-crab_10-igia
Since the given nums.length() <= 100, space complexity is O(n).\nhttps://www.youtube.com/watch?v=FlFxSnK2SmY\n\nclass Solution {\npublic:\n int numIdenticalP
crab_10legs
NORMAL
2020-07-15T15:23:39.311214+00:00
2020-08-05T16:48:08.190188+00:00
6,213
false
Since the given nums.length() <= 100, space complexity is O(n).\nhttps://www.youtube.com/watch?v=FlFxSnK2SmY\n```\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n \n int mem[101] ={0};\n int sum=0;\n \n for(int i=0; i < nums.size(); i++){\n sum += mem[nums[i]];\n ++mem[nums[i]];\n }\n \n return sum;\n }\n};\n```
40
3
['C', 'C++']
12
number-of-good-pairs
Python 99.27%, O(n), easy to understand, (its math)
python-9927-on-easy-to-understand-its-ma-qxbj
Because pairs are only created if nums[i] == nums[j] and i < j, we can infer a arithmethic sequence from this condition. \n\nA hint was also given from the exam
berelt
NORMAL
2020-08-31T18:41:40.373831+00:00
2020-08-31T18:41:40.373887+00:00
6,409
false
Because pairs are only created if **nums[i] == nums[j]** and i < j, we can infer a arithmethic sequence from this condition. \n\nA hint was also given from the examples:\n[1,1,1,1] have 6 combination\nThe first 1 have 3 pairs\nThe second 1 have 2 pairs\nThe third 1 have 1 pairs\nHence for 4 of 1\'s, we can have 3 + 2 + 1 combination\n\nThen we just have to store every value count and then count arithmetic sequence sum from 1 to n, given n is the number of appearance for each number.\n\nPlease star it if you like my solution and explanation :), any advice or correction would be appreciated.\n\nThanks !\n\n```\ndef numIdenticalPairs(self, nums: List[int]) -> int:\n pairs = 0\n d = {}\n for i in nums:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for num in d:\n val = d[num]\n for i in range(val):\n pairs += i\n return pairs\n\t```
39
2
['Math', 'Python', 'Python3']
9
number-of-good-pairs
HASH_TABLE|| EXPLAINED line by line || Faster
hash_table-explained-line-by-line-faster-yl60
Before solving the question we will keep two thing in mind.\n1.The use of Vectors\n2.The use of Hashing.\n\nHere, this question can be solved by a direct formul
smritipradhan545
NORMAL
2021-02-24T05:36:25.538934+00:00
2021-02-24T05:36:25.538970+00:00
3,018
false
Before solving the question we will keep two thing in mind.\n1.The use of Vectors\n2.The use of Hashing.\n\nHere, this question can be solved by a direct formula which we will use to find the number of good pairs.\nThe formula is (n*(n-1))/2.\n\n*First we find the count of number occurences of a number. \n*Then store the number count in the dictionary .\n[1,2,3,1,1,3]\n\nkey - value pair\n1 : 3\n2 : 1\n3 : 2\n\n*Then we consider n = value in the hash table\n*using loop calculate the good pairs.\n```\n//Program to find the number of good pairs\n//Good pairs are those in which nums[i] == nums[j] and i<j\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) \n {\n \n unordered_map<int,int> umap; //Initializing a Hash Table\n \n for(int i=0;i<nums.size();i++) //Iterating through the vector\n {\n ++umap[nums[i]]; //Counting the occurences of a number and storing it in value.\n \n }\n int good_pairs = 0;\n for(auto i:umap) //Using the formula \n {\n int n = i.second; //i.second implies -- value of hash table\n good_pairs += ((n)*(n-1))/2;\n \n }\n return good_pairs;\n \n \n }\n};\n \n```\n\n
29
0
['Hash Table', 'C', 'C++']
6
number-of-good-pairs
[C++] Single-pass Solution Explained, 100% Time, ~96% Space
c-single-pass-solution-explained-100-tim-t6zi
This is a nice one that can be solved trivially, but it has some more challenge if you plan on tackling it in a more optimised way. My core intuition was that f
ajna
NORMAL
2020-12-09T18:58:05.977751+00:00
2020-12-09T18:58:05.977795+00:00
3,968
false
This is a nice one that can be solved trivially, but it has some more challenge if you plan on tackling it in a more optimised way. My core intuition was that for each number `n` we basically need to apply the Gaussian formula to its frequency `f`, `-1` (since numbers can\'t form couples with themselves in this problem).\n\nSo, if we encounter `9` once, we have `0` pairs; twice, we have `1` pair; thrice, we have `1 + 2 == 3` pairs; four times, we have `1 + 2 + 3 == 6` pairs and so on.\n\nWith that in mind, we have 2 ways to skin this cat \uD83D\uDC08 : the first one is to add for each number the cumulative frequency of its occurrence so far.\n\nTo do so, we declare 2 support variables;\n* `res` to store our ongoing total;\n* `seen` to collect the frequency of each element (and we know that all the values will go in the `1 - 100` range, so we can just use an array with `101` elements to avoid converting them into a `0`-indexed operation).\n\nFor each number `n`, we will:\n* increase `res` by its previous comulative frequency so far `seen[n]`;\n* increase said frequency by `1` with `seen[n]++`.\n\nOnce done, we can return `res`.\n\nThe code:\n\n```cpp\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n // support variables\n int res = 0, seen[101] = {};\n for (auto n: nums) {\n // for each occurrence, we had the previously found matches to res...\n res += seen[n];\n // ...and then we update seen \n seen[n]++;\n }\n return res;\n }\n};\n```\n\nAlternative version, which would be more perfoming with significantly longer inputs where an optimised multiplicative algorithm trumps manual sums, would do partially the same, first populating `seen` with all the relative frequencies (provided at least one element was found) and then applying the gaussian formula to them.\n\nInterestingly enough, this approach proved to be consistently slower and a bit more demanding in terms of memory (I guess due to how multiplications are usually computed):\n\n```cpp\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n // support variables\n int res = 0, seen[101] = {};\n // populating seen with all the frequencies\n for (int n: nums) seen[n]++;\n // updating res based on the found frequencies\n for (int f: seen) if (f) res += f * (f - 1) / 2;\n return res;\n }\n};\n```
29
0
['Array', 'C', 'Counting', 'C++']
1
number-of-good-pairs
【Video】How we think about a solution - Python, JavaScript, Java, C++
video-how-we-think-about-a-solution-pyth-kcf8
Welcome to my post! This post starts with "How we think about a solution". In other words, that is my thought process to solve the question. This post explains
niits
NORMAL
2023-10-03T03:13:29.697982+00:00
2023-10-04T20:52:45.430213+00:00
1,585
false
Welcome to my post! This post starts with "How we think about a solution". In other words, that is my thought process to solve the question. This post explains how I get to my solution instead of just posting solution codes or out of blue algorithms. I hope it is helpful for someone.\n\n# Intuition\nUsing HashMap\n\n---\n\n# Solution Video\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\nhttps://youtu.be/QCL9vE4_k0s\n\n\u25A0 Timeline of the video\n`0:00` Read the question of Number of Good Pairs\n`0:17` How we think about a solution\n`1:54` Demonstrate solution with an example.\n`4:48` Coding\n`6:05` Time Complexity and Space Complexity\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 2,582\nMy initial goal is 10,000\nThank you for your support!\n\n---\n\n# Approach\n\n### How we think about a solution\n\nI think the simplest way to solve this question is brute force like this.\n\n```\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n count = 0\n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] == nums[j]:\n count += 1\n \n return count\n```\n\nSpace compelxity is $$O(1)$$ but time complexity is $$O(n^2)$$. Actually this brute force passed all test cases and got success.\n\nIn real interview, $$O(n^2)$$ is not good for the most cases. Can we improve time complexity? That\'s how I started thinking $$O(n)$$ time.\n\nTo improve time, I thought I need to keep number of occurrence of each previous number. In that case, what data structure do you use?\n\n\n---\n\u2B50\uFE0F Points\n\nMy answer is to use `HashMap` to keep number of occurrence of each previous number. Key is each number and value is the cumulative numbers of each value that I found before.\n\n- Why do we need cumulative numbers of each value?\n\nThat\'s because when we find new same number in later index, we are sure we can create number of occurrence of the same number pairs with the number we found this time.\n\n---\n\n\n\nLet\'s think about a simple example.\n```\nInput: [1,1,1]\nOutput: 3\n```\nFrom `index 0`, we can create two pairs `(0, 1)` and `(0, 2)` and from `index 1`, we can create one pair `(1, 2)`. That\'s why we should return `3`(pairs).\n\nLet\'s see inside of `HashMap`\n\nWe are now `index 0`\n\nIf we have the same key in `HashMap`, calculate `count`(return value) with `cumulative numbers of current value so far`\n```\ncount = 0, because no data in HashMap\n```\nthen add `current value` as a key and `cumulative numbers of current value so far + 1` as a value\n```\nHashMap = {1: 1}\n```\n`+1` is coming from a current value, because we found it this time.\n\nAt `index 1`, we have `1` in `HashMap`, so calculate `count` with `cumulative numbers of current value so far`.\n```\ncount = 1, coming from HashMap = {1: 1}\n```\nThis indicates `(1, 1)` coming from `index 0` and `index 1`\n\nthen add `current value` as a key and `cumulative numbers of current value so far + 1` as a value\n```\nHashMap = {1: 2}\n```\n \nAt `index 2`, we have `1` in `HashMap`, so calculate `count` with `cumulative numbers of current value so far`.\n```\ncount = 3, coming from HashMap = {1: 2}\n```\nThis indicates `(1, 1)` coming from `index 0` and `index 2` and `(1, 1)` coming from `index 1` and `index 2`\n\n```\nOutput: 3\n```\n\nAlthough I was thinking of providing more examples, I believe this should be sufficient for understanding. Let\'s proceed to review a real algorithm.\n\n\n### Algorithm Overview:\n1. Create a dictionary `pairs` to store the counts of occurrences of each number.\n2. Initialize a variable `count` to 0 to keep track of the number of good pairs.\n3. Iterate through the input array `nums`.\n4. For each element in `nums`, check if it\'s already in the `pairs` dictionary.\n5. If the element is in `pairs`, update the `count` by adding the current count of that element from the `pairs` dictionary.\n6. Update the count of the current element in the `pairs` dictionary.\n7. Return the total count of good pairs.\n\n### Detailed Explanation:\n1. Create an empty dictionary `pairs` to keep track of the counts of each number.\n2. Initialize a variable `count` to 0, which will store the count of good pairs.\n3. Iterate through the input array `nums` using a `for` loop, using the loop variable `i` to index the elements.\n4. Inside the loop, check if the current element `nums[i]` is already a key in the `pairs` dictionary.\n5. If `nums[i]` is a key in `pairs`, increment the `count` by the value associated with `nums[i]` in the `pairs` dictionary. This is because for every occurrence of `nums[i]`, it forms a good pair with each previous occurrence.\n6. Update the count of occurrences of the current element `nums[i]` in the `pairs` dictionary using `pairs.get(nums[i], 0) + 1`. If `nums[i]` is not a key in `pairs`, this sets its count to 1. If it\'s already a key, it increments its count.\n7. After processing all elements in `nums`, return the total count of good pairs, which is stored in the `count` variable.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n\n- Space complexity: $$O(n)$$\nFor `HashMap`. It depends on size of input array.\n\n\n```python []\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n pairs = {}\n count = 0\n\n for i in range(len(nums)):\n if nums[i] in pairs:\n count += pairs[nums[i]]\n \n pairs[nums[i]] = pairs.get(nums[i], 0) + 1\n \n return count\n```\n```javascript []\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar numIdenticalPairs = function(nums) {\n const pairs = {};\n let count = 0;\n\n for (let i = 0; i < nums.length; i++) {\n if (nums[i] in pairs) {\n count += pairs[nums[i]];\n }\n \n pairs[nums[i]] = (pairs[nums[i]] || 0) + 1;\n }\n\n return count; \n};\n```\n```java []\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n Map<Integer, Integer> pairs = new HashMap<>();\n int count = 0;\n\n for (int i = 0; i < nums.length; i++) {\n if (pairs.containsKey(nums[i])) {\n count += pairs.get(nums[i]);\n }\n pairs.put(nums[i], pairs.getOrDefault(nums[i], 0) + 1);\n }\n\n return count; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n unordered_map<int, int> pairs;\n int count = 0;\n\n for (int i = 0; i < nums.size(); i++) {\n if (pairs.find(nums[i]) != pairs.end()) {\n count += pairs[nums[i]];\n }\n pairs[nums[i]] = pairs[nums[i]] + 1;\n }\n\n return count; \n }\n};\n```\n\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\nMy next post for daily coding challenge on Oct 4, 2023\nhttps://leetcode.com/problems/design-hashmap/solutions/4130553/video-how-we-think-about-a-solution-python-javascript-java-c/
28
1
['C++', 'Java', 'Python3', 'JavaScript']
5
number-of-good-pairs
One Pass | O(n) time | Using HashMap
one-pass-on-time-using-hashmap-by-guywit-37cc
This is a basic concept of combinations:\n\nn_C_r = n! / r! * (n-r)!\n\nwhere:\nn_C_r\t= \tnumber of combinations\nn\t= \ttotal number of objects in the set\nr\
guywithimpostersyndrome
NORMAL
2020-12-17T07:06:55.783787+00:00
2022-03-20T18:53:26.820029+00:00
2,361
false
This is a basic concept of **combinations**:\n```\nn_C_r = n! / r! * (n-r)!\n\nwhere:\nn_C_r\t= \tnumber of combinations\nn\t= \ttotal number of objects in the set\nr\t= \tnumber of choosing objects from the set\n```\nHere:\n* The **set** would be with respect to a unique number at a time. (combinations for each distinct number)\n* **n** is the number of occurences and **r = 2**, since we are choosing pairs. So replacing these values will lead to the formula: **n * (n-1)/2**\n**Note**: Even with numbers with frequency 1 in total, the respective pairs will amount to 0 based on above formula. (Hence, 0 pairs)\n\n\n# TL;DR\n**Approach taken with an example:**\n\n- For a number with number of occurences count **n**, the number of good pairs would be: **n * (n-1)/2**\n- We will consider the data structure **HashMap** that will store **key** as the number and number of occurrences as **value**.\n\nSo let\'s say for array **[1,2,3,1,1,3,5,6,5]**, the Hashmap will have the following entries:\n```\n{\n\t1 : 3,\n\t2 : 1,\n\t3 : 2,\n\t5 : 2,\n\t6 : 1\n}\n```\nThe required count would be: **(3 * 2/2) + (1 * 0/2) + (2 * 1/2) + (2 * 1/2) + (1 * 0/2) = 5**\n, which is true since the good pairs are: **(0, 3), (0, 4), (3, 4), (2, 5), (6, 8)**\n\n**Short & Sweet:**\n```\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n Map<Integer, Integer> countMap = new HashMap<>();\n int count = 0;\n \n for(Integer num : nums)\n countMap.put(num, countMap.getOrDefault(num, 0) + 1);\n \n for(Integer currCount : countMap.values())\n count += currCount * (currCount-1)/2;\n \n return count;\n }\n}\n```
26
2
['Java']
4
number-of-good-pairs
My Favorite Story in Maths -- "The Prince of Mathematicians”
my-favorite-story-in-maths-the-prince-of-jksv
https://nrich.maths.org/2478 & https://nrich.maths.org/2478\n\nCarl Friedrich Gauss (1777-1855) is recognised as being one of the greatest mathematicians of all
mcclay
NORMAL
2020-07-12T17:59:21.547653+00:00
2020-07-12T18:02:04.445624+00:00
1,077
false
https://nrich.maths.org/2478 & https://nrich.maths.org/2478\n\nCarl Friedrich Gauss (1777-1855) is recognised as being one of the greatest mathematicians of all time.\n\nThe most well-known story is a tale from when Gauss was still at primary school. One day Gauss\' teacher asked his class to add together all the numbers from 1 to 100, assuming that this task would occupy them for quite a while. He was shocked when young Gauss, after a few seconds thought, wrote down the answer 5050. The teacher couldn\'t understand how his pupil had calculated the sum so quickly in his head, but the eight year old Gauss pointed out that the problem was actually quite simple.\n![image](https://assets.leetcode.com/users/images/0bdd5099-5631-40e9-b3a6-ad5b11ba2eeb_1594576169.009218.png)\n\nHe had added the numbers in pairs \n1. the first and the last (1+100=101)\n2. the second and the second to last (2+99=101) \n3. and so on...\n\nso the total would be 50 lots of 101, which is 5050.\n\n```python\nclass Solution:\n def numIdenticalPairs(self, arr: List[int]) -> int:\n \n\t\t# Gauss\'s insight as a child -> n(n + 1)/2\n def sumASeriesOfConsecutiveNumbers(n):\n return n*(n + 1)//2\n \n res = 0\n c = collections.Counter(arr)\n for v in c.values():\n res += sumASeriesOfConsecutiveNumbers(v-1)\n return res\n```
24
1
[]
4
number-of-good-pairs
✅ 100% | Simple & Mathmatical Approach || Cpp , Java ,Python , Javascript
100-simple-mathmatical-approach-cpp-java-0918
Read article Explaination and codes :https://www.nileshblog.tech/leetcode-1512-number-of-good-pairs/\n\nThe Bruteforce is simplest approach ,we used .The Loopin
user6845R
NORMAL
2023-10-03T07:22:14.456584+00:00
2023-10-03T07:22:14.456607+00:00
1,811
false
# **Read article Explaination and codes :https://www.nileshblog.tech/leetcode-1512-number-of-good-pairs/\n\nThe Bruteforce is simplest approach ,we used .The Looping approach contain two loops and it check every possible pair is good pair or not and we count no of good pairs .\n\n**The Time complexityO(N^2)**\n\nThe Bruteforce is simplest approach ,we used .The Looping approach contain two loops and it check every possible pair is good pair or not and we count no of good pairs .\n\nThe Time complexity of Looping Approach wiill be O(N^2)\n\n2) Mathmatical Approach :\n\n![image](https://assets.leetcode.com/users/images/51b0b380-2311-4918-b5cf-67d760838f98_1696317633.984494.png)\n\n\n![image](https://assets.leetcode.com/users/images/579e7147-841f-47ed-afbe-83861e6f992e_1696317626.8515294.png)\n
22
0
['Python', 'C++', 'Java', 'JavaScript']
1
number-of-good-pairs
[C++/Java/C#/Python] Easy to understand || Clean Code with Comment
cjavacpython-easy-to-understand-clean-co-5c0f
SolutionThis code implements an optimized solution to solve the "Number of Good Pairs" problem. The problem requires counting the number of good pairs in an arr
nitishhsinghhh
NORMAL
2022-05-23T10:22:49.440325+00:00
2025-01-22T11:36:52.622405+00:00
773
false
# Solution This code implements an optimized solution to solve the "Number of Good Pairs" problem. The problem requires counting the number of good pairs in an array of integers. To solve the problem, the code follows these steps: - ##### Initialization: An array called "count" is created with a size of 101. This array will be used to store the counts of each number. Since the problem specifies that the integers in the array are in the range 1 to 100, using an array of size 101 ensures coverage for all possible values. Additionally, a variable named "goodPairs" is initialized to keep track of the count of good pairs found so far. This variable will be returned as the final result. - #### Iteration: The code iterates through the "nums" array using a foreach loop. For each number, denoted as "num," the following steps are performed: a. Incrementing goodPairs: The code increases "goodPairs" by the current count of "num" in the "count" array. This step takes into account the number of existing pairs that "num" can form with previous occurrences of the same number. For example, if there are "x" occurrences of "num" before the current iteration, it means that there are "x" pairs that "num" can form with those previous occurrences. Therefore, "goodPairs" is increased by "x". b. Updating count: The code increments the count of "num" in the "count" array by 1 to account for the current occurrence of "num." This ensures that all occurrences of each number are correctly counted. - #### Return: Finally, the code returns the value of "goodPairs," which represents the total number of good pairs found in the "nums" array. In summary, the code efficiently solves the problem by using an optimized approach with a time complexity of O(n), where "n" is the length of the "nums" array. The space complexity is constant, O(1), as it uses a fixed-size array ("count") to store the counts, which does not depend on the input size. ```C++ [] class Solution { public: /* * Computes the number of good pairs in the given array. * A pair (i, j) is called good if nums[i] == nums[j] and i < j. * * @param nums A vector of integers. * @return The number of good pairs. */ int numIdenticalPairs(vector<int>& nums) { vector<int> count(101, 0); // Initialize a count array for numbers 0-100 int goodPairs = 0; for (int num : nums) { goodPairs += count[num]; // Increase goodPairs by the current count count[num]++; // Increment the count of the number } return goodPairs; } }; ``` ```Java [] class Solution { public int numIdenticalPairs(int[] nums) { int[] count = new int[101]; int goodPairs = 0; for (int num : nums) { goodPairs += count[num]; // Increase goodPairs by the current count count[num]++; // Increment the count of the number } return goodPairs; } } ``` ```csharp [] public class Solution { public int NumIdenticalPairs(int[] nums) { int[] count = new int[101]; int goodPairs = 0; foreach (int num in nums) { goodPairs += count[num]; // Increase goodPairs by the current count count[num]++; // Increment the count of the number } return goodPairs; } } ``` ```Python [] class Solution(object): def numIdenticalPairs(self, nums): count = [0] * 101 goodPairs = 0 for num in nums: goodPairs += count[num] # Increase goodPairs by the current count count[num] += 1 # Increment the count of the number return goodPairs ``` # Frequently encountered in technical interviews ``` std::vector<std::pair<std::string, int>> interview_frequency = { {"Microsoft", 3}, {"Amazon", 3}, {"Adobe", 2}}; ```
22
0
['Array', 'Hash Table', 'Math', 'Counting', 'Python', 'C++', 'Java', 'C#']
0
number-of-good-pairs
Good pairs, Java simple Solution.
good-pairs-java-simple-solution-by-nikhi-gdac
\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int counter = 0;\n\n for(int i = 0; i < nums.length; i++){\n for(int j = i+
Nikhil_Swapper
NORMAL
2023-03-25T18:45:54.178740+00:00
2023-03-25T18:45:54.178774+00:00
4,119
false
```\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int counter = 0;\n\n for(int i = 0; i < nums.length; i++){\n for(int j = i+1; j < nums.length; j++){\n if(nums[i] == nums[j]){\n counter++;\n }\n }\n }\n return counter; \n }\n}\n```\nplease upvote me, to nourish the child of curiosity within me!
21
0
['Array', 'Java']
3
number-of-good-pairs
Simple C++ Solution
simple-c-solution-by-lokeshsk1-re3t
\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n unordered_map<int,int> map;\n int res=0;\n for(int i:nums)\n res+=
lokeshsk1
NORMAL
2020-11-19T08:12:28.730402+00:00
2021-01-03T13:22:40.238550+00:00
1,960
false
```\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n unordered_map<int,int> map;\n int res=0;\n for(int i:nums)\n res+=map[i]++;\n return res;\n }\n};\n```\n\n**Explanation:**\n\n[1,2,3,1,1,3]\nconsider the above example\n\nres=0\n\n* iteration 1: map[1]=0 so res=0+0 =0 and map[1]=0+1 =1\n* iteration 2: map[2]=0 so res=0+0 =0 and map[2]=0+1 =1\n* iteration 3: map[3]=0 so res=0+0 =0 and map[3]=0+1 =1\n* iteration 4: map[1]=1 so res=0+1 =1 and map[1]=1+1 =2\n* iteration 5: map[1]=2 so res=2+1 =3 and map[1]=2+1 =3\n* iteration 6: map[3]=1 so res=3+1 =4 and map[3]=1+1 =2\n\nfinally **res=4** is returned
21
1
['C', 'C++']
4
number-of-good-pairs
Golang O(n) Solution
golang-on-solution-by-aplotd-xvwe
\nfunc numIdenticalPairs(nums []int) int {\n cnt := make(map[int]int)\n var pairs int\n \n for _, num := range nums {\n\t\tpairs += cnt[num] //i
aplotd
NORMAL
2021-01-18T21:06:33.156600+00:00
2021-01-18T22:22:06.320568+00:00
841
false
```\nfunc numIdenticalPairs(nums []int) int {\n cnt := make(map[int]int)\n var pairs int\n \n for _, num := range nums {\n\t\tpairs += cnt[num] //if num not in hash map "cnt", map returns default value of int (ie 0)\n cnt[num]++\n } \n return pairs\n}\n```
20
0
['Go']
3
number-of-good-pairs
Javascript -- 3 solutions
javascript-3-solutions-by-torilov123-xoyq
Brute force solution:\nO(N^2) time + O(1) space\nlogic:\n- nested loop i (start from beginning) & j (start from end)\n- if nums[i] === nums[j], increment count\
torilov123
NORMAL
2020-07-16T04:48:05.336756+00:00
2020-07-16T04:48:05.336790+00:00
2,061
false
**Brute force solution:**\nO(N^2) time + O(1) space\nlogic:\n- nested loop i (start from beginning) & j (start from end)\n- if `nums[i] === nums[j]`, increment count\n```\nvar numIdenticalPairs = function(nums) {\n let count = 0; \n for (let i = 0; i < nums.length; i++) {\n for (let j = nums.length - 1; j > i; j--) {\n if (nums[i] === nums[j]) count++;\n }\n }\n \n return count;\n};\n```\n_____\n**Optimized Time**\nO(N) time + O(N) space\nlogic: \n- Use an object to store numbers (can also use array since this problem have constraint of `1 <= nums[i] <= 100`\n- when new number is added to object, set 1 as value\n- if current number already exist in object, add 1 to current value + add the value to `count`\n```\nvar numIdenticalPairs = function(nums) {\n const map = {};\n let count = 0;\n nums.forEach(num => {\n if (map[num]) {\n count += map[num];\n map[num]++;\n } else {\n map[num] = 1;\n }\n })\n return count;\n};\n```\n____ \n**Optimized Space**\nO(NlogN) time + O(1) space\nlogic: \n- use sorting to sort nums (sorting takes NlogN time)\n- have `curCount = 1` and update it as we see same neighboring numbers in the array\n- add `curCount` to `totalCount`\n- reset `curCount` to 1 when neighboring numbers are not the same\n\n```\nvar numIdenticalPairs = function(nums) {\n nums.sort();\n let totalCount = 0; \n let curCount = 1;\n for (let i = 1; i < nums.length; i++) {\n if (nums[i] === nums[i-1]) {\n totalCount += curCount;\n curCount++;\n } else {\n curCount = 1;\n }\n }\n \n return totalCount;\n};\n```
20
1
['JavaScript']
2
number-of-good-pairs
Python Simple Solutions
python-simple-solutions-by-lokeshsk1-ikpe
Solution 1: Using count\n\n\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n c=0\n for i in range(len(nums)):\n
lokeshsk1
NORMAL
2020-11-19T07:55:30.465347+00:00
2020-11-19T07:55:30.465378+00:00
1,935
false
#### Solution 1: Using count\n\n```\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n c=0\n for i in range(len(nums)):\n c+=nums[:i].count(nums[i])\n return c\n```\n\n#### Solution 2: Using dictionary\n```\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n d={};c=0\n for i in nums:\n if i in d:\n c+=d[i]\n d[i]+=1\n else:\n d[i]=1\n return c\n```
19
1
['Python', 'Python3']
2
number-of-good-pairs
2-lines in JavaScript using counter for O(n), brute O(n^2)
2-lines-in-javascript-using-counter-for-oycva
Short and sweet:\n\nfunction numIdenticalPairs(nums) { // O(n)\n const map = nums.reduce((m, n, i) => m.set(n, (m.get(n)||0) + 1), new Map());\n return [...ma
adriansky
NORMAL
2020-07-18T21:30:22.310434+00:00
2020-07-18T21:30:22.310477+00:00
2,970
false
Short and sweet:\n```\nfunction numIdenticalPairs(nums) { // O(n)\n const map = nums.reduce((m, n, i) => m.set(n, (m.get(n)||0) + 1), new Map());\n return [...map.values()].reduce((num, n) => num + n * (n - 1) / 2, 0);\n};\n```\n\nFirst line, count how many times each number appears.\n2nd line, use the `n(n-1)/2` to get how many combinations are possible.\n\nThis is the intuition for the formula, if you have only one number is zero, if you have a pair is two and so on.\n\n1: 0\n2: 1\n3: 2 + 1 = 3\n4: 3 + 2 + 1 = 6\n5: 4 + 3 + 2 + 1 = 10\n\nSo of the formula to getting all natural number added up is: `n(n-1)/2`.\n\nAlso, you can use the brute force for O(n^2):\n\n```js\nfunction numIdenticalPairs(nums) { // O(n^2)\n\tlet sum = 0;\n\tfor (let i = 0; i < nums.length; i++) {\n\t\tfor (let j = i + 1; j < nums.length; j++) {\n\t\t\tif (nums[i] === nums[j]) sum++;\n\t\t}\n\t}\n\treturn sum;\n}\n```
18
0
['JavaScript']
1
number-of-good-pairs
Swift: Number of Good Pairs
swift-number-of-good-pairs-by-asahiocean-eapa
swift\nclass Solution {\n func numIdenticalPairs(_ nums: [Int]) -> Int {\n var res = 0, map = [Int:Int]()\n nums.forEach {\n res +=
AsahiOcean
NORMAL
2021-04-11T21:11:38.056553+00:00
2021-07-12T19:42:14.850563+00:00
778
false
```swift\nclass Solution {\n func numIdenticalPairs(_ nums: [Int]) -> Int {\n var res = 0, map = [Int:Int]()\n nums.forEach {\n res += map[$0] ?? 0\n map[$0,default: 0] += 1\n }\n return res\n }\n}\n```\n```swift\nimport XCTest\n\n// Executed 3 tests, with 0 failures (0 unexpected) in 0.031 (0.033) seconds\n\nclass Tests: XCTestCase {\n private let s = Solution()\n func test0() {\n XCTAssertEqual(s.numIdenticalPairs([1,2,3,1,1,3]), 4)\n }\n func test1() {\n XCTAssertEqual(s.numIdenticalPairs([1,1,1,1]), 6)\n }\n func test2() {\n XCTAssertEqual(s.numIdenticalPairs([1,2,3]), 0)\n }\n}\n\nTests.defaultTestSuite.run()\n```\n
16
0
['Swift']
2
number-of-good-pairs
Basic Java Solution
basic-java-solution-by-hbhavsar389-nliq
\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int i=0,j=0,c=0;\n \n for(i=0;i<nums.length;i++)\n {\n
hbhavsar389
NORMAL
2020-07-13T05:35:31.470394+00:00
2020-07-13T05:35:31.470427+00:00
1,492
false
```\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int i=0,j=0,c=0;\n \n for(i=0;i<nums.length;i++)\n {\n for(j=i+1;j<nums.length;j++)\n {\n if(nums[i]==nums[j])\n c++;;\n }\n }\n return c;\n }\n}\n```
14
1
['Java']
2
number-of-good-pairs
Simple C++ Code, beats 100% time
simple-c-code-beats-100-time-by-kyouma45-0kby
\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nTake two iterators, traverse one
Kyouma45
NORMAL
2023-04-14T17:21:40.264815+00:00
2023-04-15T06:12:25.129675+00:00
6,529
false
\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTake two iterators, traverse one iterator from other till the end of the vector and check if both have same value or not.\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n std::vector<int>::iterator itr1,itr2;\n int count=0;\n for(itr1=nums.begin();itr1!=nums.end();itr1++)\n {\n for(itr2=itr1+1;itr2!=nums.end();itr2++)\n {\n if(*itr1==*itr2)\n {\n count++;\n }\n }\n }\n return count;\n }\n};\n```
13
0
['C++']
4
number-of-good-pairs
Python O(n) simple solution
python-on-simple-solution-by-tovam-wff0
Python :\n\n\ndef numIdenticalPairs(self, nums: List[int]) -> int:\n\tcountPairs = 0\n\tcounter = {}\n\n\tfor n in nums:\n\t\tif n in counter:\n\t\t\tcountPairs
TovAm
NORMAL
2021-11-07T15:17:37.069296+00:00
2021-11-07T15:17:37.069360+00:00
1,047
false
**Python :**\n\n```\ndef numIdenticalPairs(self, nums: List[int]) -> int:\n\tcountPairs = 0\n\tcounter = {}\n\n\tfor n in nums:\n\t\tif n in counter:\n\t\t\tcountPairs += counter[n]\n\t\t\tcounter[n] += 1\n\n\t\telse:\n\t\t\tcounter[n] = 1\n\n\treturn countPairs\n```\n\n**Like it ? please upvote !**
13
0
['Python', 'Python3']
2
number-of-good-pairs
Clear explanation using Combinations for pairs
clear-explanation-using-combinations-for-ygnl
We are asked to return the total number of pairs in a list of numbers (pair (i,j) is called good if nums[i] == nums[j] and i < j).\n\nFirst, let\'s consider a
alexanco
NORMAL
2021-03-22T19:28:08.499951+00:00
2021-03-23T03:30:04.925451+00:00
1,200
false
We are asked to return the total number of pairs in a list of numbers (`pair (i,j)` is called good if `nums[i] == nums[j]` and `i < j`).\n\nFirst, let\'s consider a list of just one number, e.g. `nums = [1]`. Here, this number cannot be paired with any others (other than itself), so the result is zero.\n\nNext, let\'s consider a list of all idential numbers, e.g. `nums = [1, 1, 1, 1]`. What we are really being asked is how many combinations of two can be made from such a list. Using zero based indexing, we have the following six pairs of such combinations:\n```\n(0, 1), (0, 2), (0, 3) # The first number at index 0 can be paired with the others at index locations 1, 2 and 3.\n (1, 2), (1, 3) # The second at index 1 can be paired with its matching pair at index locations 2 and 3.\n\t\t (2, 3) # The third at index 2 can form a unique pair with the number at index location 3.\n```\n\nMore generally, the combination formula is `n! / [k! * (n - k)!]`. In this problem, `n` represents the count of a given number and `k=2` because we are looking at unique pairs. So the general formula becomes `n! / [2 * (n - 2)!]`. Noting that `n! / (n - 2)!` is simply `n * (n - 1)` after cancelling the factorial terms, the total number of unique pairs of the same number can be calculated as `n * (n - 1) / 2`.\n\nNow let\'s say we are given the following ten mixed numbers:\n`nums = [1, 2, 3, 1, 3, 2, 2, 4, 2, 3]`\n\nThe first thing we want to do is count the number of occurrences of each number, so `number: count of number`\n```\n1: 2\n2: 4\n3: 3\n4: 1\n```\n\nNote that when `n = 1`, then `n * (n - 1) / 2` is simply zero and can hence be ignored (one item cannot be paired with any matching item).\n\nSo, the result is as follows given the above set of ten numbers with their respective counts:\n```\n1: 2 -> 2 * (2 - 1) / 2 = 1\n2: 4 -> 4 * (4 - 1) / 2 = 6\n3: 3 -> 3 * (3 - 1) / 2 = 3\n4: 1 -> 1 * (1 - 1) / 2 = 0\n```\nThe answer in this example is thus `1 + 6 + 3 = 10`.\n\n<strong>Python Implementations</strong>\n\nNote that all of this can be solved simply in python using `Counter` and using a generator expression to sum the calculations for each counted value. Note that `n * (n - 1)` always results in an even number because it is the product of an odd number and an even number. We can therefore use floor division on the summed result because this summed result will be even. All intermediate results are guaranteed to be integers as is the final result. Note that summing everything and then dividing by two just once is slightly more efficient that summing all intermediate `n * (n - 1) / 2` calculations.\n\n```\nfrom collections import Counter\n\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n return sum(num * (num - 1) for num in Counter(nums).values()) // 2\n```\n\nAn alternative solution that just uses one pass (`O(n)` time complexity) to calculated the total pairs:\n\n```\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n pairs = 0\n counts = {}\n for num in nums:\n prior_num_count = counts.get(num, 0)\n pairs += prior_num_count\n counts[num] = prior_num_count + 1\n return pairs\n```\n\nBy observing the cumulative count, one notes that it is equal to the sum of the prior counts plus one minus the current total count (i.e. the prior count). The solution immediately above uses this obvservation, increasing the pairs count by one less than the number of occurrences observed for each number. This solution has the same `O(n)` space complexity as the prior solution, as they both require the use of a dictionary/hashmap to keep track of the counts for each number observed.\n\n```\ncount: sum of prior counts + (count - 1)\n1: 0\n2: 1 (0 + 1)\n3: 3 (1 + 2)\n4: 6 (3 + 3)\n5: 10 (6 + 4)\n```
13
1
['Python', 'Python3']
1
number-of-good-pairs
Java HashMap 100% faster
java-hashmap-100-faster-by-abhishekpatel-2lzp
1. we make a HashMap , which we will use to store freq of each num (How many times every num has appeared in array) \n\n2. we traverse through nums array and fo
abhishekpatel_
NORMAL
2021-05-07T08:55:30.200937+00:00
2021-07-11T03:19:41.192918+00:00
1,789
false
**1.** we make a HashMap<Integer, Integer> , which we will use to store freq of each num (How many times every num has appeared in array) \n\n**2.** we traverse through nums array and for each num :\n* we check if ( it is already present in our HashMap or not ):\n* * A) num is not already present in HashMap : *Then it has only one occurrence and it can not make pair with itself. We simply put it in HashMap with its frequecy as 1.*\n B) num is already present in HashMap : Then it means there are (one or) more than one occurrences of it previously and now it can make pairs. ( but how many pairs? ) \n To know how many pairs? we need to know how many times it has previously appeared in the array ( that\'s why we used HashMap instead of Hashset to store the current frequency of num. )\n we get the frequency ( k ) of num from HashMap ( which is also equal to the number of pairs it can make ). add then add freq ( k) to count [ count += k; ]. Then increment the freq of that num by one and put new freq in hashMap [ hs.put(n, k + 1); ]\n \n** 3.** we count all such pairs in \'count\' variable. which is our final answer.\n\n# CODE:\n\n```\nimport java.util.HashMap;\n\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n HashMap<Integer, Integer> hs = new HashMap<>();\n int count = 0;\n for (int n : nums) {\n if (hs.containsKey(n)) {\n int k = hs.get(n);\n count += k;\n hs.put(n, k + 1);\n } else {\n hs.put(n, 1);\n }\n }\n return count;\n\n }\n}\n```\n\n# **EXAMPLE DRY RUN:**\nwe have have array as { 3,3,3,3 } then we start traversing....\n\n**index 0 :** value = 3.... and frequency(3) = 0.... and good pairs = 0; \n===> update frequency(3) = 1 and still good pairs = 0 bcz only one occurrence of 3 till now.\n\n**index 1:** value = 3.... and frequency(3) = 1.... and good pairs = 0;\n===>access previous frequency(3) = 1 and update good pairs = 0+1 (bcz the \'3\' at \'index 1\' can make *one* new pair with \'3\' at \'index 0\')\n===> update frequency(3) = 2\n\n**index 2:** value = 3.... and frequency(3) = 2.... and good pairs = 1; \n===>access previous frequency(3) = 2 and update good pairs = 0+1+2 (bcz the \'3\' at \'index 2\' can make* two* new pairs with \'3\' at \'index 1\' & with \'3\' at \'index 0\' )\n===> update frequency(3) = 3.\n\n**index 3:** value = 3.... and frequency(3) = 3.... and good pairs = 3;\n===>access previous frequency(3) = 3 and update good pairs = 0+1+2+3 (bcz the \'3\' at \'index 3\' can make* three *new pairs with \'3\' at \'index 2\' & with \'3\' at \'index 1\' & & with \'3\' at \'index 0\')\n===> update frequency(3) = 4.\n\n*good pairs* = 0+1+2+3 = 6
12
1
['Hash Table', 'Java']
2
number-of-good-pairs
JAVA || Beats 100% in Time || O(N) Time O(1) Space || Easy To Understand
java-beats-100-in-time-on-time-o1-space-alxcf
\n\n# Youtube Video Link:\nhttps://youtu.be/DDQvDDY3L2U\n\nPlease like, share,subscribe my YouTube channel.\n\n# Intuition\n- The problem is to count the number
millenium103
NORMAL
2023-10-03T02:33:00.511039+00:00
2023-10-03T02:33:00.511060+00:00
1,169
false
![Screenshot 2023-10-03 075116.png](https://assets.leetcode.com/users/images/bf9eede4-caf0-49ec-b810-22b01518dbad_1696300001.6432285.png)\n\n# Youtube Video Link:\n[https://youtu.be/DDQvDDY3L2U]()\n\nPlease like, share,subscribe my YouTube channel.\n\n# Intuition\n- The problem is to count the number of good pairs in the given array. A good pair is defined as a pair of indices (i, j) where `nums[i] == nums[j]` and `i < j`. To solve this efficiently, we can use a counting approach. We\'ll count the occurrences of each number in the array and then calculate the number of good pairs for each count. Finally, we\'ll sum up the counts of good pairs for all numbers to get the total count of good pairs in the array.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize a variable `ans` to `0`. This variable will store the count of good pairs.\n\n2. Create an array count of size `101` (since the constraints specify that `1 <= nums[i] <= 100`). This array will be used to count the occurrences of each number. Initialize all elements of `count` to 0.\n\n3. Iterate through the `nums` array and for each number `n` at index `i`, increment `count[n]` by `1` to count the occurrences of `n`.\n\n4. After counting the occurrences, iterate through the `count` array. For each count `n`, calculate the number of good pairs using the formula `(n * (n - 1)) / 2`. This formula represents the number of pairs that can be formed with n occurrences.\n\n5. Add the count of good pairs for each number to the `ans` variable.\n\n6. Return the final value of `ans`, which represents the total count of good pairs in the array.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: `O(N)`, the first loop that counts occurrences of each number takes O(N) time, where N is the length of the nums array.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(1)`, beacuse we have used the count array which is of `constant` size.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int ans = 0;\n int count[] = new int[101];\n\n for(int n:nums)\n {\n count[n]++;\n } \n for(int n:count)\n {\n ans+=(n*(n-1))/2; \n }\n return ans;\n }\n}\n```\n![upvote.png](https://assets.leetcode.com/users/images/0907c0cf-208c-469e-bef6-0f8ceb9316ad_1696299970.9515321.png)\n
10
0
['Java']
4
number-of-good-pairs
✅ Beats 100% || 💡 C++ Easy Map-Based Solution || 🎬 Animation
beats-100-c-easy-map-based-solution-anim-mlrk
Intuition\n Describe your first thoughts on how to solve this problem. \n\n\n\n# Approach\n1. Create an unordered map called mp to store the frequency of each n
Tyrex_19
NORMAL
2023-10-03T02:08:37.569447+00:00
2023-10-03T03:29:26.967811+00:00
530
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n![ezgif.com-video-to-gif (12).gif](https://assets.leetcode.com/users/images/07fa1459-e7b2-410a-8656-69459d02a7f5_1696303312.0705419.gif)\n\n\n# Approach\n1. Create an unordered map called mp to store the frequency of each number in the input vector.\n\n1. Iterate through each element, num and increment the corresponding value in the map mp for the current number num.\n\n1. Initialize a variable result to 0. This variable will be used to store the final count of identical pairs.\n\n1. Iterate through the key-value pairs in the map mp using an iterator.\n\n1. For each key-value pair, retrieve the count of occurrences of the number (stored in the second element of the pair) and subtract 1 from it. Assign the result to the variable mx.\n\n 1. Calculate the number of identical pairs that can be formed with mx occurrences of the number using the formula (1 + mx) * mx / 2. This formula represents the sum of an arithmetic series, where mx is the number of terms and (1 + mx) is the sum of the first and last element.\n\n 1. Add the calculated count to the result variable.\n\n1. Once all the key-value pairs have been processed, return the final count of identical pairs stored in the variable result.\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 int numIdenticalPairs(vector<int>& nums) {\n unordered_map<int, int> mp;\n for(int num: nums) mp[num]++;\n int result = 0;\n for(auto it = mp.begin(); it != mp.end(); it++){\n int mx = it->second - 1;\n result += (1 + mx) * mx / 2;\n }\n return result;\n }\n};\n```\n\nhttps://youtu.be/DBWbzqJnaa8
10
0
['C++']
1
number-of-good-pairs
C# - Simple O(N ^ 2) solution
c-simple-on-2-solution-by-christris-k3cr
csharp\npublic int NumIdenticalPairs(int[] nums) \n{\n\tint count = 0;\n\n\tfor(int i = 0; i < nums.Length; i++)\n\t{\n\t\tfor(int j = i + 1; j < nums.Length; j
christris
NORMAL
2020-07-12T04:11:35.061356+00:00
2020-07-12T04:11:35.061398+00:00
638
false
```csharp\npublic int NumIdenticalPairs(int[] nums) \n{\n\tint count = 0;\n\n\tfor(int i = 0; i < nums.Length; i++)\n\t{\n\t\tfor(int j = i + 1; j < nums.Length; j++)\n\t\t{\n\t\t\tif(nums[i] == nums[j])\n\t\t\t{\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn count;\n}\n```
10
2
[]
0