title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
tag
stringclasses
643 values
level
stringclasses
3 values
question_hints
stringclasses
869 values
view_count
int64
19
630k
vote_count
int64
5
3.67k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
Populating Next Right Pointers in Each Node
populating-next-right-pointers-in-each-node
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
37,398
396
Simply do it level by level, using the `next`-pointers of the current level to go through the current level and set the `next`-pointers of the next level.\n\nI say "real" O(1) space because of the many recursive solutions ignoring that recursion management needs space.\n\n def connect(self, root):\n while root and root.left:\n next = root.left\n while root:\n root.left.next = root.right\n root.right.next = root.next and root.next.left\n root = root.next\n root = next
11,416
Populating Next Right Pointers in Each Node
populating-next-right-pointers-in-each-node
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
486
7
# * Extra space but clean code\n---\n```java []\nclass Solution {\n public Node connect(Node root) {\n if(root == null)\n return root;\n Queue<Node> queue = new LinkedList<>();\n queue.add(root);\n while(queue.size() > 0)\n {\n Deque<Node> dq = new ArrayDeque<>();\n int length = queue.size();\n for(int i = 0;i<length;i++)\n {\n Node curr = queue.poll();\n dq.addLast(curr);\n if(curr.left!=null)\n queue.add(curr.left);\n if(curr.right!=null)\n queue.add(curr.right);\n }\n while(dq.size() > 1)\n {\n Node popped = dq.removeFirst();\n popped.next = dq.getFirst();\n }\n Node popped = dq.removeFirst();\n popped.next = null;\n }\n return root;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n Node* connect(Node* root) {\n if(root == nullptr)\n return root;\n queue<Node*> queue;\n queue.push(root);\n while(queue.size() > 0)\n {\n deque<Node*> dq;\n int length = queue.size();\n for(int i = 0;i<length;i++)\n {\n Node* curr = queue.front();\n queue.pop();\n dq.push_back(curr);\n if(curr->left!=nullptr)\n queue.push(curr->left);\n if(curr->right!=nullptr)\n queue.push(curr->right);\n }\n while(dq.size() > 1)\n {\n Node* popped = dq.front();\n dq.pop_front();\n popped->next = dq.front();\n }\n Node* popped = dq.front();\n dq.pop_front();\n popped->next = nullptr;\n }\n return root;\n }\n};\n```\n```python []\nclass Solution:\n def connect(self, root: \'Node\') -> \'Node\':\n if not root:\n return root\n queue = []\n queue.append(root)\n while queue:\n dq = collections.deque()\n length = len(queue)\n for i in range(length):\n curr = queue.pop(0)\n dq.append(curr)\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n while len(dq) > 1:\n popped = dq.popleft()\n popped.next = dq[0]\n popped = dq.popleft()\n popped.next = None\n return root\n```\n---\n>### *Please don\'t forget to upvote if you\'ve liked my solution.* \u2B06\uFE0F\n---
11,429
Populating Next Right Pointers in Each Node
populating-next-right-pointers-in-each-node
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
349
6
***Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome*.**\n___________________\n_________________\n***Q116. Populating Next Right Pointers in Each Node***\n\nYou are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:\n```\nstruct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n}\n```\nPopulate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.\nInitially, all next pointers are set to NULL.\n____________________________________________________________________________________________________________________\n\n***Time complexity*** - O(n)\n***Space complexity*** - O(1)\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **Java Code** :\n**Runtime**: 0 ms, faster than 100.00% of Java online submissions for Populating Next Right Pointers in Each Node.\n```\nclass Solution {\n public Node connect(Node root) {\n if(root == null) return root;\n Node current = root;\n while(current != null) {\n Node level1stNode = current;\n while(current != null) \n {\n if(current.left != null) \n current.left.next = current.right;\n if(current.right != null && current.next != null) \n current.right.next = current.next.left;\n\n current = current.next;\n }\n current = level1stNode.left;\n }\n return root;\n }\n}\n```\n**Runtime:** 0ms\n**Memory Usage:** 42.2 MB\n\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **Python Code** :\n\n```\nclass Solution:\n def connect(self, root: \'Optional[Node]\') -> \'Optional[Node]\':\n if not root: return root \n self.current = root\n while self.current:\n self.level1stNode = self.current\n while self.current:\n if self.current.left:\n self.current.left.next = self.current.right\n \n if self.current.right and self.current.next:\n self.current.right.next = self.current.next.left\n \n self.current = self.current.next\n self.current = self.level1stNode.left\n return root\n```\n**Runtime:** 131ms\n**Memory Usage:** 13.8 MB\n\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **C++ Code** :\n\n```\n\nclass Solution {\npublic:\n Node* connect(Node* root) {\n if(!root) return root;\n Node* current = root;\n while(current) {\n Node* level1stNode = current;\n while(current) \n {\n if(current->left)\n current->left->next = current->right;\n if(current->right && current->next)\n current->right->next = current->next->left;\n\n current = current->next;\n }\n current = level1stNode->left;\n }\n return root;\n }\n};\n```\n**Runtime:** 41ms\n**Memory Usage:** 69.7MB\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\nIf you like the solution, please upvote \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F
11,457
Populating Next Right Pointers in Each Node
populating-next-right-pointers-in-each-node
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
14,099
146
def connect1(self, root):\n if root and root.left and root.right:\n root.left.next = root.right\n if root.next:\n root.right.next = root.next.left\n self.connect(root.left)\n self.connect(root.right)\n \n # BFS \n def connect2(self, root):\n if not root:\n return \n queue = [root]\n while queue:\n curr = queue.pop(0)\n if curr.left and curr.right:\n curr.left.next = curr.right\n if curr.next:\n curr.right.next = curr.next.left\n queue.append(curr.left)\n queue.append(curr.right)\n \n # DFS \n def connect(self, root):\n if not root:\n return \n stack = [root]\n while stack:\n curr = stack.pop()\n if curr.left and curr.right:\n curr.left.next = curr.right\n if curr.next:\n curr.right.next = curr.next.left\n stack.append(curr.right)\n stack.append(curr.left)
11,462
Populating Next Right Pointers in Each Node
populating-next-right-pointers-in-each-node
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
15,101
129
I want to share how I come up with this solution with you:\n\nSince we are manipulating tree nodes on the same level, it's easy to come up with\na very standard BFS solution using queue. But because of next pointer, we actually\ndon't need a queue to store the order of tree nodes at each level, we just use a next\npointer like it's a link list at each level; In addition, we can borrow the idea used in\nthe Binary Tree level order traversal problem, which use cur and next pointer to store \nfirst node at each level; we exchange cur and next every time when cur is the last node\nat each level. \n\n\n class Solution(object):\n def connect(self, root):\n """\n :type root: TreeLinkNode\n :rtype: nothing\n """\n \n if not root:\n return None\n cur = root\n next = root.left\n \n while cur.left :\n cur.left.next = cur.right\n if cur.next:\n cur.right.next = cur.next.left\n cur = cur.next\n else:\n cur = next\n next = cur.left
11,463
Populating Next Right Pointers in Each Node
populating-next-right-pointers-in-each-node
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
681
12
I thought that this solution was a little different to the others posted, most of them doing a level order search using the next pointer. However here, I have recursively split the tree into \'pincer\' segments (this is what I call them because I don\'t know the name), at each level the pair is made up of 1. the right most node of that level in the left node\'s subtree & 2. the left most node of that level in the right node\'s subtree - and then connected node 1 to node 2 at each level.\n\n```\nclass Solution:\n def connect(self, root: \'Optional[Node]\') -> \'Optional[Node]\':\n if not root:\n return\n \n c1, c2 = root.left, root.right\n \n while c1 and c2:\n c1.next = c2\n c1, c2 = c1.right, c2.left\n \n self.connect(root.left)\n self.connect(root.right)\n \n return root\n```\n\t\nThe idea being, that I could simply connect a node\'s left child to it\'s right child, with the only difficulty being to find the \'next\' node of a right child. The \'pincer\' segments help resolve this issue, as the \'next\' node of a right child is simply the other node in that level of the \'pincer\'\n\nI\'m not quite sure the if there is a specific name for this general idea, and would be very appreciative if anyone knows what it is Hope this helps!\n\nEDIT: A diagram illustrating the \'pincer segments\' of each of the first three nodes, and the pointers created by each - in red, blue and green respectively. Note that each node not on the left or right \'boundary\' is visited by two other \'pincer segments\', as is necessary since each node should have a pointer coming in and one coming out.\n\n![image]()
11,467
Populating Next Right Pointers in Each Node II
populating-next-right-pointers-in-each-node-ii
Given a binary tree Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
5,950
57
1. ##### **Level Order Traversal Approach**\nAs the problem states that the output should return a tree with all the nodes in the same level connected, the problem can be solved using **Level Order Traversal**.\nEach iteration of Queue traversal, the code would:\n1. Find the length of the current level of the tree. \n2. Iterate through all the nodes in the same level using the level length. \n3. Find the siblings in the next level and connect them using next pointers. Enqueue all the nodes in the next level.\n\n\n```\nclass Solution:\n def connect(self, root: \'Node\') -> \'Node\':\n if not root:\n return None\n q = deque()\n q.append(root)\n dummy=Node(-999) # to initialize with a not null prev\n while q:\n length=len(q) # find level length\n \n prev=dummy\n for _ in range(length): # iterate through all nodes in the same level\n popped=q.popleft()\n if popped.left:\n q.append(popped.left)\n prev.next=popped.left\n prev=prev.next\n if popped.right:\n q.append(popped.right)\n prev.next=popped.right\n prev=prev.next \n \n return root\n```\n\n\n\n**Time = O(N)** - iterate through all the nodes\n**Space=O(L)** - As the code is using level order traversal, the maximum size of Queue is maximum number of nodes at any level.\n\n\n\n---\n2. ##### **O(1) Space Approach**\n\nIn addition to this, there is a **follow-up question** asking to solve this problem using constant extra space. There is an additional hint to maybe use recursion for this and the extra call stack is assumed to be `O(1)` space\n\nThe code will track the `head` at each level and use that not null `head` to define the next iteration. Following is my take on `O(1)` space solution:\n\n\n```\nclass Solution:\n def connect(self, root: \'Node\') -> \'Node\':\n if not root:\n return None\n \n curr=root\n dummy=Node(-999) \n head=root \n\n\t\twhile head:\n curr=head # initialize current level\'s head\n prev=dummy # init prev for next level linked list traversal\n\t\t\t# iterate through the linked-list of the current level and connect all the siblings in the next level\n while curr: \n if curr.left:\n prev.next=curr.left\n prev=prev.next\n if curr.right:\n prev.next=curr.right\n prev=prev.next \n curr=curr.next\n head=dummy.next # update head to the linked list of next level\n dummy.next=None # reset dummy node\n return root\n \n```\n\n**Time = O(N)** - iterate through all the nodes\n**Space = O(1)** - No additional space\n\n---\n\n***Please upvote if you find it useful***
11,520
Populating Next Right Pointers in Each Node II
populating-next-right-pointers-in-each-node-ii
Given a binary tree Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
25,540
201
The algorithm is a BFS or level order traversal. We go through the tree level by level. node is the pointer in the parent level, tail is the tail pointer in the child level.\nThe parent level can be view as a singly linked list or queue, which we can traversal easily with a pointer.\nConnect the tail with every one of the possible nodes in child level, update it only if the connected node is not nil.\nDo this one level by one level. The whole thing is quite straightforward.\n\n**Python**\n\n def connect(self, node):\n tail = dummy = TreeLinkNode(0)\n while node:\n tail.next = node.left\n if tail.next:\n tail = tail.next\n tail.next = node.right\n if tail.next:\n tail = tail.next\n node = node.next\n if not node:\n tail = dummy\n node = dummy.next\n\n\n # 61 / 61 test cases passed.\n # Status: Accepted\n # Runtime: 100 ms\n # 95.26%
11,527
Populating Next Right Pointers in Each Node II
populating-next-right-pointers-in-each-node-ii
Given a binary tree Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
690
6
As soon as we see this problem, we think of a **level order traversal**, that traverses through the tree level by level. This level order traversal can be achieved using **Breadth First Search** that uses queue data structure to store and retrieve data.\n\nFirstly, queue in python can be easily implemented using deque (it has a few advantages over lists).\n\nNow coming to the BFS algo:\n1. **If no root**, then no next pointer population so **simply return**.\n2. **Create a queue**, that stores the tree Node element along with its level. The **level** simply **means depth**, where *depth of root = 0*.\n3. Deque the first element from the Queue and Enqueue its immediate successors/children, and *keep this deque and enqueue opeations on, till no more successors are found*. Just like Normal **BFS**.\n4. Now, During this BFS, we want that the current element should point to the next element in the same level.\n\nThere is no way to know the next element ahead of time always, but we always know what we have encountered earlier (the previous node). \n\nSo, what we did here was, **update the previous node\'s next pointer value to current node pointer**, *if both the current and previous node are at the same level*.\n\n```\nclass Solution:\n from collections import deque\n def connect(self, root: \'Node\') -> \'Node\':\n if not root:\n return \n queue = deque()\n queue.append([root, 0])\n prev, lvl = None, -1\n while queue:\n current, level = queue.popleft()\n if current.left:\n queue.append([current.left, level + 1])\n if current.right:\n queue.append([current.right, level + 1])\n if prev and level == lvl:\n prev.next = current\n prev, lvl = current, level\n return root \n```\n**Time Complexity analysis:**\nWe are traversing through each element exactly once.\nHence, **time complexity = O(n)**.\n\n**Space Complexity Analysis:**\nThere are 2^h number of nodes in the last level of a full Binary Tree (worst case) with height h. \nAlso, for a full Binary Tree, height of the tree = (log2n) nearly.\nAt max we will be storing one complete level at a time in our queue, and max number of elements (in the worst case) are present in the last level.\nSo, max size of queue = 2 ^ (log2n) = **O(n) = Space Complexity**.\n\nUpvote, if helpful.
11,540
Populating Next Right Pointers in Each Node II
populating-next-right-pointers-in-each-node-ii
Given a binary tree Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
2,648
34
Python O(1) aux space DFS sol.\n\n---\n\n**Hint**:\n\nThink of DFS traversal.\n\n---\n\n**Algorithm**:\n\nFor each current node,\n\nStep_#1:\nUse **scanner** to **locate the left-most neighbor, on same level**, in right hand side.\n\nStep_#2-1:\nWhen right child exists, update right child\'next as scanner\n\nStep_#2-2:\nWhen left child exists, update left child\'next as either right child (if right child exists ),or scanner.\n\n---\n\n**Abstract Model**:\n\n**Before** connection of next pointer:\n![image]()\n\n\n---\n\n**After** connection of next pointer:\nBoth left child and right child exist\n![image]()\n\n---\n\nOnly right child exists\n![image]()\n\n\n---\n\nOnly left child exists\n![image]()\n\n\n---\n\n**Implementation**:\n```\nclass Solution:\n def connect(self, root: \'Node\') -> \'Node\':\n \n def helper( node: \'Node\'):\n \n if not node:\n return None\n \n scanner = node.next\n\n # Scanner finds left-most neighbor, on same level, in right hand side\n while scanner:\n\n if scanner.left:\n scanner = scanner.left\n break\n\n if scanner.right:\n scanner = scanner.right\n break\n\n scanner = scanner.next\n\n\n # connect right child if right child exists\n if node.right:\n node.right.next = scanner \n\n # connect left child if left child exists\n if node.left:\n node.left.next = node.right if node.right else scanner\n\n\n # DFS down to next level\n helper( node.right ) \n helper( node.left ) \n \n return node\n # -------------------------------\n \n return helper( root ) \n```\n\n---\n\nRelated leetcode challenge:\n\n( a special case of current challenge )\n[Leetcode #116 Populating Next Right Pointers in Each Node]()
11,553
Populating Next Right Pointers in Each Node II
populating-next-right-pointers-in-each-node-ii
Given a binary tree Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
8,492
58
level by level traversal with a dummy head `prekid`. <br>\nroot is in the current level, and kid is in the next level. `prekid.next` is the head in the kid level<br>\n`kid = kid.next or kid` : Update kid ONLY when we actually find its next node\n<br><br>\nruntime is around 96ms with a best runtime 88ms.\n\n\n def connect(self, root):\n prekid = kid = TreeLinkNode(0)\n while root:\n while root:\n kid.next = root.left\n kid = kid.next or kid\n kid.next = root.right\n kid = kid.next or kid\n root = root.next\n root, kid = prekid.next, prekid
11,557
Populating Next Right Pointers in Each Node II
populating-next-right-pointers-in-each-node-ii
Given a binary tree Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
3,792
31
### BFS: Level Order Traversal - simple approach:\n```\ndef connect(self, root: \'Node\') -> \'Node\':\n\tif not root:\n return root\n q = []\n \n q.append(root)\n \n tail = root\n while len(q) > 0:\n node = q.pop(0)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n \n if node == tail:\n node.next = None\n tail = q[-1] if len(q) > 0 else None\n else:\n node.next = q[0]\n \n return root\n```\n### O(1) Space approach:\n```\ndef connect(self, root: \'Node\') -> \'Node\':\n dummy = Node(-1, None, None, None)\n tmp = dummy\n res = root\n while root:\n while root:\n if root.left:\n tmp.next = root.left\n tmp = tmp.next\n if root.right:\n tmp.next = root.right\n tmp = tmp.next\n root = root.next\n root = dummy.next\n tmp = dummy\n dummy.next = None\n \n return res\n```
11,561
Populating Next Right Pointers in Each Node II
populating-next-right-pointers-in-each-node-ii
Given a binary tree Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
343
11
```python\nclass Solution:\n def connect(self, root: \'Node\') -> \'Node\':\n if not root: return\n queue = [root]\n \n while queue:\n newQueue = []\n while queue:\n node = queue.pop(0)\n if queue: node.next = queue[0]\n if node.left: newQueue.append(node.left)\n if node.right: newQueue.append(node.right)\n queue = newQueue\n \n return root\n```
11,592
Pascal's Triangle
pascals-triangle
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
20,536
472
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**The problem** of generating Pascal\'s triangle can be approached in **various ways.**\n**Here are some approaches and their intuition to solve the problem:**\n\n# Approach 1: Using Recursion\n<!-- Describe your approach to solving the problem. -->\n**Intuition:** In Pascal\'s triangle, **each element is the sum of the two elements directly above it**. We can use a **recursive approach** to generate the triangle. **The base case is when numRows is 1**, in which case we return [[1]]. **Otherwise, we recursively generate the triangle for numRows - 1** and then calculate the current row by summing the adjacent elements from the previous row.\n\n# Approach 2: Using Combinatorial Formula\n\n**Intuition:** Pascal\'s triangle **can also be generated using combinatorial formula C(n, k) = C(n-1, k-1) + C(n-1, k)**, where C(n, k) **represents the binomial coefficient**. **We can calculate each element of the triangle using this formula.** This approach avoids the need for storing the entire triangle in memory, **making it memory-efficient.**\n\n# Approach 3: Using Dynamic Programming with 1D Array\n\n**Intuition:** **We can use a dynamic programming approach with a 1D array to generate Pascal\'s triangle row by row**. Instead of maintaining a 2D array, we can use a single array to store the current row and update it as we iterate through the rows. This approach reduces space complexity.\n\n# Here\'s a brief outline of each approach:\n1. **Recursion Approach:**\n\n - Base case: If numRows is 1, return [[1]].\n - Recursively generate the triangle for numRows - 1.\n - Calculate the current row by summing adjacent elements from the previous row.\n\n2. **Combinatorial Formula Approach:**\n\n - Use the binomial coefficient formula C(n, k) to calculate each element.\n - Build the triangle row by row using the formula.\n\n3. **Dynamic Programming with 1D Array:**\n - Initialize a 1D array to store the current row.\n - Iterate through numRows and update the array for each row.\n\n\n# Complexity\n**In terms of time complexity**, all three methods have the same overall time complexity of **O(numRows^2)** because we need to generate all the elements of Pascal\'s triangle. **However, in terms of space complexity,** Method 3 is the most efficient as it uses only O(numRows) space, while the other two methods use O(numRows^2) space due to storing the entire triangle or previous rows in recursion.\n\n---\n\n# SMALL REQUEST : If you found this post even remotely helpful, be kind enough to smash a upvote. I will be grateful.I will be motivated\uD83D\uDE0A\uD83D\uDE0A\n\n---\n\n\n\n# Method 1: Using Recursion\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> generate(int numRows) {\n if (numRows == 0) return {};\n if (numRows == 1) return {{1}};\n \n vector<vector<int>> prevRows = generate(numRows - 1);\n vector<int> newRow(numRows, 1);\n \n for (int i = 1; i < numRows - 1; i++) {\n newRow[i] = prevRows.back()[i - 1] + prevRows.back()[i];\n }\n \n prevRows.push_back(newRow);\n return prevRows;\n }\n};\n\n```\n```Java []\nclass Solution {\n public List<List<Integer>> generate(int numRows) {\n if (numRows == 0) return new ArrayList<>();\n if (numRows == 1) {\n List<List<Integer>> result = new ArrayList<>();\n result.add(Arrays.asList(1));\n return result;\n }\n \n List<List<Integer>> prevRows = generate(numRows - 1);\n List<Integer> newRow = new ArrayList<>();\n \n for (int i = 0; i < numRows; i++) {\n newRow.add(1);\n }\n \n for (int i = 1; i < numRows - 1; i++) {\n newRow.set(i, prevRows.get(numRows - 2).get(i - 1) + prevRows.get(numRows - 2).get(i));\n }\n \n prevRows.add(newRow);\n return prevRows;\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n if numRows == 0:\n return []\n if numRows == 1:\n return [[1]]\n \n prevRows = self.generate(numRows - 1)\n newRow = [1] * numRows\n \n for i in range(1, numRows - 1):\n newRow[i] = prevRows[-1][i - 1] + prevRows[-1][i]\n \n prevRows.append(newRow)\n return prevRows\n\n```\n```JavaScript []\nvar generate = function(numRows) {\n if (numRows === 0) {\n return [];\n }\n if (numRows === 1) {\n return [[1]];\n }\n \n let prevRows = generate(numRows - 1);\n let newRow = new Array(numRows).fill(1);\n \n for (let i = 1; i < numRows - 1; i++) {\n newRow[i] = prevRows[numRows - 2][i - 1] + prevRows[numRows - 2][i];\n }\n \n prevRows.push(newRow);\n return prevRows;\n};\n\n```\n\n# Method 2: Using Combinatorial Formula\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> generate(int numRows) {\n vector<vector<int>> result;\n for (int i = 0; i < numRows; i++) {\n vector<int> row(i + 1, 1);\n for (int j = 1; j < i; j++) {\n row[j] = result[i - 1][j - 1] + result[i - 1][j];\n }\n result.push_back(row);\n }\n return result;\n }\n};\n\n```\n```java []\nimport java.util.ArrayList;\nimport java.util.List;\n\nclass Solution {\n public List<List<Integer>> generate(int numRows) {\n List<List<Integer>> result = new ArrayList<>();\n if (numRows == 0) {\n return result;\n }\n\n List<Integer> firstRow = new ArrayList<>();\n firstRow.add(1);\n result.add(firstRow);\n\n for (int i = 1; i < numRows; i++) {\n List<Integer> prevRow = result.get(i - 1);\n List<Integer> currentRow = new ArrayList<>();\n currentRow.add(1);\n\n for (int j = 1; j < i; j++) {\n currentRow.add(prevRow.get(j - 1) + prevRow.get(j));\n }\n\n currentRow.add(1);\n result.add(currentRow);\n }\n\n return result;\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n result = []\n if numRows == 0:\n return result\n\n first_row = [1]\n result.append(first_row)\n\n for i in range(1, numRows):\n prev_row = result[i - 1]\n current_row = [1]\n\n for j in range(1, i):\n current_row.append(prev_row[j - 1] + prev_row[j])\n\n current_row.append(1)\n result.append(current_row)\n\n return result\n\n```\n```Javascript []\nvar generate = function(numRows) {\n let result = [];\n if (numRows === 0) {\n return result;\n }\n\n let firstRow = [1];\n result.push(firstRow);\n\n for (let i = 1; i < numRows; i++) {\n let prevRow = result[i - 1];\n let currentRow = [1];\n\n for (let j = 1; j < i; j++) {\n currentRow.push(prevRow[j - 1] + prevRow[j]);\n }\n\n currentRow.push(1);\n result.push(currentRow);\n }\n\n return result;\n};\n\n```\n\n---\n\n# SMALL REQUEST : If you found this post even remotely helpful, be kind enough to smash a upvote. I will be grateful.I will be motivated\uD83D\uDE0A\uD83D\uDE0A\n\n---\n\n\n# Method 3: Using Dynamic Programming with 1D Array\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> generate(int numRows) {\n vector<vector<int>> result;\n vector<int> prevRow;\n \n for (int i = 0; i < numRows; i++) {\n vector<int> currentRow(i + 1, 1);\n \n for (int j = 1; j < i; j++) {\n currentRow[j] = prevRow[j - 1] + prevRow[j];\n }\n \n result.push_back(currentRow);\n prevRow = currentRow;\n }\n \n return result;\n }\n};\n\n```\n```Java []\nimport java.util.ArrayList;\nimport java.util.List;\n\nclass Solution {\n public List<List<Integer>> generate(int numRows) {\n List<List<Integer>> result = new ArrayList<>();\n if (numRows == 0) {\n return result;\n }\n\n if (numRows == 1) {\n List<Integer> firstRow = new ArrayList<>();\n firstRow.add(1);\n result.add(firstRow);\n return result;\n }\n\n result = generate(numRows - 1);\n List<Integer> prevRow = result.get(numRows - 2);\n List<Integer> currentRow = new ArrayList<>();\n currentRow.add(1);\n\n for (int i = 1; i < numRows - 1; i++) {\n currentRow.add(prevRow.get(i - 1) + prevRow.get(i));\n }\n\n currentRow.add(1);\n result.add(currentRow);\n\n return result;\n }\n}\n\n```\n```Python []\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n if numRows == 0:\n return []\n if numRows == 1:\n return [[1]]\n\n prev_rows = self.generate(numRows - 1)\n prev_row = prev_rows[-1]\n current_row = [1]\n\n for i in range(1, numRows - 1):\n current_row.append(prev_row[i - 1] + prev_row[i])\n\n current_row.append(1)\n prev_rows.append(current_row)\n\n return prev_rows\n\n```\n```Javascript []\nvar generate = function(numRows) {\n if (numRows === 0) {\n return [];\n }\n if (numRows === 1) {\n return [[1]];\n }\n\n let prevRows = generate(numRows - 1);\n let prevRow = prevRows[prevRows.length - 1];\n let currentRow = [1];\n\n for (let i = 1; i < numRows - 1; i++) {\n currentRow.push(prevRow[i - 1] + prevRow[i]);\n }\n\n currentRow.push(1);\n prevRows.push(currentRow);\n\n return prevRows;\n};\n\n```\n\n\n---\n\n#SMALL REQUEST : If you found this post even remotely helpful, be kind enough to smash a upvote. I will be grateful.I will be motivated\uD83D\uDE0A\uD83D\uDE0A\n\n---\n\n![UPVOTE.png]()\n\n
11,600
Pascal's Triangle
pascals-triangle
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
26,543
468
```C++ []\nclass Solution {\n public:\n vector<vector<int>> generate(int numRows) {\n vector<vector<int>> ans;\n\n for (int i = 0; i < numRows; ++i)\n ans.push_back(vector<int>(i + 1, 1));\n\n for (int i = 2; i < numRows; ++i)\n for (int j = 1; j < ans[i].size() - 1; ++j)\n ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j];\n\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n finalNums=[]\n finalNums.append([1])\n for i in range(numRows-1):\n newRow=[1]\n for j in range(i):\n newRow.append(finalNums[i][j]+finalNums[i][j+1])\n newRow.append(1)\n finalNums.append(newRow)\n return finalNums\n```\n\n```Java []\nclass Solution {\n public List<List<Integer>> generate(int numRows) {\n List<List<Integer>> ans = new ArrayList<>();\n\n for (int i = 0; i < numRows; ++i) {\n Integer[] temp = new Integer[i + 1];\n Arrays.fill(temp, 1);\n ans.add(Arrays.asList(temp));\n }\n\n for (int i = 2; i < numRows; ++i)\n for (int j = 1; j < ans.get(i).size() - 1; ++j)\n ans.get(i).set(j, ans.get(i - 1).get(j - 1) + ans.get(i - 1).get(j));\n\n return ans;\n }\n}\n```\n
11,604
Pascal's Triangle
pascals-triangle
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
14,237
74
# Comprehensive Guide to Generating Pascal\'s Triangle: A Three-Pronged Approach for Programmers\n\n## Introduction & Problem Statement\n\nWelcome to this in-depth guide on generating Pascal\'s Triangle up to a given number of rows. Pascal\'s Triangle is a mathematical concept that finds applications in various domains, including combinatorics, probability theory, and computer science. In this guide, we will explore three distinct methods to solve this problem: Dynamic Programming, Recursion, and Math (Combinatorics).\n\n## Key Concepts and Constraints\n\n1. **Row Anatomy**: \n In Pascal\'s Triangle, each row starts and ends with 1. Each inner element is the sum of the two elements directly above it in the previous row.\n\n2. **Row Generation**: \n Our primary task is to generate the first `numRows` of Pascal\'s Triangle.\n\n3. **Constraints**: \n 1 <= `numRows` <= 30. The constraint allows us to generate up to 30 rows of Pascal\'s Triangle.\n\n---\n\n# Strategies to Tackle the Problem: A Three-Pronged Approach\n\n### Live Coding Dynamic Programming\n\n\n## Method 1. Dynamic Programming\n\n### Intuition and Logic Behind the Solution\n\nIn Dynamic Programming, we use the concept of "building upon previous solutions" to solve the problem. We start with the first row and iteratively generate each subsequent row based on the row above it.\n\n### Step-by-step Explanation\n\n1. **Initialization**: \n - Start with a list containing the first row `[1]`.\n\n2. **Iterative Row Generation**: \n - For each subsequent row, generate it based on the last row in the list. Start and end each row with 1 and fill the middle elements according to Pascal\'s rule.\n\n3. **Return the Triangle**: \n - After generating the required number of rows, return the triangle.\n\n### Complexity Analysis\n\n- **Time Complexity**: $$O(n^2)$$ \u2014 Each row takes $$O(n)$$ time to generate.\n- **Space Complexity**: $$O(n^2)$$ \u2014 Storing the triangle takes $$O(n^2)$$ space.\n\n## Code Dynamic Programming \n``` Python []\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n if numRows == 0:\n return []\n \n triangle = [[1]]\n \n for i in range(1, numRows):\n prev_row = triangle[-1]\n new_row = [1]\n \n for j in range(1, len(prev_row)):\n new_row.append(prev_row[j-1] + prev_row[j])\n \n new_row.append(1)\n triangle.append(new_row)\n \n return triangle\n```\n``` Go []\nfunc generate(numRows int) [][]int {\n\tvar triangle [][]int\n\tif numRows == 0 {\n\t\treturn triangle\n\t}\n\n\ttriangle = append(triangle, []int{1})\n\n\tfor i := 1; i < numRows; i++ {\n\t\tprevRow := triangle[i-1]\n\t\tvar newRow []int\n\t\tnewRow = append(newRow, 1)\n\n\t\tfor j := 1; j < len(prevRow); j++ {\n\t\t\tnewRow = append(newRow, prevRow[j-1]+prevRow[j])\n\t\t}\n\n\t\tnewRow = append(newRow, 1)\n\t\ttriangle = append(triangle, newRow)\n\t}\n\n\treturn triangle\n}\n```\n``` Rust []\nimpl Solution {\n pub fn generate(num_rows: i32) -> Vec<Vec<i32>> {\n let mut triangle = Vec::new();\n if num_rows == 0 {\n return triangle;\n }\n\n triangle.push(vec![1]);\n\n for _ in 1..num_rows {\n let prev_row = triangle.last().unwrap();\n let mut new_row = vec![1];\n\n for j in 1..prev_row.len() {\n new_row.push(prev_row[j-1] + prev_row[j]);\n }\n\n new_row.push(1);\n triangle.push(new_row);\n }\n\n triangle\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n vector<vector<int>> generate(int numRows) {\n vector<vector<int>> triangle;\n if (numRows == 0) return triangle;\n\n triangle.push_back({1});\n\n for (int i = 1; i < numRows; ++i) {\n vector<int> prev_row = triangle.back();\n vector<int> new_row = {1};\n\n for (int j = 1; j < prev_row.size(); ++j) {\n new_row.push_back(prev_row[j-1] + prev_row[j]);\n }\n\n new_row.push_back(1);\n triangle.push_back(new_row);\n }\n\n return triangle;\n }\n};\n```\n``` Java []\npublic class Solution {\n public List<List<Integer>> generate(int numRows) {\n List<List<Integer>> triangle = new ArrayList<>();\n if (numRows == 0) return triangle;\n\n triangle.add(new ArrayList<>());\n triangle.get(0).add(1);\n\n for (int i = 1; i < numRows; i++) {\n List<Integer> prev_row = triangle.get(i - 1);\n List<Integer> new_row = new ArrayList<>();\n new_row.add(1);\n\n for (int j = 1; j < prev_row.size(); j++) {\n new_row.add(prev_row.get(j - 1) + prev_row.get(j));\n }\n\n new_row.add(1);\n triangle.add(new_row);\n }\n\n return triangle;\n }\n}\n```\n``` C# []\nclass Solution {\n public IList<IList<int>> Generate(int numRows) {\n List<IList<int>> triangle = new List<IList<int>>();\n if (numRows == 0) return triangle;\n\n triangle.Add(new List<int>() { 1 });\n\n for (int i = 1; i < numRows; i++) {\n List<int> prevRow = (List<int>)triangle[i - 1];\n List<int> newRow = new List<int> { 1 };\n\n for (int j = 1; j < prevRow.Count; j++) {\n newRow.Add(prevRow[j - 1] + prevRow[j]);\n }\n\n newRow.Add(1);\n triangle.Add(newRow);\n }\n\n return triangle;\n }\n}\n```\n``` JavaScript []\n/**\n * @param {number} numRows\n * @return {number[][]}\n */\nvar generate = function(numRows) {\n let triangle = [];\n if (numRows === 0) return triangle;\n\n triangle.push([1]);\n\n for (let i = 1; i < numRows; i++) {\n let prevRow = triangle[i - 1];\n let newRow = [1];\n\n for (let j = 1; j < prevRow.length; j++) {\n newRow.push(prevRow[j - 1] + prevRow[j]);\n }\n\n newRow.push(1);\n triangle.push(newRow);\n }\n\n return triangle;\n};\n```\n``` PHP []\nclass Solution {\n function generate($numRows) {\n $triangle = [];\n if ($numRows == 0) return $triangle;\n\n $triangle[] = [1];\n\n for ($i = 1; $i < $numRows; $i++) {\n $prevRow = end($triangle);\n $newRow = [1];\n\n for ($j = 1; $j < count($prevRow); $j++) {\n $newRow[] = $prevRow[$j - 1] + $prevRow[$j];\n }\n\n $newRow[] = 1;\n $triangle[] = $newRow;\n }\n\n return $triangle;\n}\n}\n```\n\n---\n\n## Method 2. Recursion\n\n### Intuition and Logic Behind the Solution\n\nThe Recursive approach generates Pascal\'s Triangle by making recursive calls to generate the previous rows and then building upon that to generate the current row.\n\n### Step-by-step Explanation\n\n1. **Base Case**: \n - If `numRows` is 1, return `[[1]]`.\n\n2. **Recursive Row Generation**: \n - Make a recursive call to generate the first `numRows - 1` rows.\n - Generate the `numRows`-th row based on the last row in the list.\n\n3. **Return the Triangle**: \n - Return the triangle after adding the new row.\n\n### Complexity Analysis\n\n- **Time Complexity**: $$O(n^2)$$\n- **Space Complexity**: $$O(n^2)$$\n\n## Code Recursion\n``` Python []\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n if numRows == 1:\n return [[1]]\n \n triangle = self.generate(numRows - 1)\n \n prev_row = triangle[-1]\n new_row = [1]\n \n for i in range(1, len(prev_row)):\n new_row.append(prev_row[i-1] + prev_row[i])\n \n new_row.append(1)\n triangle.append(new_row)\n \n return triangle\n```\n``` Go []\nfunc generate(numRows int) [][]int {\n if numRows == 1 {\n return [][]int{{1}}\n }\n\n triangle := generate(numRows - 1)\n prevRow := triangle[len(triangle) - 1]\n var newRow []int\n newRow = append(newRow, 1)\n\n for i := 1; i < len(prevRow); i++ {\n newRow = append(newRow, prevRow[i-1] + prevRow[i])\n }\n\n newRow = append(newRow, 1)\n triangle = append(triangle, newRow)\n\n return triangle\n}\n\n```\n\n---\n\n## Method 3. Math (Combinatorics)\n\n### Intuition and Logic Behind the Solution\n\nThis method uses the mathematical formula for combinations to directly compute the elements of Pascal\'s Triangle without relying on previous rows. This formula is $$ \\binom{n}{k} $$.\n\n### Step-by-step Explanation\n\n1. **Define the Combination Function**: \n - Use `math.comb()` or a custom function to calculate $$ \\binom{n}{k} $$.\n\n2. **Direct Row Generation**: \n - For each row $$ n $$ and each index $$ k $$ in that row, directly compute the element using $$ \\binom{n}{k} $$.\n\n3. **Return the Triangle**: \n - Return the generated triangle.\n\n### Complexity Analysis\n\n- **Time Complexity**: $$O(n^2)$$\n- **Space Complexity**: $$O(n^2)$$\n\n## Code Math\n``` Python []\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n import math\n\n triangle = []\n \n for n in range(numRows):\n row = []\n for k in range(n+1):\n row.append(math.comb(n, k))\n triangle.append(row)\n \n return triangle\n```\n\n## Performance\n\n| Language | Method | Execution Time (ms) | Memory (MB) |\n|--------------|-------------|---------------------|-------------|\n| Go | Recursion | 0 | 2.5 |\n| Rust | DP | 1 | 2.0 |\n| Java | DP | 1 | 41.2 |\n| Go | DP | 2 | 2.4 |\n| PHP | DP | 3 | 19 |\n| C++ | DP | 4 | 6.8 |\n| Python3 | Recursion | 27 | 16.3 |\n| Python3 | Math | 35 | 16.2 |\n| Python3 | DP | 40 | 16.3 |\n| JavaScript | DP | 48 | 42.1 |\n| C# | DP | 76 | 36.9 |\n\n![p118a.png]()\n\n\n## Live Coding Recursion\n\n\n\n## Code Highlights and Best Practices\n\n- In the Dynamic Programming and Recursion approaches, we build upon previous solutions, making them more intuitive but dependent on previous rows.\n- The Math approach directly computes each element, making it independent of previous rows but less intuitive.\n- The Dynamic Programming approach is often the most straightforward and easy to implement.\n\nBy understanding these three approaches, you\'ll be well-equipped to tackle problems that involve generating Pascal\'s Triangle or similar combinatorial constructs.
11,608
Pascal's Triangle
pascals-triangle
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
137
6
# Intuition\nMy initial thoughts on solving this problem revolve around traversing through the array and keeping track of the maximum sum obtained so far. I might consider using Kadane\'s algorithm, which efficiently finds the maximum subarray sum in a single traversal.\n\n# Approach\n1. Initialize variables: max_sum to store the maximum sum found so far, and current_sum to keep track of the current sum.\n2. Start iterating through the array from the first element.\n3. At each iteration, update current_sum by adding the current element or starting a new subarray if the current element itself is larger than the sum of the previous subarray.\n4. Update max_sum if current_sum exceeds it.\n5. Continue iterating through the array and repeat steps 3-4.\n6. Finally, return the max_sum obtained, which represents the maximum sum of a subarray.\n\n# Complexity\n- Time complexity:\n O(n) - We traverse the array only once.\n\n- Space complexity:\nO(1) - We use a constant amount of extra space for variables max_sum and current_sum regardless of the input size.\n\n# Code\n``` C++ []\nclass Solution {\n List<List<int>> generate(int numRows) {\n List<List<int>> triangle = [];\n\n if (numRows <= 0) {\n return triangle;\n }\n\n for (int i = 0; i < numRows; i++) {\n List<int> row = List.filled(i + 1, 1);\n\n if (i >= 2) {\n for (int j = 1; j < i; j++) {\n row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j];\n }\n }\n\n triangle.add(row);\n }\n\n return triangle;\n }\n}\n\n```\n``` Python []\nclass Solution(object):\n def generate(self, numRows):\n if numRows <= 0:\n return []\n \n triangle = []\n \n for i in range(numRows):\n row = [1] * (i + 1)\n \n if i >= 2:\n for j in range(1, i):\n row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j]\n \n triangle.append(row)\n \n return triangle\n\n```\n``` Dart []\nclass Solution {\n List<List<int>> generate(int numRows) {\n List<List<int>> triangle = [];\n\n if (numRows <= 0) {\n return triangle;\n }\n\n for (int i = 0; i < numRows; i++) {\n List<int> row = List.filled(i + 1, 1);\n\n if (i >= 2) {\n for (int j = 1; j < i; j++) {\n row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j];\n }\n }\n\n triangle.add(row);\n }\n\n return triangle;\n }\n}\n```\n``` Python3 []\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n if numRows <= 0:\n return []\n \n triangle = []\n \n for i in range(numRows):\n row = [1] * (i + 1)\n \n if i >= 2:\n for j in range(1, i):\n row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j]\n \n triangle.append(row)\n \n return triangle\n```
11,639
Pascal's Triangle
pascals-triangle
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
3,670
24
# Main point of the Solution\n\nThe main point of this solution is to generate Pascal\'s triangle, up to a specified number of rows, by iteratively constructing each row based on the previous one. It initializes with the first row containing a single "1," then iterates through the desired number of rows, creating each row by adding zeros at both ends of the previous row, and calculating the inner values as sums of adjacent elements.\n\nThis Python solution beats 97.61%\n\n![Screen Shot 2023-09-08 at 9.15.28.png]()\n\n\n---\n\n# Solution Video\n\n### Please subscribe to my channel from here. I have 257 videos as of September 8th, 2023.\n\n### In the video, the steps of approach below are visualized using diagrams and drawings. I\'m sure you understand the solution easily!\n\n\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\n\n\nSubscribers: 2253\nThank you for your support!\n\n---\n\n# Approach\nThis is based on Python. Other might be different a bit.\n\n1. Initialize the result list `res` with a single row containing the value 1.\n - Explanation: The `res` list will store the generated Pascal\'s triangle.\n\n2. Use a for loop to iterate `numRows - 1` times.\n - Explanation: We need to generate a total of `numRows` rows in Pascal\'s triangle, so we start with one row already added in `res`.\n\n3. Create a `dummy_row` by adding a 0 at the beginning and end of the last row in `res`.\n - Explanation: In Pascal\'s triangle, each row begins and ends with a 1, so we add a 0 on both sides of the previous row to calculate the values for the current row.\n\n4. Initialize an empty list `row` to store the values of the current row.\n\n5. Use a for loop to iterate over the indices of `dummy_row`.\n - Explanation: We iterate through `dummy_row` to calculate the values of the current row by adding pairs of adjacent values from `dummy_row`.\n\n6. Inside the loop, calculate the sum of `dummy_row[i]` and `dummy_row[i+1]` and append it to the `row` list.\n - Explanation: Each value in the current row is the sum of the two values directly above it in the `dummy_row`.\n\n7. After the loop completes, append the `row` list to the `res` list.\n - Explanation: The calculated values for the current row are added to the `res` list.\n\n8. Repeat steps 3-7 for a total of `numRows - 1` times to generate the required number of rows.\n\n9. Once the loop finishes, return the `res` list containing Pascal\'s triangle.\n\nIn summary, this code generates Pascal\'s triangle up to the specified number of rows by iteratively calculating each row based on the previous row using the principle that each value in a row is the sum of the two values directly above it.\n\n# Complexity\n- **Time complexity: O(n^2)** where n is numRows\n\n - The outer for loop iterates numRows - 1 times.\n - Inside the loop, we perform operations that depend on the length of the current row (which increases with each iteration).\n - The inner loop iterates over the elements of the `dummy_row`, which has a length equal to the length of the last row in `res` plus 2 (due to the added zeros at both ends).\n - In the worst case, the length of the last row in `res` would be numRows - 1 (e.g., for the 5th row, it would be [1, 4, 6, 4, 1]).\n - So, the inner loop runs a number of times proportional to numRows.\n\nConsidering the outer and inner loops, the overall time complexity is O(numRows^2).\n\n- **Space complexity: O(n^2)**, where n is numRows\n\n - The `res` list stores the entire Pascal\'s triangle, which has numRows rows and a total of (numRows^2)/2 elements (since each row has an increasing number of elements).\n - The `dummy_row` list is created in each iteration of the loop and has a length equal to the length of the last row in `res` plus 2.\n - The `row` list is created in each iteration and has a length equal to the length of the current `dummy_row`.\n\n Considering the space used by `res`, `dummy_row`, and `row`, the space complexity is O(numRows^2).\n\n\nIn summary, both the time and space complexity of this code are O(n^2), meaning they grow quadratically with the input parameter `numRows`.\n\n\n```python []\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n res = [[1]]\n\n for _ in range(numRows - 1):\n dummy_row = [0] + res[-1] + [0]\n row = []\n\n for i in range(len(res[-1]) + 1):\n row.append(dummy_row[i] + dummy_row[i+1])\n res.append(row)\n \n return res\n```\n```javascript []\n/**\n * @param {number} numRows\n * @return {number[][]}\n */\nvar generate = function(numRows) {\n const res = [[1]];\n\n for (let i = 0; i < numRows - 1; i++) {\n const dummyRow = [0, ...res[res.length - 1], 0];\n const row = [];\n\n for (let j = 0; j < dummyRow.length - 1; j++) {\n row.push(dummyRow[j] + dummyRow[j + 1]);\n }\n\n res.push(row);\n }\n\n return res; \n};\n```\n```java []\nclass Solution {\n public List<List<Integer>> generate(int numRows) {\n List<List<Integer>> res = new ArrayList<>();\n res.add(List.of(1));\n\n for (int i = 0; i < numRows - 1; i++) {\n List<Integer> dummyRow = new ArrayList<>();\n dummyRow.add(0);\n dummyRow.addAll(res.get(res.size() - 1));\n dummyRow.add(0);\n List<Integer> row = new ArrayList<>();\n\n for (int j = 0; j < dummyRow.size() - 1; j++) {\n row.add(dummyRow.get(j) + dummyRow.get(j + 1));\n }\n\n res.add(row);\n }\n\n return res; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> generate(int numRows) {\n std::vector<std::vector<int>> res;\n res.push_back({1});\n\n for (int i = 0; i < numRows - 1; i++) {\n std::vector<int> dummyRow = {0};\n dummyRow.insert(dummyRow.end(), res.back().begin(), res.back().end());\n dummyRow.push_back(0);\n std::vector<int> row;\n\n for (int j = 0; j < dummyRow.size() - 1; j++) {\n row.push_back(dummyRow[j] + dummyRow[j + 1]);\n }\n\n res.push_back(row);\n }\n\n return res; \n }\n};\n```\n
11,641
Pascal's Triangle
pascals-triangle
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
825
17
# Python | Easy to Understand | Fast\n```\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n finalNums=[]\n finalNums.append([1])\n for i in range(numRows-1):\n newRow=[1]\n for j in range(i):\n newRow.append(finalNums[i][j]+finalNums[i][j+1])\n newRow.append(1)\n finalNums.append(newRow)\n return finalNums\n```
11,642
Pascal's Triangle
pascals-triangle
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
737
11
# Problem Description\nGiven an integer numRows, return the first `numRows` of **Pascal\'s triangle**.\n\nIn **Pascal\'s triangle**, each number is the sum of the two numbers directly above it as shown:\n\n![PascalTriangleAnimated2.gif]()\n\n- **Constraints:**\n - `1 <= numRows <= 30`\n\n---\n\n\n# Proposed Solutions\n## 1. Dynamic Programming\n\n### Approach\n1. **Initialize 2D Vector**: Create a 2D vector pascalTriangle with numRows rows to represent Pascal\'s Triangle.\n2. **Generate Rows**: Generate first row seperately then Loop through each row from 1 to numRows - 1.\n3. **Set First and Last Elements**: Set the first and last elements of each row to 1.\n4. **Calculate Middle Elements**: For each row, calculate and append the middle elements by adding the corresponding elements from the previous row.\n5. **Return** Pascal\'s Triangle.\n\n### Complexity\n- **Time complexity:**\nWe have two for-loops each of max size of `n`, then time complexity is `O(N^2)`.\n- **Space complexity:**\n`O(N^2)`, Since we are storing the triangle.\n\n\n## 2. Combinatorics \n\n### Approach\n1. **Initialize 2D Vector**: Create a 2D vector pascalTriangle with numRows rows to represent Pascal\'s Triangle.\n2. **Generate Rows**: Loop through each row from 0 to numRows-1.\n3. **Calculate Middle Elements**: For each row, calculate and append the row elements by calculating combinatorics like the picture below :\n![leet.PNG]()\n\n\n4. **Return** Pascal\'s Triangle.\n\n\n### Complexity\n- **Time complexity:**\nWe have two for-loops each of max size of `n` and we have the for loop that generates the combinatorics, then time complexity is `O(N^3)`.\nBut it won\'t make any difference since `1 <= N <= 30`.\n- **Space complexity:**\n`O(N^2)`, Since we are storing the triangle.\n\n---\n\n\n# Code\n## 1. Dynamic Programming\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> generate(int numRows) {\n // Initialize a 2D vector to represent Pascal\'s Triangle\n vector<vector<int>> pascalTriangle(numRows);\n\n // Initialize the first row with a single element \'1\'\n pascalTriangle[0].push_back(1);\n\n // Generate the rest of the rows\n for (int currentRow = 1; currentRow < numRows; currentRow++) {\n // The first element of each row is always \'1\'\n pascalTriangle[currentRow].push_back(1);\n\n // Get a reference to the current row and the previous row\n vector<int>& currentRowList = pascalTriangle[currentRow];\n const vector<int>& previousRowList = pascalTriangle[currentRow - 1];\n\n // Calculate and populate the middle elements of the row\n for (int j = 1; j < previousRowList.size(); j++) {\n int sum = previousRowList[j] + previousRowList[j - 1];\n currentRowList.push_back(sum);\n }\n\n // The last element of each row is also \'1\'\n currentRowList.push_back(1);\n }\n\n return pascalTriangle;\n }\n};\n```\n```Java []\nclass Solution {\n public List<List<Integer>> generate(int numRows) {\n // Initialize the result as a list of lists\n List<List<Integer>> pascalTriangle = new ArrayList<>();\n\n // Initialize the first row with a single element \'1\'\n pascalTriangle.add(new ArrayList<>());\n pascalTriangle.get(0).add(1);\n\n // Generate the rest of the rows\n for (int currentRow = 1; currentRow < numRows; currentRow++) {\n // Create a new row for the current level\n pascalTriangle.add(new ArrayList<>());\n\n // Get references to the current and previous rows\n List<Integer> currentRowList = pascalTriangle.get(currentRow);\n List<Integer> previousRowList = pascalTriangle.get(currentRow - 1);\n\n // The first element of each row is always \'1\'\n currentRowList.add(1);\n\n // Calculate and populate the middle elements of the row\n for (int j = 1; j < previousRowList.size(); j++) {\n int sum = previousRowList.get(j) + previousRowList.get(j - 1);\n currentRowList.add(sum);\n }\n\n // The last element of each row is also \'1\'\n currentRowList.add(1);\n }\n\n return pascalTriangle;\n }\n}\n```\n```Python []\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n """\n Generates Pascal\'s Triangle up to the specified number of rows.\n :param numRows: The number of rows to generate in Pascal\'s Triangle.\n :return: A list of lists representing Pascal\'s Triangle.\n """\n # Initialize Pascal\'s Triangle with empty lists\n pascal_triangle = [[] for _ in range(numRows)]\n\n # Set the first element of the first row to 1\n pascal_triangle[0].append(1)\n\n # Generate the rest of the rows\n for i in range(1, numRows):\n current_row = pascal_triangle[i]\n prev_row = pascal_triangle[i - 1]\n\n # The first element of each row is always 1\n current_row.append(1)\n\n # Calculate and populate the middle elements of the row\n for j in range(1, len(prev_row)):\n element_sum = prev_row[j] + prev_row[j - 1]\n current_row.append(element_sum)\n\n # The last element of each row is also 1\n current_row.append(1)\n\n return pascal_triangle\n\n```\n\n## 2. Combinatorics\n```C++ []\nclass Solution {\npublic:\n // Calculate n choose r (nCr) using a loop\n int calculateCombination(int n, int r) {\n int result = 1;\n for (int i = 0; i < r; i++) {\n result = result * (n - i) / (i + 1);\n }\n return result;\n }\n\n // Generate Pascal\'s Triangle with \'numRows\' rows\n vector<vector<int>> generate(int numRows) {\n // Initialize a 2D vector to represent Pascal\'s Triangle\n vector<vector<int>> pascalTriangle(numRows);\n\n for (int i = 0; i < numRows; i++) {\n for (int j = 0; j <= i; j++) {\n // Calculate and insert the binomial coefficient (nCr) into the current row\n pascalTriangle[i].push_back(calculateCombination(i, j));\n }\n }\n return pascalTriangle;\n }\n};\n```\n```Java []\nclass Solution {\n // Calculate n choose r (nCr) using a loop\n public int calculateCombination(int n, int r) {\n int result = 1;\n for (int i = 0; i < r; i++) {\n result = result * (n - i) / (i + 1);\n }\n return result;\n }\n\n // Generate Pascal\'s Triangle with \'numRows\' rows\n public List<List<Integer>> generate(int numRows) {\n // Initialize a list of lists to represent Pascal\'s Triangle\n List<List<Integer>> pascalTriangle = new ArrayList<>();\n\n for (int i = 0; i < numRows; i++) {\n pascalTriangle.add(new ArrayList<>());\n List<Integer> currentRow = pascalTriangle.get(i);\n\n for (int j = 0; j <= i; j++) {\n // Calculate and insert the binomial coefficient (nCr) into the current row\n currentRow.add(calculateCombination(i, j));\n }\n }\n return pascalTriangle;\n }\n}\n```\n```Python []\nclass Solution:\n\n def calculate_combination(self, n: int, r: int) -> int:\n """\n Calculate the combination (n choose r) using the formula C(n, r) = n! / (r! * (n - r)!).\n :param n: Total number of items.\n :param r: Number of items to choose.\n :return: The combination value C(n, r).\n """\n result = 1\n for i in range(r):\n result = result * (n - i) // (i + 1) # Use integer division to ensure an integer result\n return result\n\n def generate(self, numRows: int) -> List[List[int]]:\n """\n Generate Pascal\'s Triangle up to a given number of rows.\n :param numRows: The number of rows in the Pascal\'s Triangle.\n :return: A list of lists representing Pascal\'s Triangle.\n """\n pascal_triangle = [[] for _ in range(numRows)]\n\n for i in range(numRows):\n for j in range(i + 1):\n pascal_triangle[i].append(self.calculate_combination(i, j))\n\n return pascal_triangle\n```\n\n
11,644
Pascal's Triangle
pascals-triangle
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
807
7
# Objective:\n - The code aims to generate a Pascal\'s Triangle up to a specified number of rows (`numRows`).\n\n# Strategies to Tackle the Problem:\n1. **Understand the Goal**: First, understand that the code\'s goal is to generate Pascal\'s Triangle up to a specified number of rows (`numRows`).\n\n1. **Visualize Pascal\'s Triangle:** It\'s helpful to visualize Pascal\'s Triangle to see the pattern of numbers.\n\n1. **Step Through the Code:** Go through the code step by step, keeping track of the ans vector and how each row is generated.\n\n**Use Test Cases:** Try running the code with different values of `numRows` to see the generated Pascal\'s Triangles and observe how they change.\n\n1. **Check the Math:** Understand that each number in a row is the sum of the two numbers directly above it.\n\n1. **Look for Optimization:** Consider how the code could be optimized or improved for efficiency.\n\n# Intuition\n- **The code generates each row of Pascal\'s Triangle** iteratively, starting with the first row (which contains only 1) and using the values from the previous row to **calculate the values of the current row.** \n-** The inner loop calculates the non-edge **values by adding two values from the previous row. \n- **This process continues** until all rows up to `numRows` are generated.\n\n# Approach\n1. Initialize an empty vector `ans` to store the rows of Pascal\'s Triangle.\n\n1. For each row from `i = 0` to `i = numRows - 1`:\na. Initialize a vector `row` with `i + 1` elements, all set to `1`.\nb. For each element in `row` from `j = 1` to `j = i - 1`, calculate its value by adding two values from the previous row (`ans[i - 1][j]` and `ans[i - 1][j - 1`]).\nc. Add the completed `row` to the `ans` vector.\n\n1. Return the ans vector containing the Pascal\'s Triangle up to numRows.\n\nThis approach builds Pascal\'s Triangle row by row, and the final result is a 2D vector representing the complete triangle.\n\n# Code Explanation:\n1. `vector<vector<int>> ans;`: Initialize an empty 2D vector `ans` to store the rows of Pascal\'s Triangle.\n\n1. `for (int i = 0; i < numRows; i++) {`: Start a loop that iterates from `i = 0` to `i = numRows - 1`. This loop will generate each row of Pascal\'s Triangle.\n\n1. `vector<int> row(i + 1, 1);`: Initialize a vector `row` with `i + 1` elements, all initialized to `1`. This represents the current row being generated.\n\n1. `for (int j = 1; j < i; j++) {`: Start a nested loop that iterates from `j = 1` to `j = i - 1`. This loop fills in the values of `row` between the first and last `1` of the row.\n\n1. `row[j] = ans[i - 1][j] + ans[i - 1][j - 1];`: Calculate the value at position `row[j]` by adding the values from the previous row (`ans[i - 1][j]` and `ans[i - 1][j - 1]`) and assign it to `row[j]`.\n\n1. `ans.push_back(row);`: Add the completed row to the ans vector, representing the current row of Pascal\'s Triangle.\n\n1. Repeat steps 3-6 for each row from `i = 0` to `i = numRows - 1`.\n\n1. Finally, return the ans vector containing the complete Pascal\'s Triangle.\n\n# Comlexity\n**Time Complexity:** `O(numRows^2)`\n**Space Complexity:** `O(numRows^2)`\n\n\n\n# Complexity Explanation:\n**- Time complexity:**\nThe time complexity of the code is` O(numRows^2),` where `numRows` is the `input argument` specifying how many rows of Pascal\'s Triangle to generate.\n\n- `**The outer loop runs for numRows iterations**`, and for each iteration, it performs operations proportional to the current row number (i).\n\n- `The inner loop runs for i - 1 iterations` (excluding the first and last elements of each row), and within the inner loop, there are constant time operations (addition and assignment).\n\n**Therefore, the overall time complexity is determined by the sum of operations for each row, which is roughly 1 + 2 + 3 + ... + numRows. This sum is proportional to numRows^2/2**, resulting in a `time complexity of O(numRows^2)`.\n\n**- Space complexity:**\n\n\n- The space complexity of the code is `O(numRows^2) `as well.\n\n- **The main space usage comes from the ans vector,** which stores the entire Pascal\'s Triangle. \n- **The number of rows in the triangle is equal to numRows,** and for each row, there are on average numRows/2 elements (since the number of elements increases linearly with the row number). \n- Therefore, the space complexity is `O(numRows * numRows/2)`, which simplifies to O(numRows^2).\n\n- Additionally, t**here\'s a constant amount of space used for integer variables i, j, and the temporary row vector.**\n\n- In summary,** both the time and space complexity of the code are O(numRows^2) with respect to the input argument numRows.**\n\n# PLEASE UPVOTE\u2763\uD83D\uDE0D\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> generate(int numRows) {\n vector<vector<int>> ans;\n for (int i = 0; i < numRows; i++) {\n vector<int> row(i + 1, 1);\n for (int j = 1; j < i; j++) {\n row[j] = ans[i - 1][j] + ans[i - 1][j - 1];\n }\n ans.push_back(row);\n }\n return ans;\n }\n};\n```\n# JAVA\n```\nimport java.util.ArrayList;\nimport java.util.List;\n\nclass Solution {\n public List<List<Integer>> generate(int numRows) {\n List<List<Integer>> ans = new ArrayList<>();\n for (int i = 0; i < numRows; i++) {\n List<Integer> row = new ArrayList<>();\n for (int j = 0; j <= i; j++) {\n if (j == 0 || j == i) {\n row.add(1);\n } else {\n int val = ans.get(i - 1).get(j - 1) + ans.get(i - 1).get(j);\n row.add(val);\n }\n }\n ans.add(row);\n }\n return ans;\n }\n}\n\n```\n# PYTHON3\n```\nclass Solution:\n def generate(self, numRows):\n ans = []\n for i in range(numRows):\n row = [1] * (i + 1)\n for j in range(1, i):\n row[j] = ans[i - 1][j] + ans[i - 1][j - 1]\n ans.append(row)\n return ans\n\n```\n# JAVASCRIPT\n```\nvar generate = function(numRows) {\n let ans = [];\n for (let i = 0; i < numRows; i++) {\n let row = new Array(i + 1).fill(1);\n for (let j = 1; j < i; j++) {\n row[j] = ans[i - 1][j] + ans[i - 1][j - 1];\n }\n ans.push(row);\n }\n return ans;\n};\n\n```\n# GO\n```\npackage main\n\nimport "fmt"\n\nfunc generate(numRows int) [][]int {\n ans := make([][]int, numRows)\n for i := 0; i < numRows; i++ {\n row := make([]int, i+1)\n for j := 1; j < i; j++ {\n row[j] = ans[i-1][j] + ans[i-1][j-1]\n }\n row[0], row[i] = 1, 1\n ans[i] = row\n }\n return ans\n}\n\nfunc main() {\n numRows := 5 // You can change this value as needed\n result := generate(numRows)\n \n for _, row := range result {\n fmt.Println(row)\n }\n}\n\n```\n# PLEASE UPVOTE\u2763\uD83D\uDE0D
11,645
Pascal's Triangle
pascals-triangle
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
42,672
217
# **Java Solution:**\nRuntime: 0 ms, faster than 100.00% of Java online submissions for Pascal\'s Triangle.\n```\nclass Solution {\n public List<List<Integer>> generate(int numRows) {\n // Create an array list to store the output result...\n List<List<Integer>> output = new ArrayList<List<Integer>>();\n // Base cases...\n\t if (numRows <= 0) return output;\n // Create an array list to store the prev triangle value for further addition...\n\t ArrayList<Integer> prev = new ArrayList<Integer>();\n // Inserting for the first row & store the prev array to the output array...\n\t prev.add(1);\n\t output.add(prev);\n // For rest of the rows, Traverse all elements through a for loop...\n\t for (int i = 2; i <= numRows; i++) {\n // Create another array to store the current triangle value...\n\t\t ArrayList<Integer> curr = new ArrayList<Integer>();\n\t\t curr.add(1); //first\n // Calculate for each of the next values...\n\t\t for (int j = 0; j < prev.size() - 1; j++) {\n // Inserting the addition of the prev arry two values...\n\t\t\t curr.add(prev.get(j) + prev.get(j + 1)); //middle\n\t\t }\n // Store the number 1...\n\t\t curr.add(1); //last\n // Store the value in the Output array...\n\t\t output.add(curr);\n // Set prev is equal to curr...\n\t\t prev = curr;\n\t }\n\t return output; // Return the output list of pascal values...\n }\n}\n```\n\n# **C++ Solution:**\n```\nclass Solution {\npublic:\n vector<vector<int>> generate(int numRows) {\n vector<vector<int>> output;\n // Base cases...\n if(numRows == 0) return output;\n // Traverse all the elements through a loop\n for(int i=0; i<numRows; i++)\n output.push_back(vector<int>(i + 1, 1)); // Initialize the first row of the pascal triangle as {1}.\n // For generating each row of the triangle...\n for (int i = 2; i < numRows; ++i)\n // Run an inner loop from j = 1 to j = {previous row size} for calculating element of each row of the triangle.\n for (int j = 1; j < output[i].size() - 1; ++j)\n // Calculate the elements of a row, add each pair of adjacent elements of the previous row in each step of the inner loop.\n output[i][j] = output[i - 1][j - 1] + output[i - 1][j];\n return output; // After the inner loop gets over, simply output the row generated.\n }\n};\n```\n\n# **Python/Python3 Solution:**\n```\nclass Solution(object):\n def generate(self, numRows):\n # Create an array list to store the output result...\n output = []\n for i in range(numRows):\n if(i == 0):\n # Create a list to store the prev triangle value for further addition...\n # Inserting for the first row & store the prev array to the output array...\n prev = [1]\n output.append(prev)\n else:\n curr = [1]\n j = 1\n # Calculate for each of the next values...\n while(j < i):\n # Inserting the addition of the prev arry two values...\n curr.append(prev[j-1] + prev[j])\n j+=1\n # Store the number 1...\n curr.append(1)\n # Store the value in the Output array...\n output.append(curr)\n # Set prev is equal to curr...\n prev = curr\n return output # Return the output list of pascal values...\n```\n \n# **JavaScript Solution:**\n```\nvar generate = function(numRows) {\n var i = 0;\n var j = 0;\n // Create an array list to store the output result...\n var res = [];\n // For generating each row of the triangle...\n for (i = 0; i < numRows; i++) {\n res.push(Array(i + 1)); // Initialize the first row of the pascal triangle as {1}...\n for (j = 0; j <= i; j++) {\n // Primary...\n if (j === 0 || j === i) {\n res[i][j] = 1;\n }\n else {\n // Calculate the elements of a row, add each pair of adjacent elements of the previous row in each step of the inner loop.\n res[i][j] = res[i - 1][j - 1] + res[i - 1][j];\n }\n }\n }\n return res; // Return the output list of pascal values...\n};\n```\n**I am working hard for you guys...\nPlease upvote if you found any help with this code...**
11,653
Pascal's Triangle
pascals-triangle
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
24,394
213
```\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n return [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1], [1, 6, 15, 20, 15, 6, 1], [1, 7, 21, 35, 35, 21, 7, 1], [1, 8, 28, 56, 70, 56, 28, 8, 1], [1, 9, 36, 84, 126, 126, 84, 36, 9, 1], [1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1], [1, 11, 55, 165, 330, 462, 462, 330, 165, 55, 11, 1], [1, 12, 66, 220, 495, 792, 924, 792, 495, 220, 66, 12, 1], [1, 13, 78, 286, 715, 1287, 1716, 1716, 1287, 715, 286, 78, 13, 1], [1, 14, 91, 364, 1001, 2002, 3003, 3432, 3003, 2002, 1001, 364, 91, 14, 1], [1, 15, 105, 455, 1365, 3003, 5005, 6435, 6435, 5005, 3003, 1365, 455, 105, 15, 1], [1, 16, 120, 560, 1820, 4368, 8008, 11440, 12870, 11440, 8008, 4368, 1820, 560, 120, 16, 1], [1, 17, 136, 680, 2380, 6188, 12376, 19448, 24310, 24310, 19448, 12376, 6188, 2380, 680, 136, 17, 1], [1, 18, 153, 816, 3060, 8568, 18564, 31824, 43758, 48620, 43758, 31824, 18564, 8568, 3060, 816, 153, 18, 1], [1, 19, 171, 969, 3876, 11628, 27132, 50388, 75582, 92378, 92378, 75582, 50388, 27132, 11628, 3876, 969, 171, 19, 1], [1, 20, 190, 1140, 4845, 15504, 38760, 77520, 125970, 167960, 184756, 167960, 125970, 77520, 38760, 15504, 4845, 1140, 190, 20, 1], [1, 21, 210, 1330, 5985, 20349, 54264, 116280, 203490, 293930, 352716, 352716, 293930, 203490, 116280, 54264, 20349, 5985, 1330, 210, 21, 1], [1, 22, 231, 1540, 7315, 26334, 74613, 170544, 319770, 497420, 646646, 705432, 646646, 497420, 319770, 170544, 74613, 26334, 7315, 1540, 231, 22, 1], [1, 23, 253, 1771, 8855, 33649, 100947, 245157, 490314, 817190, 1144066, 1352078, 1352078, 1144066, 817190, 490314, 245157, 100947, 33649, 8855, 1771, 253, 23, 1], [1, 24, 276, 2024, 10626, 42504, 134596, 346104, 735471, 1307504, 1961256, 2496144, 2704156, 2496144, 1961256, 1307504, 735471, 346104, 134596, 42504, 10626, 2024, 276, 24, 1], [1, 25, 300, 2300, 12650, 53130, 177100, 480700, 1081575, 2042975, 3268760, 4457400, 5200300, 5200300, 4457400, 3268760, 2042975, 1081575, 480700, 177100, 53130, 12650, 2300, 300, 25, 1], [1, 26, 325, 2600, 14950, 65780, 230230, 657800, 1562275, 3124550, 5311735, 7726160, 9657700, 10400600, 9657700, 7726160, 5311735, 3124550, 1562275, 657800, 230230, 65780, 14950, 2600, 325, 26, 1], [1, 27, 351, 2925, 17550, 80730, 296010, 888030, 2220075, 4686825, 8436285, 13037895, 17383860, 20058300, 20058300, 17383860, 13037895, 8436285, 4686825, 2220075, 888030, 296010, 80730, 17550, 2925, 351, 27, 1], [1, 28, 378, 3276, 20475, 98280, 376740, 1184040, 3108105, 6906900, 13123110, 21474180, 30421755, 37442160, 40116600, 37442160, 30421755, 21474180, 13123110, 6906900, 3108105, 1184040, 376740, 98280, 20475, 3276, 378, 28, 1], [1, 29, 406, 3654, 23751, 118755, 475020, 1560780, 4292145, 10015005, 20030010, 34597290, 51895935, 67863915, 77558760, 77558760, 67863915, 51895935, 34597290, 20030010, 10015005, 4292145, 1560780, 475020, 118755, 23751, 3654, 406, 29, 1]][:numRows]\n```\n\nWhy so serious? \xAF\\\\\\_(\u30C4)_/\xAF\n\nNOTE: This one is faster than 87.94% of python3 submissions\n
11,654
Pascal's Triangle
pascals-triangle
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
1,444
10
# Intuition\nHere is a real C solution provided which is really very rare.\n\nSolution via Pascal\'s identity $$C^i_j=C^{i-1}_{j-1}+C^{i-1}_{j}$$& $$C^i_j=C^i_{i-j}$$\n\nDon\'t use the built-in function comb(i, j) to compute, because it is very time consuming.\n\nIt is also not suggested direct to use the defintion to compute:\n$$\nC^i_j=\\frac{i!}{j!(i-j)!}\n$$\nwhere the compting for factorial $i!$ is very slow $O(i)$& will overflow when $i$ is more than 12 for 32-bit int. Pascal triangle is a theorem for computing binomial coefficients!\n$$\n(x+y)^i=\\sum_{j=0}^i C^i_jx^{i-j}y^j\n$$\n# Use binomial coefficients to prove Pascal\'s triangle:\n$$\n(x+y)^i=\\sum_{j=0}^i C^i_jx^{i-j}y^j\\\\\n=(x+y)^{i-1}(x+y)\\\\\n=\\sum_{j=1}^i C^{i-1}_{j-1}x^ {i-j-1}y^j(x+y)\\\\\n=\\sum_{j=1}^i C^{i-1}_{j-1}x^ {i-j}y^j+\\sum_{j=0}^{i-1} C^{i-1}_{j}x^ {i-j}y^j\n$$\nCompare the coefficients for term $x^{i-j}y^j$, one obtain \n$$C^i_j=C^{i-1}_{j-1}+C^{i-1}_{j}$$ QED.\n# Approach\nIterative DP uses double for loop.\n\n[Please turn English subtitles if neccessary]\n[]()\n# Complexity\n- Time complexity:\n $$O(n^2)$$\n\n- Space complexity:\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n $$O(n^2)$$ for returning answer. $$O(1)$$ for extra need.\n\n\n# Code Runtime 0ms Beats 100%\n```\nclass Solution {\npublic:\n vector<vector<int>> generate(int numRows) {\n vector<vector<int>> a(numRows);\n for(int&& i=0; i<numRows; i++){\n a[i].assign(i+1, 1);// exact allocation once\n for(int&& j=1; j<=i/2; j++){\n a[i][i-j]=a[i][j]=a[i-1][j-1]+a[i-1][j];\n \n } \n }\n return a;\n }\n};\n\n```\n# C code\n```\n/**\n * Return an array of arrays of size *returnSize.\n * The sizes of the arrays are returned as *returnColumnSizes array.\n * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().\n */\nint** generate(int numRows, int* returnSize, int** returnColumnSizes) {\n int** a = (int**)malloc(sizeof(int*) * numRows);\n *returnSize = numRows;\n *returnColumnSizes=(int*)malloc(sizeof(int)*numRows); //Allocate for column sizes array\n\n for (register int i=0; i<numRows; i++) {\n (*returnColumnSizes)[i] =i+1; // Set the size of each row in column sizes array\n a[i] = (int*)malloc(sizeof(int)*(i+1));\n\n a[i][0] = a[i][i] = 1;\n for (register int j=1; j<=i/2; j++) {\n a[i][j]=a[i][i-j]= a[i-1][j-1]+a[i-1][j];\n }\n }\n return a;\n}\n```\n# Python solution\n```\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n a=[[]]*numRows\n for i in range(numRows):\n a[i]=[1]*(i+1)\n for j in range(1,i//2+1):\n a[i][i-j]=a[i][j]=a[i-1][j-1]+a[i-1][j]\n return a\n```\n# Python code using lambda function\n```\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n a = [[1]]\n for i in range(1, numRows):\n a += [list(map(lambda x, y: x+y, a[-1] + [0], [0] + a[-1]))]\n return a[:numRows]\n```\n# Pascal Traingle can solve [62. Unique Paths]()\n[Please turn on English subtitles if necessary]\n[]()
11,669
Pascal's Triangle
pascals-triangle
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
3,787
5
# Intuition\n<!-- Describe your first- thoughts on how to solve this problem. -->\nUsing the for loops and just iterating through it..\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\njust observe the pattern and see for every row the leading and ending 1\'s are in commmon..\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n**2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution:\n def generate(self, n: int) -> List[List[int]]:\n dp=[]\n for i in range(1,n+1):\n dp.append([0]*i)\n for i in range(0,n):\n for j in range(0,i+1):\n if(j==0 or j==i):\n #For leading and trailing of the row the 1 should be appended....\n dp[i][j]=1\n else:\n #The previous values both are added together\n dp[i][j]=dp[i-1][j-1]+dp[i-1][j]\n return dp\n \n```
11,671
Pascal's Triangle
pascals-triangle
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
121
5
# Approach\nLet\'s break down the given Python code step by step. This code defines a class `Solution` with a method `generate` that generates Pascal\'s triangle up to a specified number of rows.\n\n```python\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n```\n\nThis line defines a class called `Solution` with a method `generate`. This method takes an integer `numRows` as an argument and is expected to return a list of lists of integers.\n\n```python\n res = [[1]]\n```\n\nHere, we initialize a list `res` with a single row, which contains only a single element, the number 1. This represents the first row of Pascal\'s triangle.\n\n```python\n for i in range(numRows - 1):\n```\n\nThis for loop runs for `numRows - 1` iterations. It\'s important to note that we already initialized `res` with the first row, so we start generating additional rows.\n\n```python\n temp = [0] + res[-1] + [0]\n```\n\nIn each iteration, we create a new list `temp`. This list is constructed by adding a 0 at the beginning and end of the last row in `res`. This is because Pascal\'s triangle has 1s at its edges, and we\'re preparing `temp` to calculate the values in the next row.\n\n```python\n row = []\n```\n\nWe initialize an empty list `row` to store the elements of the current row we\'re generating.\n\n```python\n for j in range(len(res[-1]) + 1):\n```\n\nThis inner for loop runs for the length of the last row in `res` plus 1. This is because we want to generate one more element than the previous row had.\n\n```python\n row.append(temp[j] + temp[j+1])\n```\n\nIn this line, we calculate each element of the current row by adding the corresponding elements from `temp` and `temp` shifted one position to the right. This is how the values in Pascal\'s triangle are calculated, as each element is the sum of the two elements above it.\n\n```python\n res.append(row)\n```\n\nOnce we have generated the current row (`row`), we append it to the `res` list, which stores all the rows of Pascal\'s triangle.\n\nFinally, after all iterations are complete, we return the `res` list, which contains the Pascal\'s triangle up to the specified number of rows.\n\nIn summary, this code generates Pascal\'s triangle up to the specified number of rows by iteratively calculating each row based on the previous row and appending it to a list of rows (`res`).\n\n# Python Code\n```\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]: \n res = [[1]]\n for i in range(numRows-1):\n temp = [0]+res[-1]+[0]\n row = []\n\n for j in range(len(res[-1])+1):\n row.append(temp[j] + temp[j+1])\n res.append(row)\n\n return res\n\n```\n\n**Please upvote if you like the solution.\nHappy Coding! \uD83D\uDE0A**\n
11,685
Pascal's Triangle
pascals-triangle
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
14,223
142
\u2714\uFE0F ***Solution - I (Dynamic Programming - Iterative)***\n\nThe pascal triangle problem has a very simple and intuitive dynamic programming approach. As the definition states, every element of a row is formed by the sum of the two numbers directly above. So, we can just apply DP and use the previously stored rows of trianlge to calculate the new rows.\n\nWe can just initialize the start and end elements of each row as 1 and update only the elements between them. This will make the code simpler and avoid the need of having extra checks for edge elements of each row.\n\n<iframe src="" width="100%" height=270 frameBorder="0"></iframe>\n\n\n***Time Complexity :*** <b><code>O(n<sup>2</sup>)</code></b>\n***Space Complexity :*** <b><code>O(n<sup>2</sup>)</code></b>\n\n---\n\n\u2714\uFE0F ***Solution - II (Top-Down Recursive)***\n\nHere, the same logic as above is applied, just using a recursive implementation. We will start from the bottom of triangle and recursively call the *`generate(n-1)`*, till the top-most row of trianlge is generated and then construct the bottom rows one-by-one using the values from the above rows.\n\n\n<iframe src="" frameBorder="0" width="100%" height="270"></iframe>\n\n \n\n\n***Time Complexity :*** <b><code>O(n<sup>2</sup>)</code></b>\n***Space Complexity :*** <b><code>O(n<sup>2</sup>)</code></b>\n\n\n---\n---\n\n\uD83D\uDCBB\uD83D\uDC31\u200D\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, please do comment below \uD83D\uDC47 \n\n---\n---
11,698
Pascal's Triangle II
pascals-triangle-ii
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
2,004
40
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\nadd left number and right number in a previous row\n\n---\n\n# Solution Video\n\n\n\n\u25A0 Timeline of the video\n`0:04` Key point to solve this question\n`0:05` Two key points to solve this question\n`0:16` Actually there is a formula for Pascal\'s Triangle\n`0:32` Explain basic idea and the key point\n`2:38` Demonstrate real algorithms\n`6:39` Coding\n`7:43` Time Complexity and Space Complexity\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\n\n\nSubscribers: 2,720\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\nFirst of all there is formula for Pascal\'s Triangle Recurrence Relation.\n\n\n```\nnext_element = previous element\xD7(rowIndex\u2212position+1) / position\n```\n\nBased on the formula, you can implement solution code like this.\n\n```\nclass Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n row = [1]\n\n for i in range(1, rowIndex + 1):\n next_element = row[i - 1] * (rowIndex - i + 1) // i\n row.append(next_element)\n\n return row\n```\n\nBut in real interview, it\'s hard to come up with the formula, so I don\'t use this solution.\n\nWe know that we add left and right numbers in above row, then create a current row.\n\u200B\nso we iterate the same two rows at the same time but add `[0]` to the first position for one row and add `[0]` to the last position for the other row.\n\nThis idea comes from Pascal Tringle \u2160. I have a video here.\n\n\n\n\n---\n\n\u2B50\uFE0F Points\n\nAdd `[0]` to the first position for one row and add `[0]` to the last position for the other row, because we can prevent out of bounds when we iterate thorugh each row and we can create order of left number and order of right number.\n\nWhat I\'m trying to do is for example, when we create the second row, we need to add left and right number in the first row `[1]`. But how?\n\nWhen we create the `index 0` number in the second row, left number in the first row is out of bounds.\n\nThat\'s why we add `0` to the first and the last position of the first row.\n\n`[0,1,0]`\n\nso we can calulcate 0 + 1 for `index 0` in the second row.\nwe can calulcate 1 + 0 for `index 1` in the second row.\n\nin the end, we have `[1,1]`\n\n`0` doesn\'t afffect result of calculation.\n\nWe use this basic idea to this problem.\n\n---\n\nLet\'s see an example.\n\n```\nInput: rowIndex = 3\n```\n\nFirst of all, we initialize `row = [1]`, because the frist row in the triangle row is `1`.\n\nAfter that, we add `[0]` to the first position and the last position respectively.\n\nNow we have\n\n```\n[0,1] (order of left number)\n[1,0] (order of right number)\n\nPascal Triangle I, I created [0,1,0] for the first row.\n\norder of left number is the first two numbers [0,1] in [0,1,0]\norder of right number is the last two numbers [1,0] in [0,1,0]\n```\n\nAdd each position. In the end we have\n```\n[1,1]\n```\n\nNext, add `[0]` to the first and the last.\n```\n[0,1,1] (order of left number)\n[1,1,0] (order of right number)\n\nPascal Triangle I, I created [0,1,1,0] for the second row.\n\norder of left number is the first three numbers [0,1,1] in [0,1,1,0]\norder of right number is the last three numbers [1,1,0] in [0,1,1,0]\n```\n \nAdd each position. In the end we have\n```\n[1,2,1]\n```\n\nNext, add `[0]` to the first and the last.\n```\n[0,1,2,1] (order of left number)\n[1,2,1,0] (order of right number)\n\nPascal Triangle I, I created [0,1,2,1,0] for the third row.\n\norder of left number is the first four numbers [0,1,2,1] in [0,1,2,1,0]\norder of right number is the last four numbers [1,2,1,0] in [0,1,2,1,0]\n```\n\nAdd each position. In the end we have\n```\nOutput: [1,3,3,1]\n```\n\nLet\'s see real algorithm!\n\n### Algorithm Overview:\n1. Initialize a list `row` with a single element, which is 1.\n2. Iterate `rowIndex` times, each time calculating the next row using the binomial coefficient recurrence relation and updating the `row`.\n3. Return the generated row.\n\n### Detailed Explanation:\n1. Start with an initial row containing a single element: [1]. This is the 0th row (rowIndex = 0).\n\n2. For each iteration from 0 to `rowIndex` (exclusive):\n a. Calculate each element of the new row using binomial coefficients.\n b. The element at index `i` in the new row is the sum of the element at index `i` and the element at index `i-1` in the previous row.\n c. Update `row` with the new row for the next iteration.\n\n3. After all iterations, return the `row` which represents the `rowIndex`-th row of Pascal\'s Triangle.\n\n# Complexity\n- Time complexity: $$O(rowIndex^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(rowIndex)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```python []\nclass Solution(object):\n def getRow(self, rowIndex):\n row = [1]\n\n for _ in range(rowIndex):\n row = [left + right for left, right in zip([0]+row, row+[0])]\n \n return row \n```\n```javascript []\n/**\n * @param {number} rowIndex\n * @return {number[]}\n */\nvar getRow = function(rowIndex) {\n let row = [1];\n\n for (let i = 0; i < rowIndex; i++) {\n row = row.map((val, index) => (row[index - 1] || 0) + (row[index] || 0));\n row.push(1);\n }\n\n return row; \n};\n```\n```java []\nclass Solution {\n public List<Integer> getRow(int rowIndex) {\n List<Integer> row = new ArrayList<>();\n row.add(1);\n\n for (int i = 0; i < rowIndex; i++) {\n List<Integer> newRow = new ArrayList<>();\n newRow.add(1);\n for (int j = 1; j < row.size(); j++) {\n newRow.add(row.get(j - 1) + row.get(j));\n }\n newRow.add(1);\n row = newRow;\n }\n\n return row; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> getRow(int rowIndex) {\n vector<int> row(1, 1);\n\n for (int i = 0; i < rowIndex; i++) {\n vector<int> newRow;\n newRow.push_back(1);\n for (int j = 1; j < row.size(); j++) {\n newRow.push_back(row[j - 1] + row[j]);\n }\n newRow.push_back(1);\n row = newRow;\n }\n\n return row; \n }\n};\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\n\n### My next daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n`0:04` Key point to solve this question\n`0:23` Explain the first key point\n`1:12` Explain the second key point\n`1:39` Demonstrate real algorithms\n`6:36` Coding\n`10:33` Time Complexity and Space Complexity\n\n\n\n### My previous daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n`0:04` How we think about a solution\n`0:05` Two key points to solve this question\n`0:21` Explain the first key point\n`1:28` Explain the second key point\n`2:36` Break down and explain real algorithms\n`6:09` Demonstrate how it works\n`10:17` Coding\n`12:58` Time Complexity and Space Complexity\n
11,703
Pascal's Triangle II
pascals-triangle-ii
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
17,631
72
# Intuition\nWhen faced with Pascal\'s Triangle, a fundamental pattern that stands out is the binomial coefficient. The elements of each row in Pascal\'s Triangle can be represented as combinations. Recognizing this mathematical property offers a direct route to the solution without the need to iterate through all the preceding rows.\n\n## Live Coding + Explaining\n\n\n# Approach\nEach row of Pascal\'s Triangle can be represented using the sequence of combinations:\n$$ C(r, 0), C(r, 1), C(r, 2), \\ldots, C(r, r) $$\nwhere $$ C(n, k) $$ is the binomial coefficient, defined as:\n$$ C(n, k) = \\frac{n!}{k!(n-k)!} $$\n\nThe row\'s first element is always 1. Given the previous element in the row (`prev`), the next element can be calculated using:\n$$ \\text{next\\_val} = \\text{prev} \\times \\frac{\\text{rowIndex} - k + 1}{k} $$\nThis formula is derived from the relationship between consecutive binomial coefficients in the same row.\n\nIterating from `k = 1` to `k = rowIndex`, we can directly generate the elements for the desired row without building the entire triangle.\n\n# Complexity\n- Time complexity: $$O(\\text{rowIndex})$$\nThis is because we are directly computing the rowIndex-th row without iterating through all previous rows.\n\n- Space complexity: $O(\\text{rowIndex})$\nThe only significant space used is for the result list, which has a length of rowIndex + 1.\n\n# Code\n``` Python []\nclass Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n res = [1]\n prev = 1\n for k in range(1, rowIndex + 1):\n next_val = prev * (rowIndex - k + 1) // k\n res.append(next_val)\n prev = next_val\n return res\n```\n``` C++ []\nclass Solution {\npublic:\n std::vector<int> getRow(int rowIndex) {\n std::vector<int> res(1, 1);\n long long prev = 1;\n for(int k = 1; k <= rowIndex; k++) {\n long long next_val = prev * (rowIndex - k + 1) / k;\n res.push_back(next_val);\n prev = next_val;\n }\n return res;\n }\n};\n```\n``` Java []\npublic class Solution {\n public List<Integer> getRow(int rowIndex) {\n List<Integer> res = new ArrayList<>();\n res.add(1);\n long prev = 1;\n for (int k = 1; k <= rowIndex; k++) {\n long next_val = prev * (rowIndex - k + 1) / k;\n res.add((int) next_val);\n prev = next_val;\n }\n return res;\n }\n}\n```\n``` Go []\nfunc getRow(rowIndex int) []int {\n res := []int{1}\n prev := 1\n for k := 1; k <= rowIndex; k++ {\n next_val := prev * (rowIndex - k + 1) / k\n res = append(res, next_val)\n prev = next_val\n }\n return res\n}\n```\n``` Rust []\nimpl Solution {\n pub fn get_row(row_index: i32) -> Vec<i32> {\n let mut res = vec![1];\n let mut prev: i64 = 1; // use i64 for the calculations\n for k in 1..=row_index {\n let next_val = prev * (row_index - k + 1) as i64 / k as i64;\n res.push(next_val as i32);\n prev = next_val;\n }\n res\n }\n}\n```\n``` PHP []\nclass Solution {\n function getRow($rowIndex) {\n $res = [1];\n $prev = 1;\n for($k = 1; $k <= $rowIndex; $k++) {\n $next_val = $prev * ($rowIndex - $k + 1) / $k;\n $res[] = $next_val;\n $prev = $next_val;\n }\n return $res;\n }\n}\n```\n``` JavaScript []\nvar getRow = function(rowIndex) {\n let res = [1];\n let prev = 1;\n for(let k = 1; k <= rowIndex; k++) {\n let next_val = prev * (rowIndex - k + 1) / k;\n res.push(next_val);\n prev = next_val;\n }\n return res;\n};\n```\n``` C# []\npublic class Solution {\n public IList<int> GetRow(int rowIndex) {\n List<int> res = new List<int> {1};\n long prev = 1;\n for (int k = 1; k <= rowIndex; k++) {\n long next_val = prev * (rowIndex - k + 1) / k;\n res.Add((int)next_val);\n prev = next_val;\n }\n return res;\n }\n}\n```\n\n\n## Performance\n\n| Language | Runtime (ms) | Memory (MB) |\n|------------|--------------|-------------|\n| Rust | 0 ms | 2 MB |\n| Java | 0 ms | 39.8 MB |\n| C++ | 0 ms | 6.9 MB |\n| Go | 1 ms | 1.9 MB |\n| PHP | 3 ms | 19.1 MB |\n| Python3 | 36 ms | 16.2 MB |\n| JavaScript | 45 ms | 42 MB |\n| C# | 83 ms | 35.8 MB |\n\n![v7.png]()\n\n\n# What have we learned?\nThis problem teaches us the importance of recognizing patterns and mathematical properties in data. Rather than relying on a brute-force approach (i.e., building the entire Pascal\'s Triangle up to the desired row), we leveraged the properties of binomial coefficients to directly compute the required row. This understanding reduces both the time and space complexity of our solution. The logic behind this solution is the inherent mathematical relationship between consecutive binomial coefficients in Pascal\'s Triangle, which allows us to compute the next coefficient given the previous one. This is a testament to the power of mathematical insight in algorithm design.
11,704
Pascal's Triangle II
pascals-triangle-ii
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
5,984
39
# Problem Description\nGiven an integer rowIndex, return the `rowIndexth` (0-indexed) row of the **Pascal\'s triangle**.\n\nIn **Pascal\'s triangle**, each number is the sum of the two numbers directly above it as shown:\n\n![PascalTriangleAnimated2.gif]()\n\n- **Constraints:**\n - `0 <= rowIndex <= 33`\n\n\n---\n\n\n# Proposed Solutions\n## 1. Dynamic Programming\n\n### Approach\n1. **Initialize 2D Vector**: Create a 2D vector pascalTriangle with numRows rows to represent Pascal\'s Triangle.\n2. **Generate Rows**: Generate first row seperately then Loop through each row from 1 to numRows (inclusive).\n3. **Set First and Last Elements**: Set the first and last elements of each row to 1.\n4. **Calculate Middle Elements**: For each row, calculate and append the middle elements by adding the corresponding elements from the previous row.\n5. **Return** Last computed row.\n\n### Complexity\n- **Time complexity:**\nWe have two for-loops each of max size of `n`, then time complexity is `O(N^2)`.\n- **Space complexity:**\n`O(N^2)`, Since we are storing the triangle.\n\n\n---\n\n## 2. Dynamic Programming Optimized Space\n\n### Approach\n1. **Initialize 2D Vector**: Create a 2D vector pascalTriangle with only two rows to represent last two rows of our Pascal\'s Triangle.\n2. **Generate Rows**: Generate first row seperately then Loop through each row from 1 to numRows (inclusive).\n3. **Set First and Last Elements**: Set the first and last elements of each row to 1.\n4. **Calculate Middle Elements**: For each row, calculate and append the middle elements by adding the corresponding elements from the previous row.\n5. **Change Rows**: After each iteration, switch the last computed row with the first row then deleted its vector.\n6. **Return** Last computed row.\n\n### Complexity\n- **Time complexity:**\nWe have two for-loops each of max size of `n`, then time complexity is `O(N^2)`.\n- **Space complexity:**\n`O(N)`, Since we are storing only two rows each iteration.\n\n\n\n---\n\n\n\n## 3. Combinatorics \n\n**Note: For this solution, it can be done in one for loop but I wanted to write the whole function of calculateCombination to show you how to calculate combinatorics generally.**\n\n### Approach\n1. **Initialize Vector**: Create a vector lastRow with that represents the last row.\n2. **Generate Row**: Loop through each element in the last row.\n3. **Calculate Middle Elements**: For each element, calculate and append them by using combinatorics like the picture below :\n![leet.PNG]()\n\n4. **Return** Last computed row.\n\n\n### Complexity\n- **Time complexity:**\nWe have one for-loops of max size of `n` and we have the for loop that generates the combinatorics, then time complexity is `O(N^2)`.\n- **Space complexity:**\n`O(N)`, Since we are storing only the last row.\n\n\n\n\n\n---\n\n\n# Code\n## 1. Dynamic Programming\n```C++ []\nclass Solution {\npublic:\n vector<int> getRow(int rowIndex) {\n // Initialize a 2D vector to represent Pascal\'s Triangle\n vector<vector<int>> pascalTriangle(rowIndex + 1);\n\n // Initialize the first row with a single element \'1\'\n pascalTriangle[0].push_back(1);\n\n // Generate the rest of the rows\n for (int currentRow = 1; currentRow <= rowIndex; currentRow++) {\n // The first element of each row is always \'1\'\n pascalTriangle[currentRow].push_back(1);\n\n // Get a reference to the current row and the previous row\n vector<int>& currentRowList = pascalTriangle[currentRow];\n vector<int>& previousRowList = pascalTriangle[currentRow - 1];\n\n // Calculate and populate the middle elements of the row\n for (int j = 1; j < previousRowList.size(); j++) {\n int sum = previousRowList[j] + previousRowList[j - 1];\n currentRowList.push_back(sum);\n }\n\n // The last element of each row is also \'1\'\n currentRowList.push_back(1);\n }\n\n return pascalTriangle[rowIndex];\n }\n};\n```\n```Java []\nclass Solution {\n public List<Integer> getRow(int rowIndex) {\n // Initialize a 2D list to represent Pascal\'s Triangle\n List<List<Integer>> pascalTriangle = new ArrayList<>();\n \n // Generate the rows\n for (int i = 0; i <= rowIndex; i++) {\n List<Integer> currentRow = new ArrayList<>();\n \n // The first element of each row is always \'1\'\n currentRow.add(1);\n \n if (i > 0) {\n // Get a reference to the previous row\n List<Integer> previousRow = pascalTriangle.get(i - 1);\n \n // Calculate and populate the middle elements of the row\n for (int j = 1; j < previousRow.size(); j++) {\n int sum = previousRow.get(j) + previousRow.get(j - 1);\n currentRow.add(sum);\n }\n \n // The last element of each row is also \'1\'\n currentRow.add(1);\n }\n \n pascalTriangle.add(currentRow);\n }\n \n return pascalTriangle.get(rowIndex);\n }\n}\n```\n```Python []\nclass Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n # Initialize a list of lists to represent Pascal\'s Triangle\n pascal_triangle = [[] for _ in range(rowIndex + 1)]\n \n # Initialize the first row with a single element \'1\'\n pascal_triangle[0].append(1)\n \n # Generate the rest of the rows\n for current_row in range(1, rowIndex + 1):\n # The first element of each row is always \'1\'\n pascal_triangle[current_row].append(1)\n \n # Calculate and populate the middle elements of the row\n for j in range(1, len(pascal_triangle[current_row - 1])):\n sum_val = pascal_triangle[current_row - 1][j] + pascal_triangle[current_row - 1][j - 1]\n pascal_triangle[current_row].append(sum_val)\n \n # The last element of each row is also \'1\'\n pascal_triangle[current_row].append(1)\n \n return pascal_triangle[rowIndex]\n\n```\n``` C []\nint* getRow(int rowIndex, int* returnSize) {\n // Initialize a 2D array to represent Pascal\'s Triangle\n int** pascalTriangle = (int**)malloc((rowIndex + 1) * sizeof(int*));\n \n for (int i = 0; i <= rowIndex; i++) {\n pascalTriangle[i] = (int*)malloc((i + 1) * sizeof(int));\n }\n \n // Generate the rows\n for (int currentRow = 0; currentRow <= rowIndex; currentRow++) {\n pascalTriangle[currentRow][0] = 1; // The first element of each row is always \'1\'\n \n if (currentRow > 0) {\n int* previousRow = pascalTriangle[currentRow - 1];\n \n // Calculate and populate the middle elements of the row\n for (int j = 1; j < currentRow; j++) {\n pascalTriangle[currentRow][j] = previousRow[j] + previousRow[j - 1];\n }\n \n pascalTriangle[currentRow][currentRow] = 1; // The last element of each row is also \'1\'\n }\n }\n \n // Set the return size\n *returnSize = rowIndex + 1;\n \n // Copy the row to a 1D array\n int* resultRow = (int*)malloc((rowIndex + 1) * sizeof(int));\n for (int i = 0; i <= rowIndex; i++) {\n resultRow[i] = pascalTriangle[rowIndex][i];\n }\n \n return resultRow;\n}\n```\n\n---\n\n\n## 2. Dynamic Programming Optimized Space\n\n```C++ []\nclass Solution {\npublic:\n vector<int> getRow(int rowIndex) {\n // Initialize a 2D vector to represent Pascal\'s Triangle\n vector<vector<int>> pascalTriangle(2);\n\n // Initialize the first row with a single element \'1\'\n pascalTriangle[0].push_back(1);\n\n // Generate the rest of the rows\n for (int currentRow = 1; currentRow <= rowIndex; currentRow++) {\n // The first element of each row is always \'1\'\n pascalTriangle[1].push_back(1);\n\n // Get a reference to the current row and the previous row\n vector<int>& currentRowList = pascalTriangle[1];\n vector<int>& previousRowList = pascalTriangle[0];\n\n // Calculate and populate the middle elements of the row\n for (int j = 1; j < previousRowList.size(); j++) {\n int sum = previousRowList[j] + previousRowList[j - 1];\n currentRowList.push_back(sum);\n }\n\n // The last element of each row is also \'1\'\n currentRowList.push_back(1);\n\n // Switch rows\n pascalTriangle[0] = pascalTriangle[1] ;\n pascalTriangle[1].clear() ;\n }\n\n return pascalTriangle[0];\n }\n};\n```\n```Java []\nclass Solution {\n public List<Integer> getRow(int rowIndex) {\n List<List<Integer>> pascalTriangle = new ArrayList<>();\n pascalTriangle.add(new ArrayList<>());\n pascalTriangle.add(new ArrayList<>());\n\n // Initialize the first row with a single element \'1\'\n pascalTriangle.get(0).add(1);\n\n // Generate the rest of the rows\n for (int currentRow = 1; currentRow <= rowIndex; currentRow++) {\n // The first element of each row is always \'1\'\n pascalTriangle.get(1).add(1);\n\n List<Integer> currentRowList = pascalTriangle.get(1);\n List<Integer> previousRowList = pascalTriangle.get(0);\n\n // Calculate and populate the middle elements of the row\n for (int j = 1; j < previousRowList.size(); j++) {\n int sum = previousRowList.get(j) + previousRowList.get(j - 1);\n currentRowList.add(sum);\n }\n\n // The last element of each row is also \'1\'\n currentRowList.add(1);\n\n // Switch rows\n pascalTriangle.set(0, new ArrayList<>(pascalTriangle.get(1)));\n pascalTriangle.get(1).clear();\n }\n\n return pascalTriangle.get(0);\n }\n}\n```\n```Python []\nclass Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n pascal_triangle = [[1], []]\n\n for currentRow in range(1, rowIndex + 1):\n # The first element of each row is always \'1\'\n pascal_triangle[1].append(1)\n\n currentRowList = pascal_triangle[1]\n previousRowList = pascal_triangle[0]\n\n # Calculate and populate the middle elements of the row\n for j in range(1, len(previousRowList)):\n sum_val = previousRowList[j] + previousRowList[j - 1]\n currentRowList.append(sum_val)\n\n # The last element of each row is also \'1\'\n currentRowList.append(1)\n\n # Switch rows\n pascal_triangle[0] = pascal_triangle[1][:]\n pascal_triangle[1] = []\n\n return pascal_triangle[0]\n```\n``` C []\nint* getRow(int rowIndex, int* returnSize) {\n // Initialize a 2D array to represent Pascal\'s Triangle\n int** pascalTriangle = (int**)malloc(2 * sizeof(int*));\n for (int i = 0; i < 2; i++) {\n pascalTriangle[i] = (int*)malloc((rowIndex + 1) * sizeof(int));\n }\n\n // Initialize the first row with a single element \'1\'\n pascalTriangle[0][0] = 1;\n int currentRow = 1;\n\n // Generate the rest of the rows\n for (int i = 1; i <= rowIndex; i++) {\n // The first element of each row is always \'1\'\n pascalTriangle[currentRow][0] = 1;\n\n // Calculate and populate the middle elements of the row\n for (int j = 1; j < i; j++) {\n pascalTriangle[currentRow][j] = pascalTriangle[1 - currentRow][j] + pascalTriangle[1 - currentRow][j - 1];\n }\n\n // The last element of each row is also \'1\'\n pascalTriangle[currentRow][i] = 1;\n\n // Switch rows\n currentRow = 1 - currentRow;\n }\n\n *returnSize = rowIndex + 1;\n\n // Copy the row to a 1D array\n int* resultRow = (int*)malloc((rowIndex + 1) * sizeof(int));\n for (int i = 0; i <= rowIndex; i++) {\n resultRow[i] = pascalTriangle[1 - currentRow][i];\n }\n\n return resultRow;\n}\n```\n\n---\n\n\n## 3. Combinatorics\n```C++ []\nclass Solution {\npublic:\n // Calculate n choose r (nCr) using a loop\n int calculateCombination(int n, int r) {\n long long result = 1;\n for (int i = 0; i < r; i++) {\n result = result * (n - i) / (i + 1);\n }\n return result;\n }\n\n vector<int> getRow(int rowIndex) {\n // Initialize a vector to represent The last Row\n vector<int> lastRow;\n\n for (int j = 0; j <= rowIndex; j++) {\n // Calculate and insert the binomial coefficient (nCr) into the row\n lastRow.push_back(calculateCombination(rowIndex, j));\n }\n \n return lastRow;\n }\n};\n```\n```Java []\nclass Solution {\n // Calculate n choose r (nCr) using a loop\n private long calculateCombination(int n, int r) {\n long result = 1;\n for (int i = 0; i < r; i++) {\n result = result * (n - i) / (i + 1);\n }\n return result;\n }\n\n public List<Integer> getRow(int rowIndex) {\n // Initialize a list to represent the last row\n List<Integer> lastRow = new ArrayList<>();\n\n for (int j = 0; j <= rowIndex; j++) {\n // Calculate and insert the binomial coefficient (nCr) into the row\n lastRow.add((int) calculateCombination(rowIndex, j));\n }\n\n return lastRow;\n }\n}\n```\n```Python []\nclass Solution:\n def calculateCombination(self, n: int, r: int) -> int:\n result = 1\n for i in range(r):\n result = result * (n - i) // (i + 1)\n return result\n\n def getRow(self, rowIndex: int) -> list[int]:\n last_row = []\n\n for j in range(rowIndex + 1):\n # Calculate and append the binomial coefficient (nCr) into the row\n last_row.append(self.calculateCombination(rowIndex, j))\n\n return last_row\n```\n```C []\nlong long calculateCombination(int n, int r) {\n long long result = 1;\n for (int i = 0; i < r; i++) {\n result = result * (n - i) / (i + 1);\n }\n return result;\n}\n\nint* getRow(int rowIndex, int* returnSize) {\n // Initialize an array to represent the last row\n int* lastRow = (int*)malloc((rowIndex + 1) * sizeof(int));\n\n for (int j = 0; j <= rowIndex; j++) {\n // Calculate and insert the binomial coefficient (nCr) into the row\n lastRow[j] = (int)calculateCombination(rowIndex, j);\n }\n\n *returnSize = rowIndex + 1;\n\n return lastRow;\n}\n```\n\n\n\n![leet_sol.jpg]()\n\n
11,738
Pascal's Triangle II
pascals-triangle-ii
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
272
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn this solution, we use the concept of combinations (n choose k) to calculate each element of the Pascal\'s Triangle\'s row. We start with a value of 1 and update it in each step by multiplying by the relevant factor to get the next value in the row. By leveraging the mathematical properties of combinations, we can efficiently compute the row.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize an empty vector `result` to store the row.\n\n2. Initialize a variable `val` to 1, which represents the current value.\nIterate from 0 to `rowIndex`:\n\n- Set the current value in the `result` vector at index `i` to `val`.\n- Update `val` by multiplying it with `(rowIndex - i) / (i + 1)`. This step calculates the next value based on combinations.\n\n3. After the loop, `result` contains the row of Pascal\'s Triangle at the given `rowIndex`.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is `O(rowIndex)` because we iterate through rowIndex elements, performing constant time operations for each element.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(rowIndex) because we store the row in the `result` vector, which has `rowIndex + 1` elements. The `val` variable is of constant space.\n# Code\n```\n/* class Solution {\npublic:\n vector<int> getRow(int rowIndex) {\n vector<int> prevRow(rowIndex + 1, 1);\n vector<int> currentRow(rowIndex + 1, 1);\n \n for (int i = 1; i <= rowIndex; i++) {\n for (int j = 1; j < i; j++) {\n currentRow[j] = prevRow[j - 1] + prevRow[j];\n }\n swap(prevRow, currentRow);\n }\n \n return prevRow;\n }\n};\n//using two array and swapping */\n\nclass Solution {\npublic:\n vector<int> getRow(int rowIndex) {\n vector<int> result(rowIndex + 1);\n long long val = 1;\n \n for (int i = 0; i <= rowIndex; i++) {\n result[i] = val;\n val = val * (rowIndex - i) / (i + 1);\n }\n \n return result;\n }\n};\n\n```\n\n# \uD83D\uDCA1If you come this far, then i would like to request you to please upvote this solution so that it could reach out to another one \u2763\uFE0F\uD83D\uDCA1
11,739
Pascal's Triangle II
pascals-triangle-ii
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
2,022
21
![Screenshot 2023-10-16 094451.png]()\n\n# Intuition\n\nPascal\'s triangle is a mathematical structure where each number is obtained by summing up the two numbers directly above it. In the context of this problem, you\'re asked to find the `rowIndex`-th row of Pascal\'s triangle. \n# YouTube Video Explanation\n[]()\n\n\uD83D\uDD25 ***Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.***\n\nSubscribe Link: \n\n***Subscribe Goal: 100 Subscribers\nCurrent Subscribers: 74***\n\n## Approach 1: Straightforward Solution\n- This approach directly constructs Pascal\'s triangle up to the `rowIndex`. It iterates through the rows, calculating each element based on the rule of Pascal\'s triangle.\n- We start with the first row (which is [1]) and continue building the triangle by calculating each row based on the previous row.\n- For each element in a row, we sum the two elements from the previous row directly above it.\n- We repeat this process until we reach the `rowIndex`.\n- The final row will be the `rowIndex`-th row of Pascal\'s triangle.\n\n```\nclass Solution {\n public List<Integer> getRow(int rowIndex) {\n List<List<Integer>> ans = new ArrayList<>();\n for(int i=1;i<=rowIndex+1;i++)\n {\n List<Integer> list = new ArrayList<>();\n for(int j=0;j<i;j++)\n {\n if(j==0 || j==i-1)\n list.add(1);\n else\n list.add(ans.get(i-2).get(j-1)+ans.get(i-2).get(j));\n }\n ans.add(list);\n if(i==rowIndex+1)\n return list;\n }\n return new ArrayList<>();\n }\n}\n```\n\n\n## Approach 2: Faster Solution\n- This approach is optimized to calculate only the `rowIndex`-th row without constructing the entire triangle.\n- It uses the binomial coefficient formula (n choose k) to calculate each element of the row directly.\n- We start with the first element (1) and use the formula to calculate the subsequent elements.\n- The formula allows us to efficiently calculate each element without the need to build the entire Pascal\'s triangle.\n- The resulting list is the `rowIndex`-th row of Pascal\'s triangle.\n\n```\nclass Solution {\n public List<Integer> getRow(int row) {\n List<Integer> list = new ArrayList<>();\n long start=1;\n list.add((int)start);\n for(int i=0;i<row;i++)\n {\n start*=(row-i);\n start/=(i+1);\n list.add((int)start);\n }\n return list;\n }\n}\n```\n\n# Complexity\n## Approach 1 (Straightforward Solution):\n\nIn this approach, we iterate through rows and elements, building the entire Pascal\'s triangle up to the given rowIndex. Therefore, the time complexity is **`O(rowIndex^2)`**. This is because for each row i, we calculate i elements, and we do this for rows from 1 to rowIndex.\n\n## Approach 2 (Faster Solution):\n\nIn the second approach, we directly calculate the elements of the rowIndex, which is much faster and more efficient. It requires only a single loop that runs for rowIndex. So, the time complexity for this approach is **`O(rowIndex)`**.\n\n# Code\n<iframe src="" frameBorder="0" width="600" height="300"></iframe>\n\n---\n\n![upvote1.jpeg]()\n\n
11,740
Pascal's Triangle II
pascals-triangle-ii
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
3,284
33
Here\'s the problem statement:\n\nGiven an integer `k`, return the `k`-th row of the Pascal\'s triangle.\n\nNow, let\'s discuss the approaches to solve this problem from naive to efficient:\n\n## 1. Naive Approach: 79% Beats\uD83D\uDE80\n - Generate Pascal\'s triangle up to the `k`-th row and return the `k`-th row.\n - This approach involves generating all the rows up to the `k`-th row and then returning the desired row.\n### \uD83D\uDEA9Time complexity: O(k^2) as you need to generate all previous rows.\n### \uD83D\uDEA9Space complexity: O(k^2) to store all rows.\n\n``` Java []\n// 79% Beats\nclass Solution {\n public List<Integer> getRow(int rowIndex) {\n List<List<Integer>> triangle = new ArrayList<>();\n\n for (int i = 0; i <= rowIndex; i++) {\n List<Integer> row = new ArrayList<>();\n for (int j = 0; j <= i; j++) {\n if (j == 0 || j == i) {\n row.add(1); // The first and last elements in each row are 1.\n } else {\n int prevRow = i - 1;\n int leftVal = triangle.get(prevRow).get(j - 1);\n int rightVal = triangle.get(prevRow).get(j);\n row.add(leftVal + rightVal); // Sum of the two numbers above.\n }\n }\n triangle.add(row);\n }\n\n return triangle.get(rowIndex);\n }\n}\n```\n``` C++ []\n// 60% Beast\nclass Solution {\npublic:\n vector<int> getRow(int rowIndex) {\n std::vector<std::vector<int>> triangle;\n\n for (int i = 0; i <= rowIndex; i++) {\n std::vector<int> row(i + 1);\n for (int j = 0; j <= i; j++) {\n if (j == 0 || j == i) {\n row[j] = 1; // The first and last elements in each row are 1.\n } else {\n int prevRow = i - 1;\n int leftVal = triangle[prevRow][j - 1];\n int rightVal = triangle[prevRow][j];\n row[j] = leftVal + rightVal; // Sum of the two numbers above.\n }\n }\n triangle.push_back(row);\n }\n\n return triangle[rowIndex];\n }\n};\n```\n``` Python []\n# 88% Beats\nclass Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n triangle = []\n\n for i in range(rowIndex + 1):\n row = []\n for j in range(i + 1):\n if j == 0 or j == i:\n row.append(1) # The first and last elements in each row are 1.\n else:\n prevRow = i - 1\n leftVal = triangle[prevRow][j - 1]\n rightVal = triangle[prevRow][j]\n row.append(leftVal + rightVal) # Sum of the two numbers above.\n\n triangle.append(row)\n\n return triangle[rowIndex]\n\n```\n``` JavaScript []\n// 87% Beast\nvar getRow = function(rowIndex) {\n let triangle = [];\n\n for (let i = 0; i <= rowIndex; i++) {\n let row = [];\n for (let j = 0; j <= i; j++) {\n if (j === 0 || j === i) {\n row.push(1); // The first and last elements in each row are 1.\n } else {\n let prevRow = i - 1;\n let leftVal = triangle[prevRow][j - 1];\n let rightVal = triangle[prevRow][j];\n row.push(leftVal + rightVal); // Sum of the two numbers above.\n }\n }\n triangle.push(row);\n }\n\n return triangle[rowIndex];\n};\n```\n``` C# []\n// 50% Beats\npublic class Solution {\n public IList<int> GetRow(int rowIndex) {\n List<List<int>> triangle = new List<List<int>>();\n\n for (int i = 0; i <= rowIndex; i++)\n {\n List<int> row = new List<int>();\n for (int j = 0; j <= i; j++)\n {\n if (j == 0 || j == i)\n {\n row.Add(1); // The first and last elements in each row are 1.\n }\n else\n {\n int prevRow = i - 1;\n int leftVal = triangle[prevRow][j - 1];\n int rightVal = triangle[prevRow][j];\n row.Add(leftVal + rightVal); // Sum of the two numbers above.\n }\n }\n triangle.Add(row);\n }\n\n return triangle[rowIndex]; \n }\n}\n```\n![vote.jpg]()\n\n---\n## 2. Combinatorial Approach: 100% Beats\uD83D\uDE80\n - Utilize the combinatorial properties of Pascal\'s triangle.\n - Use the binomial coefficient formula to directly compute the `k`-th row.\n#### \uD83D\uDEA9Time complexity: O(k).\n#### \uD83D\uDEA9Space complexity: O(k) for storing the result.\n``` Java []\n// 100% Beats\nclass Solution {\n public List<Integer> getRow(int rowIndex) {\n List<Integer> result = new ArrayList<>();\n\n // Initialize the first element of the row to 1.\n result.add(1);\n\n // Calculate each element in the row using the binomial coefficient formula.\n for (int i = 1; i <= rowIndex; i++) {\n long prevElement = (long) result.get(i - 1);\n // Use the formula C(rowIndex, i) = C(rowIndex, i-1) * (rowIndex - i + 1) / i\n long currentElement = prevElement * (rowIndex - i + 1) / i;\n result.add((int) currentElement);\n }\n\n return result;\n }\n}\n```\n``` C++ []\n// 100% Beats\nclass Solution {\npublic:\n vector<int> getRow(int rowIndex) {\n std::vector<int> result;\n\n // Initialize the first element of the row to 1.\n result.push_back(1);\n\n // Calculate each element in the row using the binomial coefficient formula.\n for (int i = 1; i <= rowIndex; i++) {\n long prevElement = result[i - 1];\n // Use the formula C(r, i) = C(r, i-1) * (r - i + 1) / i\n long currentElement = prevElement * (rowIndex - i + 1) / i;\n result.push_back(static_cast<int>(currentElement));\n }\n\n return result;\n }\n};\n```\n``` Python []\n# 25% Beats\nclass Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n result = [1]\n\n for i in range(1, rowIndex + 1):\n prevElement = result[i - 1]\n # Use the formula C(r, i) = C(r, i-1) * (r - i + 1) / i\n currentElement = prevElement * (rowIndex - i + 1) // i\n result.append(currentElement)\n\n return result\n\n```\n``` JavaScript []\n// 93% Beats\nvar getRow = function(rowIndex) {\n let result = [1];\n\n for (let i = 1; i <= rowIndex; i++) {\n let prevElement = result[i - 1];\n // Use the formula C(r, i) = C(r, i-1) * (r - i + 1) / i\n let currentElement = (prevElement * (rowIndex - i + 1)) / i;\n result.push(currentElement);\n }\n\n return result;\n};\n```\n``` C# []\n// 30% Beats\npublic class Solution {\n public IList<int> GetRow(int rowIndex) {\n List<int> result = new List<int>();\n\n // Initialize the first element of the row to 1.\n result.Add(1);\n\n // Calculate each element in the row using the binomial coefficient formula.\n for (int i = 1; i <= rowIndex; i++)\n {\n long prevElement = result[i - 1];\n // Use the formula C(r, i) = C(r, i-1) * (r - i + 1) / i\n long currentElement = prevElement * (rowIndex - i + 1) / i;\n result.Add((int)currentElement);\n }\n\n return result;\n }\n}\n```\n![vote.jpg]()\n\n---\n## 3. Dynamic Programming Approach: 79% Beats\uD83D\uDE80\n - Calculate the `k`-th row using a dynamic programming approach.\n - Initialize an array to store the current row and use the values from the previous row to compute the current row.\n#### \uD83D\uDEA9Time complexity: O(k^2) (less efficient than the combinatorial approach).\n#### \uD83D\uDEA9Space complexity: O(k) for storing the current row.\n``` Java []\n// 79% Beats\nclass Solution {\n public List<Integer> getRow(int rowIndex) {\n List<Integer> currentRow = new ArrayList<Integer>();\n\n // Base case: The first row is always [1].\n currentRow.add(1);\n\n for (int i = 1; i <= rowIndex; i++) {\n List<Integer> newRow = new ArrayList<Integer>();\n \n // The first element of each row is always 1.\n newRow.add(1);\n\n // Calculate the middle elements using the values from the previous row.\n for (int j = 1; j < i; j++) {\n int sum = currentRow.get(j - 1) + currentRow.get(j);\n newRow.add(sum);\n }\n\n // The last element of each row is always 1.\n newRow.add(1);\n\n // Update the current row with the newly calculated row.\n currentRow = newRow;\n }\n \n return currentRow;\n }\n}\n```\n``` C++ []\n// 100% Beats\nclass Solution {\npublic:\n vector<int> getRow(int rowIndex) {\n std::vector<int> currentRow;\n\n // Base case: The first row is always [1].\n currentRow.push_back(1);\n\n for (int i = 1; i <= rowIndex; i++) {\n std::vector<int> newRow;\n \n // The first element of each row is always 1.\n newRow.push_back(1);\n\n // Calculate the middle elements using the values from the previous row.\n for (int j = 1; j < i; j++) {\n int sum = currentRow[j - 1] + currentRow[j];\n newRow.push_back(sum);\n }\n\n // The last element of each row is always 1.\n newRow.push_back(1);\n\n // Update the current row with the newly calculated row.\n currentRow = newRow;\n }\n \n return currentRow;\n }\n};\n```\n``` Python []\n# 50% Beats\nclass Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n currentRow = []\n\n # Base case: The first row is always [1].\n currentRow.append(1)\n\n for i in range(1, rowIndex + 1):\n newRow = []\n \n # The first element of each row is always 1.\n newRow.append(1)\n\n # Calculate the middle elements using the values from the previous row.\n for j in range(1, i):\n sum_val = currentRow[j - 1] + currentRow[j]\n newRow.append(sum_val)\n\n # The last element of each row is always 1.\n newRow.append(1)\n\n # Update the current row with the newly calculated row.\n currentRow = newRow\n \n return currentRow\n\n```\n``` JavaScript []\n// 73% Beats\nvar getRow = function(rowIndex) {\n let currentRow = [];\n\n // Base case: The first row is always [1].\n currentRow.push(1);\n\n for (let i = 1; i <= rowIndex; i++) {\n let newRow = [];\n \n // The first element of each row is always 1.\n newRow.push(1);\n\n // Calculate the middle elements using the values from the previous row.\n for (let j = 1; j < i; j++) {\n let sum = currentRow[j - 1] + currentRow[j];\n newRow.push(sum);\n }\n\n // The last element of each row is always 1.\n newRow.push(1);\n\n // Update the current row with the newly calculated row.\n currentRow = newRow;\n }\n \n return currentRow;\n};\n```\n``` C# []\n// 55% Beats\npublic class Solution {\n public IList<int> GetRow(int rowIndex) {\n List<int> currentRow = new List<int>();\n\n // Base case: The first row is always [1].\n currentRow.Add(1);\n\n for (int i = 1; i <= rowIndex; i++){\n List<int> newRow = new List<int>();\n \n // The first element of each row is always 1.\n newRow.Add(1);\n\n // Calculate the middle elements using the values from the previous row.\n for (int j = 1; j < i; j++)\n {\n int sum = currentRow[j - 1] + currentRow[j];\n newRow.Add(sum);\n }\n\n // The last element of each row is always 1.\n newRow.Add(1);\n\n // Update the current row with the newly calculated row.\n currentRow = newRow;\n }\n \n return currentRow;\n }\n}\n```\n![vote.jpg]()\n\n---\n## 4. Efficient Space Dynamic Programming Approach: 80% Beats\uD83D\uDE80\n - You can optimize the dynamic programming approach by using two arrays to represent the current and previous rows.\n - This reduces the space complexity\n#### \uD83D\uDEA9while maintaining the time complexity of O(k^2).\n#### \uD83D\uDEA9space complexity to O(k) \n``` Java []\n// 80% Beats\nclass Solution {\n public List<Integer> getRow(int rowIndex) {\n List<Integer> currentRow = new ArrayList<>();\n List<Integer> previousRow = new ArrayList<>();\n\n for (int i = 0; i <= rowIndex; i++) {\n currentRow = new ArrayList<>();\n for (int j = 0; j <= i; j++) {\n if (j == 0 || j == i) {\n currentRow.add(1); // The first and last elements are always 1.\n } else {\n int sum = previousRow.get(j - 1) + previousRow.get(j);\n currentRow.add(sum);\n }\n }\n\n previousRow = new ArrayList<>(currentRow);\n }\n\n return currentRow;\n }\n}\n```\n``` C++ []\n// 100% Beats\nclass Solution {\npublic:\n vector<int> getRow(int rowIndex) {\n std::vector<int> currentRow, previousRow;\n\n for (int i = 0; i <= rowIndex; i++) {\n currentRow.clear();\n for (int j = 0; j <= i; j++) {\n if (j == 0 || j == i) {\n currentRow.push_back(1); // The first and last elements are always 1.\n } else {\n int sum = previousRow[j - 1] + previousRow[j];\n currentRow.push_back(sum);\n }\n }\n\n previousRow = currentRow;\n }\n\n return currentRow;\n }\n};\n```\n``` Python []\n# 50% Beats\nclass Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n currentRow, previousRow = [], []\n\n for i in range(rowIndex + 1):\n currentRow.clear()\n for j in range(i + 1):\n if j == 0 or j == i:\n currentRow.append(1) # The first and last elements are always 1.\n else:\n currentRow.append(previousRow[j - 1] + previousRow[j])\n\n previousRow = currentRow[:]\n\n return currentRow\n```\n``` JavaScript []\n// 95% Beats\nvar getRow = function(rowIndex) {\n let currentRow = [];\n let previousRow = [];\n\n for (let i = 0; i <= rowIndex; i++) {\n currentRow = [];\n for (let j = 0; j <= i; j++) {\n if (j === 0 || j === i) {\n currentRow.push(1); // The first and last elements are always 1.\n } else {\n currentRow.push(previousRow[j - 1] + previousRow[j]);\n }\n }\n\n previousRow = currentRow.slice();\n }\n\n return currentRow;\n};\n```\n``` C# []\n// 80% Beats\npublic class Solution {\n public List<int> GetRow(int rowIndex) {\n List<int> currentRow = new List<int>();\n List<int> previousRow = new List<int>();\n\n for (int i = 0; i <= rowIndex; i++) {\n currentRow.Clear();\n for (int j = 0; j <= i; j++) {\n if (j == 0 || j == i) {\n currentRow.Add(1); // The first and last elements are always 1.\n } else {\n int sum = previousRow[j - 1] + previousRow[j];\n currentRow.Add(sum);\n }\n }\n\n previousRow = new List<int>(currentRow);\n }\n\n return currentRow;\n }\n}\n```\n![vote.jpg]()\n\n---\n## 5. Mathematical Optimization: 100% Beats\uD83D\uDE80\n - Utilize the properties of binomial coefficients to calculate each element in the `k`-th row directly.\n - This approach is mathematically optimized for efficiency.\n#### \uD83D\uDEA9Time complexity: O(k).\n#### \uD83D\uDEA9Space complexity: O(k) for storing the result.\n``` Java []\n// 100% Beats\nclass Solution {\n public List<Integer> getRow(int rowIndex) {\n List<Integer> result = new ArrayList<>();\n\n // Initialize the first element of the row to 1.\n result.add(1);\n\n // Calculate the `k`-th row using binomial coefficient formula.\n for (int i = 1; i <= rowIndex; i++) {\n // Use the previous element to calculate the current element.\n long currentElement = (long) result.get(i - 1) * (rowIndex - i + 1) / i;\n result.add((int) currentElement);\n }\n\n return result;\n }\n}\n```\n``` C++ []\n// 100% Beats\nclass Solution {\npublic:\n std::vector<int> getRow(int rowIndex) {\n std::vector<int> result;\n \n // Initialize the first element of the row to 1.\n result.push_back(1);\n \n // Calculate the `k`-th row using binomial coefficient formula.\n for (int i = 1; i <= rowIndex; i++) {\n // Use the previous element to calculate the current element.\n long long currentElement = static_cast<long long>(result[i - 1]) * (rowIndex - i + 1) / i;\n result.push_back(static_cast<int>(currentElement));\n }\n \n return result;\n }\n};\n```\n``` Python []\n# 55% Beats\nclass Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n result = [1]\n\n for i in range(1, rowIndex + 1):\n # Use the previous element to calculate the current element.\n current_element = result[i - 1] * (rowIndex - i + 1) // i\n result.append(current_element)\n\n return result\n\n```\n``` JavaScript []\n// 95% Beats\nvar getRow = function(rowIndex) {\n let result = [1];\n\n for (let i = 1; i <= rowIndex; i++) {\n // Use the previous element to calculate the current element.\n let currentElement = result[i - 1] * (rowIndex - i + 1) / i;\n result.push(Math.round(currentElement));\n }\n\n return result;\n};\n```\n``` C# []\n// 100% Beats\npublic class Solution {\n public IList<int> GetRow(int rowIndex) {\n List<int> result = new List<int>();\n\n // Initialize the first element of the row to 1.\n result.Add(1);\n\n // Calculate the `k`-th row using binomial coefficient formula.\n for (int i = 1; i <= rowIndex; i++) {\n // Use the previous element to calculate the current element.\n long currentElement = (long)result[i - 1] * (rowIndex - i + 1) / i;\n result.Add((int)currentElement);\n }\n\n return result;\n }\n}\n```\n\n**The most efficient approach is the mathematical optimization method, followed by the combinatorial approach. The naive approach is the least efficient as it generates the entire Pascal\'s triangle up to the `k`-th row. Depending on the constraints and your goals, you can choose the most appropriate approach for solving this problem.**\n\n![upvote.png]()\n# Up Vote Guys\n
11,742
Pascal's Triangle II
pascals-triangle-ii
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
367
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt aims to optimize the generation of the `rowIndex`-th row of Pascal\'s Triangle by using a single array and a middle-out approach. By calculating elements from the center outwards, it reduces the number of calculations and minimizes memory usage.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize a vector `result` of size `rowIndex + 1` and fill it with 1s to represent the first half of the row, which is always symmetrical in Pascal\'s Triangle.\n\n2. Iterate from `1` to `rowIndex / 2` to calculate the elements in the second half of the row. For each element at index `i`, calculate the value based on the previous element (at index `i - 1`) using integer division and the symmetry property of Pascal\'s Triangle.\n\n3. Update the corresponding element in the first half of the row with the calculated value to maintain symmetry.\n\n4. Continue the iteration until the entire row is constructed.\n\n5. Return the `result` vector, which represents the `rowIndex`-th row of Pascal\'s Triangle.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this solution is O(rowIndex), where rowIndex is the input. The loop iterates from `1` to `rowIndex / 2`, and each iteration performs a constant amount of work\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(rowIndex) as we store the `result` vector of size rowIndex + 1 to represent the entire row of Pascal\'s Triangle. The space used for variables and loop control is negligible compared to the size of the result vector.\n# Code\n```\nclass Solution {\npublic:\n vector<int> getRow(int rowIndex) {\n vector<int> result(rowIndex + 1, 1);\n \n for (int i = 1; i <= rowIndex / 2; i++) {\n result[i] = (long long)result[i - 1] * (rowIndex - i + 1) / i;\n result[rowIndex - i] = result[i];\n }\n \n return result;\n }\n};\n\n```\n\n\n# \uD83D\uDCA1If you come this far, then i would like to request you to please upvote this solution so that it could reach out to another one \u2763\uFE0F\uD83D\uDCA1
11,749
Pascal's Triangle II
pascals-triangle-ii
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
534
5
# Explanation\nLet\'s break down the given code step by step.\n\n```python\ndef getRow(self, rowIndex: int) -> List[int]:\n res = [[1]]\n```\n- This function is defined as a method within a class, as it has `self` as its first parameter. It takes an integer `rowIndex` as input and is expected to return a list of integers.\n- `res` is initialized as a list containing a single list with the value `[1]`. This list represents the first row of Pascal\'s Triangle.\n\n```python\n for i in range(rowIndex):\n temp = [0] + res[-1] + [0]\n row = []\n```\n- A loop is set up to iterate from 0 to `rowIndex - 1`. This loop is used to calculate the subsequent rows of Pascal\'s Triangle.\n- `temp` is initialized as a new list, which is formed by adding `0` at the beginning and end of the last row in `res`. This is done to create a buffer of zeros around the row to calculate the next row.\n- `row` is initialized as an empty list. This list will store the values of the current row being calculated.\n\n```python\n for j in range(len(res[-1])+1):\n row.append(temp[j] + temp[j+1])\n```\n- Another nested loop is set up to iterate over the elements of `temp` and calculate the values of the current row.\n- For each element at index `j` in `temp`, it adds the value at index `j` and the value at index `j+1` and appends the result to the `row` list.\n\n```python\n res.append(row)\n```\n- After calculating all the values for the current row, the `row` list is appended to the `res` list. This adds a new row to the list, representing the current row of Pascal\'s Triangle.\n\n```python\n return res[-1]\n```\n- After the loop completes (i.e., all rows up to `rowIndex` have been calculated and added to `res`), the function returns the last row of `res`, which corresponds to the row at index `rowIndex` in Pascal\'s Triangle.\n\nIn summary, this code calculates and returns the `rowIndex`-th row of Pascal\'s Triangle using a list-based approach, where each row is calculated based on the previous row. It builds up the rows one by one, starting with the first row as `[1]` and using the values from the previous row to calculate the next row.\n\n# Python Code\n```\nclass Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n res = [[1]]\n \n for i in range(rowIndex):\n temp = [0] + res[-1] + [0]\n row = []\n\n for j in range(len(res[-1])+1):\n row.append(temp[j] + temp[j+1])\n res.append(row)\n\n return res[-1]\n```\n**Please upvote if you like the solution & feel free to give your opinion. \nHappy Coding! \uD83D\uDE0A**
11,755
Pascal's Triangle II
pascals-triangle-ii
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
358
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt is an optimized approach to generate the `rowIndex`-th row of Pascal\'s Triangle. It utilizes a single array to store the values of each element in the row while minimizing calculations and avoiding overflow by using `long long` data types.\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a vector named `result` of size `rowIndex + 1` and initialize all elements to 1, as the first and last elements of each row in Pascal\'s Triangle are always 1.\n\n2. Initialize a variable `val` to 1, which will be used to compute the next element in the row.\n\n3. Loop from `i = 1` to `i = rowIndex`. In each iteration:\n\n- Update `val` by multiplying it with `(rowIndex - i + 1) / i`. This step calculates the next element in the row efficiently, taking advantage of the fact that each element is obtained by multiplying the previous element by `(rowIndex - i + 1)` and dividing by `i`.\n\n- Set `result[i]` to the computed `val`. This stores the element in the row.\n\n4. After the loop, the `result` vector contains the `rowIndex-th` row of Pascal\'s Triangle.\n\n---\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this solution is O(rowIndex) because it iterates through the row once, performing constant-time operations for each element.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(rowIndex) because we are using a single vector of size `rowIndex + 1` to store the row\'s elements. The space required is proportional to the size of the row you want to generate.\n\n---\n\n\n# \uD83D\uDCA1If you come this far, then i would like to request you to please upvote this solution so that it could reach out to another one \u2763\uFE0F\uD83D\uDCA1\n\n\n---\n\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> getRow(int rowIndex) {\n vector<int> result(rowIndex + 1, 1);\n long long val = 1;\n \n for (int i = 1; i <= rowIndex; i++) {\n val = val * (rowIndex - i + 1) / i;\n result[i] = val;\n }\n \n return result;\n }\n};\n\n```
11,767
Pascal's Triangle II
pascals-triangle-ii
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
19,189
152
This solution here, is **Linear** in time.\n\n---\nAs you know you can get any element of Pascal\'s Triangle in **O(N)** time and constant space complexity. \nfor first row first column we have **1C1**\nfor second row first column we have **2C1**\nfor second row second column we have **2C2**\n..... and so on\nTherefore we can infer, for ith row and jth column we have the number **iCj**\n\nAnd calculating this is pretty easy just in ***N*** time (factorial basically).\n\n==> `nCr = n*(n-1)*(n-2)...(r terms) / 1*2*..........*(r-2)*(r-1)*r`\n\nNow the question asks us to find the complete row.\nIf we calculate all the elements in this manner it would be quadratic in time. But, since its formula is pretty sleek, we proceed as follows:\n\nsuppose we have **nCr** and we have to find **nC(r+1)**, like **5C3** and **5C4**\n==> `5C3 = 5*4*3 / 1*2*3`\n\nto get the next term we multiply numerator with its next term and denominator with its next term. As, \n==> `5C4 = 5*4*3 * 2 / 1*2*3 * 4`\n\nWe are following this simple maths logic to get the complete row in **O(N)** time.\n\n**Note:-** We didnt actually need the variable temp. But the test cases are such that multiplying in one case exceeds the **int range**, and since we cannot change return type we have to take the **long** data type variable as temporary.\n\n---\n**Python Code:**\nThe result for this code is **8 ms / 13.3 MB** (beats 99.82% / 88.54%): \n```\nclass Solution(object):\n def getRow(self, r):\n ans = [1]*(r+1);\n up = r\n down = 1\n for i in range(1, r):\n ans[i] = ans[i-1]*up/down;\n up = up - 1\n down = down + 1\n return ans;\n```\n\n---\n**Java Code:**\nThe result for this code is **0 ms / 36.3 MB** (beats 100% / 91.45%): \n```\nclass Solution {\n public List<Integer> getRow(int r) {\n List<Integer> ans = new ArrayList<>();\n ans.add(1);\n long temp = 1;\n for(int i=1,up=r,down=1;i<=r;i++,up--, down++){\n temp=temp*up/down;\n ans.add((int)temp);\n }\n return ans;\n }\n}\n```\n\n---\n**JavaScript Code:**\nThe result for this code is **72 ms / 38.7 MB** (beats 90.29% / 40.05%): \n```\nvar getRow = function(r) {\n var ans = new Array(r+1)\n ans[0]=ans[r]=1\n for(i=1,up=r;i<r;i++,up--)\n ans[i] = ans[i-1]*up/i\n return ans\n};\n```\n\n---\n**C++ Code:**\nThe result for this code is **0 ms / 6.2 MB** (beats 100% / 84.20%): \n```\nclass Solution {\npublic:\n vector<int> getRow(int r) {\n vector<int>v(r+1);\n long temp=1;\n v[0]=v[r]=1;\n for(int i=1,up=r,down=1;i<r;i++,up--,down++){\n temp = temp*up/down;\n v[i]=temp;\n }\n return v;\n }\n};\n```\n\n---\n**C Code:**\nThe result for this code is **0 ms / 5.6 MB** (beats 100% / 85.96%): \n```\nint* getRow(int r, int* rS){\n int*ans = calloc(r + 1, sizeof(int));\n long temp=1;\n ans[0]=1;\n for(int i=1,up=r;i<=r;i++,up--){\n temp=temp*up/i;\n ans[i]=temp;\n }\n *rS = r+1;\n return ans;\n}\n```\n\n---\n\n**C# Code:**\nThe result for this code is **188 ms / 26.2 MB** (beats 99.37% / 69.62%): \n```\npublic class Solution {\n public IList<int> GetRow(int r) {\n var ans = new int[r+1];\n ans[0]=ans[r]=1;\n long temp=1;\n for(int i=1,up=r;i<r;i++,up--){\n temp = temp * up / i;\n ans[i]=(int)temp;\n }\n return ans;\n }\n}\n```\n\n---\n\n**Ruby Code:**\nThe result for this code is **48 ms / 209.8 MB** (beats 80.65% / 35.48%): \n```\ndef get_row(r)\n return [1] if r==0\n ans = [1]\n temp = 1\n for i in 1...r do\n temp = temp * (r-i+1)/i\n ans << temp\n end\n ans << 1\n return ans\nend\n```\n\n---\n\n**Switft Code:**\nThe result for this code is **0 ms / 14 MB** (beats 100.00% / 68.04%)\n```\nclass Solution {\n func getRow(_ r: Int) -> [Int] {\n if r==0 {\n return [1]\n }\n var ans = [Int](repeating: 1, count: r+1)\n for i in 1...r {\n ans[i] = ans[i-1]*(r-i+1)/i\n }\n return ans\n }\n}\n```\n\n---\n\n**Go Code:**\nThe result for this code is **0 ms / 2 MB** (beats 100.00% / 100.00%)\n```\nfunc getRow(r int) []int {\n var ans = make([]int,r+1)\n ans[0] = 1\n ans[r] = 1\n for i:=1; i<=r; i++ {\n ans[i] = ans[i-1]*(r-i+1)/i\n }\n return ans\n}\n```\n\n---\n\n**Scala Code:**\nThe result for this code is **388 ms / 49.4 MB** (beats 100.00% / 95.00%)\n**Note:** `implicit def` function is used to implicitly convert array to List\n```\nobject Solution {\n implicit def arrayToList[A](a: Array[A]) = a.toList\n def getRow(r: Int): List[Int] = {\n var ans = new Array[Int](r+1)\n ans(0) = 1\n var temp: Long = 1\n for( i <- 1 to r){\n temp = temp*(r-i+1)/i\n ans(i) = temp.asInstanceOf[Int]\n }\n return ans\n }\n}\n```\n\n---\n\n**Kotlin Code:**\nThe result for this code is **132 ms / 33.1 MB** (beats 91.67% / 98.81%)\n```\nclass Solution {\n fun getRow(r: Int): List<Int> {\n var ans = MutableList<Int>(r+1){1}\n var temp: Long = 1\n for (i in 1..r){\n temp = temp*(r-i+1)/i\n ans[i] = temp.toInt()\n }\n return ans\n }\n}\n```\n\n---\n\n**Rust Code:**\nThe result for this code is **0 ms /1.9 MB** (beats 100.00% / 92.31%)\n```\nimpl Solution {\n pub fn get_row(r: i32) -> Vec<i32> {\n let mut ans : Vec<i32> = Vec::new(); \n ans.push(1);\n let mut temp: i64 = 1;\n let mut up = r as i64;\n let mut down = 1 as i64;\n for i in 1..=r {\n temp = temp*up/down;\n ans.push(temp as i32);\n up-=1;\n down+=1;\n }\n return ans;\n }\n}\n```\n\n---\n\n**PHP Code:**\nThe result for this code is **0 ms /15.7 MB** (beats 100.00% / 48.15%)\n```\nclass Solution {\n function getRow($r) {\n $ans = array(1);\n $temp = 1;\n for($i=1;$i<=$r;$i++){\n $temp = $temp*($r-$i+1)/$i;\n array_push($ans, $temp);\n }\n return $ans;\n }\n}\n```\n\n---\n\n**TypeScript Code:**\nThe result for this code is **80 ms /39.2 MB** (beats 74.58% / 72.88%)\n```\nfunction getRow(r: number): number[] {\n var ans:number[] = [1]\n var temp:number = 1\n for(var i:number=1;i<=r;i++){\n temp = temp*(r-i+1)/i\n ans.push(temp)\n }\n return ans\n};\n```
11,772
Pascal's Triangle II
pascals-triangle-ii
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
4,225
16
# Intuition:\nThis solution is based on Pascal\'s Triangle, where each element in a row is the sum of the two elements directly above it. By initializing the row with 1s and then calculating each element based on the previous row, we can generate the desired row efficiently.\n\n# Approach:\n1. Initialize a vector called row with rowIndex+1 elements, all of which are set to 1. This is the first row in Pascal\'s Triangle.\n2. Iterate through each row of Pascal\'s Triangle up to and including the desired rowIndex. For each row:\n a. Starting from the second last element of the row, iterate backwards to the second element, and update each element as the sum of the two elements directly above it.\n3. Return the final row.\n\n# Complexity:\n- Time Complexity: O(rowIndex^2)\n - The outer loop runs rowIndex times, and the inner loop runs i-1 times for each i, resulting in a total of 1+2+3+...+rowIndex = rowIndex*(rowIndex+1)/2 iterations. Since this is O(rowIndex^2), the time complexity of the algorithm is O(rowIndex^2).\n\n- Space Complexity: O(rowIndex)\n - The space complexity of the algorithm is O(rowIndex) since we only store a single row of Pascal\'s Triangle at a time.\n\n---\n# C++\n```cpp\nclass Solution {\npublic:\n vector<int> getRow(int rowIndex) {\n // Initialize the row with 1s\n vector<int> row(rowIndex + 1, 1); \n // Calculate each element of the row based on the previous row\n for (int i = 0; i <= rowIndex; ++i) {\n for (int j = i - 1; j > 0; --j) {\n row[j] = row[j] + row[j - 1];\n }\n }\n return row;\n }\n};\n```\n\n---\n\n# Java\n```java\nclass Solution {\n public List<Integer> getRow(int rowIndex) {\n // Initialize the row with 1s\n List<Integer> row = new ArrayList<>(rowIndex + 1); \n // Calculate each element of the row based on the previous row\n for (int i = 0; i <= rowIndex; ++i) {\n row.add(1);\n for (int j = i - 1; j > 0; --j) {\n row.set(j, row.get(j) + row.get(j - 1));\n }\n }\n return row;\n }\n}\n```\n---\n\n# Python\n```py\nclass Solution(object):\n def getRow(self, rowIndex):\n # Initialize the row with 1s\n row = [1] * (rowIndex + 1) \n # Calculate each element of the row based on the previous row\n for i in range(rowIndex + 1):\n for j in range(i - 1, 0, -1):\n row[j] = row[j] + row[j - 1]\n return row\n\n```\n---\n\n# JavaScript\n```js\nvar getRow = function(rowIndex) {\n // Initialize the row with 1s\n var row = new Array(rowIndex + 1).fill(1); \n // Calculate each element of the row based on the previous row\n for (var i = 0; i <= rowIndex; ++i) {\n for (var j = i - 1; j > 0; --j) {\n row[j] = row[j] + row[j - 1];\n }\n }\n return row;\n};\n\n```
11,783
Pascal's Triangle II
pascals-triangle-ii
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Array,Dynamic Programming
Easy
null
1,014
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n res=[[1]]\n for i in range(rowIndex):\n temp=[0]+res[-1]+[0]\n row=[]\n for j in range(len(res[-1])+1):\n row.append(temp[j]+temp[j+1])\n res.append(row)\n return res[-1]\n```\n# plz consider upvoting\n![4m44lc.jpg]()\n\n
11,793
Triangle
triangle
Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
Array,Dynamic Programming
Medium
null
16,289
255
Given a triangle array, we need to return the path whose sum from top to bottom is minimum.\nThere is one constraint: we can only move to lower-left or lower-right elements.\nFor example, in the triangle depicted below, the only valid path from `5` are `5 -> 1` and `5 -> 8`. The paths `5 -> 4` or `5 -> 3` are invalid.\n\n```text\n 2\n 3 4\n 6 5 7\n4 1 8 3\n```\n\nNow the question is, can we solve it greedily, i.e., simply check the immediate step and choose the smaller element?\nThe answer is no. Because the current choice will affect the later decisions. This is illustrated in the following example:\n\n```text\n 2\n 4 5\n 6 5 1\n4 1 8 2\n```\n\nThe greedy strategy will use the path `2 -> 4 -> 5 -> 1`. But, the optimal path is `2 -> 5 -> 1 -> 2`.\nWe need to use `Dynamic Programming` to solve this problem. Solving a problem using DP is generally tricky. This post will help you understand how to develop a DP approach. So, I highly recommend reading all three methods.\n\n___\n___\n\u274C **Solution I: Recursion [TLE]**\n\nWe can try all valid paths and calculate the sum. Out of all those, return the minimum sum. At each step, we have two choices:\n\n1. Move to lower-left element (`i + 1` and `j`)\n2. Move to lower-right element (`i + 1` and `j + 1`)\n\n<iframe src="" frameBorder="0" width="1080" height="280"></iframe>\n\nWhy have I named the inside function as `dfs`? Because if we trace our actions, we can observe that it forms a binary tree. **Don\'t worry** if you are not familiar with this term. The following visualization will help you to understand what I mean.\n\n```text\n \u250F\u2501\u2501\u2501\u2513\n \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2528 2 \u2520\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E\n \u2502 \u2517\u2501\u2501\u2501\u251B \u2502\n \u250F\u2501\u2537\u2501\u2513 \u250F\u2501\u2537\u2501\u2513 \n \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2528 3 \u2520\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2528 4 \u2520\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E \n \u2502 \u2517\u2501\u2501\u2501\u251B \u2502 \u2502 \u2517\u2501\u2501\u2501\u251B \u2502 \n \u250F\u2501\u2537\u2501\u2513 \u250F\u2501\u2537\u2501\u2513 \u250F\u2501\u2537\u2501\u2513 \u250F\u2501\u2537\u2501\u2513 \n \u256D\u2500\u2500\u2500\u2500\u2500\u2528 6 \u2520\u2500\u2500\u2500\u2500\u2500\u256E \u256D\u2500\u2500\u2500\u2500\u2500\u2528 5 \u2520\u2500\u2500\u2500\u2500\u2500\u256E \u256D\u2500\u2500\u2500\u2500\u2500\u2528 5 \u2520\u2500\u2500\u2500\u2500\u2500\u256E \u256D\u2500\u2500\u2500\u2500\u2500\u2528 7 \u2520\u2500\u2500\u2500\u2500\u2500\u256E \n \u2502 \u2517\u2501\u2501\u2501\u251B \u2502 \u2502 \u2517\u2501\u2501\u2501\u251B \u2502 \u2502 \u2517\u2501\u2501\u2501\u251B \u2502 \u2502 \u2517\u2501\u2501\u2501\u251B \u2502 \n \u250F\u2501\u2537\u2501\u2513 \u250F\u2501\u2537\u2501\u2513 \u250F\u2501\u2537\u2501\u2513 \u250F\u2501\u2537\u2501\u2513 \u250F\u2501\u2537\u2501\u2513 \u250F\u2501\u2537\u2501\u2513 \u250F\u2501\u2537\u2501\u2513 \u250F\u2501\u2537\u2501\u2513 \n \u2503 4 \u2503 \u2503 1 \u2503 \u2503 1 \u2503 \u2503 8 \u2503 \u2503 1 \u2503 \u2503 8 \u2503 \u2503 8 \u2503 \u2503 3 \u2503\n \u2517\u2501\u2501\u2501\u251B \u2517\u2501\u2501\u2501\u251B \u2517\u2501\u2501\u2501\u251B \u2517\u2501\u2501\u2501\u251B \u2517\u2501\u2501\u2501\u251B \u2517\u2501\u2501\u2501\u251B \u2517\u2501\u2501\u2501\u251B \u2517\u2501\u2501\u2501\u251B\n```\n\nIn dfs, we traverse all the paths one by one. So, here our paths will be:\n\n1. 2 -> 3 -> 6 -> 4\n2. 2 -> 3 -> 6 -> 1\n3. 2 -> 3 -> 5 -> 1\n.\n.\n.\n\n- **Time Complexity:** `O(2\u207F)`\n- **Space Complexity:** `O(n)`\n\n___\n\u2705 **Solution II: Top-Down DP or Memoization [Accepted]**\n\nWe are doing a lot of repetitive work in the above recursive solution. How?\nHave a look at the above example. The subtree with head 5 is repeated twice. We need to compute the minimum sum path during the first time `(2 -> 3 -> 5 -> ...)`. During the second time from `2 -> 4 -> 5`, we can simply use the result from the first time instead of traversing again. This is the essence of memoization.\n\n```text\n \u250F\u2501\u2501\u2501\u2513\n \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2528 2 \u2520\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E\n \u2502 \u2517\u2501\u2501\u2501\u251B \u2502\n \u250F\u2501\u2537\u2501\u2513 \u250F\u2501\u2537\u2501\u2513 \n \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2528 3 \u2520\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2528 4 \u2520\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E \n \u2502 \u2517\u2501\u2501\u2501\u251B \u2502 \u2502 \u2517\u2501\u2501\u2501\u251B \u2502 \n \u250F\u2501\u2537\u2501\u2513 .........\u250F\u2501\u2537\u2501\u2513......... .........\u250F\u2501\u2537\u2501\u2513 ........ \u250F\u2501\u2537\u2501\u2513 \n \u256D\u2500\u2500\u2500\u2500\u2500\u2528 6 \u2520\u2500\u2500\u2500\u2500\u2500\u256E . \u256D\u2500\u2500\u2500\u2500\u2500\u2528 5 \u2520\u2500\u2500\u2500\u2500\u2500\u256E . . \u256D\u2500\u2500\u2500\u2500\u2500\u2528 5 \u2520\u2500\u2500\u2500\u2500\u2500\u256E . \u256D\u2500\u2500\u2500\u2500\u2500\u2528 7 \u2520\u2500\u2500\u2500\u2500\u2500\u256E \n \u2502 \u2517\u2501\u2501\u2501\u251B \u2502 . \u2502 \u2517\u2501\u2501\u2501\u251B \u2502 . . \u2502 \u2517\u2501\u2501\u2501\u251B \u2502 . \u2502 \u2517\u2501\u2501\u2501\u251B \u2502 \n \u250F\u2501\u2537\u2501\u2513 \u250F\u2501\u2537\u2501\u2513 .\u250F\u2501\u2537\u2501\u2513 \u250F\u2501\u2537\u2501\u2513. .\u250F\u2501\u2537\u2501\u2513 \u250F\u2501\u2537\u2501\u2513. \u250F\u2501\u2537\u2501\u2513 \u250F\u2501\u2537\u2501\u2513 \n \u2503 4 \u2503 \u2503 1 \u2503 .\u2503 1 \u2503 \u2503 8 \u2503. .\u2503 1 \u2503 \u2503 8 \u2503. \u2503 8 \u2503 \u2503 3 \u2503\n \u2517\u2501\u2501\u2501\u251B \u2517\u2501\u2501\u2501\u251B .\u2517\u2501\u2501\u2501\u251B \u2517\u2501\u2501\u2501\u251B. .\u2517\u2501\u2501\u2501\u251B \u2517\u2501\u2501\u2501\u251B. \u2517\u2501\u2501\u2501\u251B \u2517\u2501\u2501\u2501\u251B\n ....................... ....................... \n```\n\nIn Python, it is as simple as adding the `@cache` decorator. But, this won\'t be accepted in the interviews and have many limitations.\n\n```python\nclass Solution:\n def minimumTotal(self, triangle: List[List[int]]) -> int:\n @cache\n def dfs(i, j):\n if i == len(triangle):\n return 0\n\n lower_left = triangle[i][j] + dfs(i + 1, j)\n lower_right = triangle[i][j] + dfs(i + 1, j + 1)\n\n return min(lower_left, lower_right)\n\n return dfs(0, 0)\n```\n\nWe can manually use a way to store the information and use it later. Here, two variables (`i` and `j`) are changing and can be used to store a state. So, we can use a matrix. The following code will make it clear.\n\n<iframe src="" frameBorder="0" width="1080" height="360"></iframe>\n\n- **Time Complexity:** `O(n\xB2)`\n- **Space Complexity:** `O(n\xB2)`\n\n___\n\u2705 **Solution III (a): Bottom Up DP or Tabulation [Accepted]**\n\nRecursion is slower than the iterative approach. So, we can further optimize the above solution by using bottom-up DP.\nWe can do a bottom-up traversal instead of traversing from top to bottom. Coming up with a bottom-up DP is challenging at first and requires practice. Instead of looking at the bigger problem, we look at smaller sub-problems and try to build up the solution. The following example will help you to understand:\n\n```text\n1. Suppose that only the last level is given. \n\n4 1 8 3\n\nThen what should be your answer?\n\nIf you thought 1, then congratulations \uD83C\uDF89 you are correct. This is our first subproblem. \n\n2. Now, the last two levels are given.\n\n 6 5 7\n4 1 8 3\n\nHere, what should be the answer and what information do you need to store?\n\nClearly, the answer is 6 (5 -> 1). But, this may not be the optimal path. So, we need to store all the optimal paths, i.e.,\n[(6 -> 1), (5 -> 1), 7 -> 3)] or [7, 6, 10]. This is our second subproblem.\n\n3. Last 3 levels are given.\n\n 3 4\n 6 5 7\n4 1 8 3\n\nAgain, what should be the answer and what information do you need to store (or use)?\n\nAnswer is 9 (3 -> 5 -> 1). Do we need to look again at all the paths? Can we use the information that we previously stored?\nNo and Yes.\nIf we replace the triangle as\n 3 4\n 7 6 10\nthen also, we\'ll get the same answer. And we can store this information as [(3 -> 6), (4 -> 6)] or [9, 10].\n\n4. All levels are given\n\n 2\n 3 4\n 6 5 7\n4 1 8 3\n\nWhich can be replaced as:\n 2\n 9 10\n\nAnd hence, our answer is 11 (2 -> 9)\n\n```\n\n<iframe src="" frameBorder="0" width="1080" height="330"></iframe>\n\n- **Time Complexity:** `O(n\xB2)`\n- **Space Complexity:** `O(n\xB2)`\n\n___\n\u2705 **Solution III (b): Bottom Up DP or Tabulation (Space Optimized) [Accepted]**\n\nNotice that we only require the information about the next row. So, instead of creating a `2D` matrix, a `1D` array is sufficient.\n\n<iframe src="" frameBorder="0" width="1080" height="350"></iframe>\n\n- **Time Complexity:** `O(n\xB2)`\n- **Space Complexity:** `O(n)`\n\n___\n___\nIf you like the solution, please **upvote**! \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F\n
11,808
Triangle
triangle
Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
Array,Dynamic Programming
Medium
null
6,788
89
We are given a triangle. We start at the top of the triangle and want to move to the bottom with minimum possible sum. We can either move down to the same index *`i`* or to the index *`i + 1`*.\n\n----\n\n\u2714\uFE0F ***Solution - I (In-Place Bottom-Up Dynamic Programming)***\n\nWe can easily see that directly just choosing the minimum value in the next row(amongst `triangle[nextRow][i]` and `triangle[nextRow][i+1]`) won\'t fetch us the optimal final result since it maybe the case that the latter values of previous chosen path turn out to be huge. \n\nWe need to observe that to get the minimum possible sum, **we must use a path that has Optimal Value for each intermediate stop in the path**. Thus, we can use **Dynamic Programming** to find the optimal value to reach each position of the triangle level by level. We can do this by accumulating the sum of path(or more specifically sum of values of optimal stops in a path) for each cell of a level from top to the bottom of triangle.\n\n We are given that, at each cell in the triangle, we can move to the next row using two choices - \n \n 1. Move to the same index `i`.\n 2. Move to the next index `i + 1`\n\nSince we are following **a bottom-up approach, the above can also be interpreted as** :- \n\nFor cell in the triangle, we could have reached here either from the previous row/level either from -\n\n1. the same index `i`, or\n2. the index `i - 1`\n\nSo, obviously the optimal choice to arrive at the current position in triangle would be to come from the cell having minimum value of these two choices. \n\nWe will keep adding the result from the lower level to the next/higher level by each time choosing the optimal cell to arrive at the current cell. Finally, we can return the minimum value that we get at the bottom-most row of the triangle. Here, no auxillary space is used and I have modified the *`triangle`* itself to achieve a space complexity of `O(1)`.\n\n**C++**\n```\nint minimumTotal(vector<vector<int>>& triangle) {\n\t// start from level 1 till the bottom-most level. Each time determine the best path to arrive at current cell\n\tfor(int level = 1; level < size(triangle); level++) \n\t\tfor(int i = 0; i <= level; i++) // triangle[level].size() == level + 1 (level starts from 0)\n\t\t\t// for the current level: \n\t\t\ttriangle[level][i] += min(triangle[level - 1][min(i, (int)size(triangle[level - 1]) - 1)], // we can either come from previous level and same index\n\t\t\t triangle[level - 1][max(i - 1, 0)]); // or the previous level and index-1\n\t// finally return the last element of the bottom level\n\treturn *min_element(begin(triangle.back()), end(triangle.back())); \n}\n```\n\n---\n\n**Python**\n```\ndef minimumTotal(self, triangle: List[List[int]]) -> int:\n for level in range(1, len(triangle)):\n for i in range(level+1):\n triangle[level][i] += min(triangle[level-1][min(i, level-1)], triangle[level-1][max(i-1,0)])\n return min(triangle[-1])\n```\n\n***Time Complexity :*** **`O(N^2)`**, where `N` are the total number of levels in *`triangle`*.\n***Space Complexity :*** **`O(1)`**\n\nThe `min` and `max` in the above code are used to do bound-checks.\n\n---\n\n\u2714\uFE0F ***Solution - II (In-Place Top-Down Dynamic Programming)***\n\n\nWe chose to go from **top-level to the bottom-level of triangle in the previous approach**. We can also choose to start from the bottom of triangle and move all the way to the top. We will again follow the same DP strategy as used in the above solution.\n\nAt each cell of the triangle, we could have moved here from the below level in 2 ways, either from -\n\n1. the same index `i` in below row, or\n2. the index `i+1`.\n\nAnd again, we will choose the minimum of these two to arrive at the optimal solution. Finally at last, we will reach at `triangle[0][0]`, which will hold the optimal (minimum) sum of path.\n\nActually, this approach will make the code a lot more clean and concise by avoiding the need of bound checks.\n\n**C++**\n```\nint minimumTotal(vector<vector<int>>& triangle) {\n\tfor(int level = size(triangle) - 2; level >= 0; level--) // start from bottom-1 level\n\t\tfor(int i = 0; i <= level; i++)\n\t\t\t // for every cell: we could have moved here from same index or index+1 of next level\n\t\t\ttriangle[level][i] += min(triangle[level + 1][i], triangle[level + 1][i + 1]);\n\treturn triangle[0][0]; // lastly t[0][0] will contain accumulated sum of minimum path\n}\n```\n\n---\n\n**Python**\n```\ndef minimumTotal(self, triangle: List[List[int]]) -> int:\n for level in range(len(triangle)-2,-1,-1):\n for i in range(level+1):\n triangle[level][i] += min(triangle[level+1][i], triangle[level+1][i+1])\n return triangle[0][0]\n```\n\n***Time Complexity :*** **`O(N^2)`**\n***Space Complexity :*** **`O(1)`**\n\n\n---\n\n***Solution - III (Bottom-Up Dynamic Programming w/ Auxillary Space)***\n\nMore often than not, you would not be allowed to modify the given input. In such a situation, we can obviously opt for making a copy of the given input(*`triangle`* in this case). This would lead to a space complexity of **`O(N^2)`**. I won\'t show this solution since the only change needed in above solutions would be adding the line `vector<vector<int>>dp(triangle);` and replacing `triangle` with `dp` (Or better yet just pass triangle by value instead of reference & keep using that itself \uD83E\uDD37\u200D\u2642\uFE0F).\n\nHere, I will present a **solution with linear space complexity without input modification**. We can observe in the above solutions that we really ever **access only two rows of the input at the same time**. So, we can just maintain two rows and alternate between those two in our loop.\n\nI have used `level & 1` in the below solution to alternate between these two rows of *`dp`*. It\'s very common way to go when we are converting from 2d DP to linear space. If you are not comfortable with it, you can also choose to maintain two separate rows and swap them at end of each iteration.\n\nAll the other things and idea remains the same as in the *`solution - I`*\n\n**C++**\n```\nint minimumTotal(vector<vector<int>>& triangle) {\n\tint n = size(triangle), level = 1;\n\tvector<vector<int> > dp(2, vector<int>(n, INT_MAX));\n\tdp[0][0]=triangle[0][0]; // assign top-most row to dp[0] as we will be starting from level 1\n\tfor(; level < n; level++) \n\t\tfor(int i = 0; i <= level; i++)\n\t\t\tdp[level & 1][i] = triangle[level][i] + min(dp[(level - 1) & 1][min(i, n - 1)], dp[(level - 1) & 1][max(i - 1, 0)]); \n\tlevel--; // level becomes n after for loop ends. We need minimum value from level - 1\n\treturn *min_element(begin(dp[level & 1]), end(dp[level & 1])); \n}\n```\n\n---\n\n**Python**\n\nThe below solution is using the two separate rows method that I described above and swapping after each iteration to alternate between them -\n```\ndef minimumTotal(self, triangle: List[List[int]]) -> int:\n\tn = len(triangle)\n\tcur_row, prev_row = [0]*n, [0]*n\n\tprev_row[0] = triangle[0][0] \n\tfor level in range(1, n):\n\t\tfor i in range(level+1):\n\t\t\tcur_row[i] = triangle[level][i] + min(prev_row[min(i, level-1)], prev_row[max(i-1,0)])\n\t\tcur_row, prev_row = prev_row, cur_row\n\treturn min(prev_row)\n```\n\n***Time Complexity :*** **`O(N^2)`**\n***Space Complexity :*** **`O(N)`**\n\n---\n\n***Solution - IV (Top-Down Dynamic Programming w/ Auxillary Space)***\n\nHere is the Top-Down version of *`Solution - II`*, without input array modification and using linear auxillary space.\n\n**C++**\n```\nint minimumTotal(vector<vector<int>>& triangle) {\n\tint n = size(triangle), level = n - 1;\n\tvector<vector<int> > dp(2, vector<int>(n, 0));\n\tdp[level-- & 1] = triangle[n - 1];\n\tfor(; level >= 0; level--)\n\t\tfor(int i = 0; i <= level; i++)\n\t\t\tdp[level & 1][i] = triangle[level][i] + min(dp[(level + 1) & 1][i], dp[(level + 1) & 1][i + 1]);\n\treturn dp[0][0];\n}\n```\n\n---\n\n**Python**\n\nAgain, I have used to two separate rows method here -\n```\ndef minimumTotal(self, triangle: List[List[int]]) -> int:\n n = len(triangle)\n cur_row, next_row = [0]*n, triangle[n-1] \n for level in range(n-2,-1,-1):\n for i in range(level+1):\n cur_row[i] = triangle[level][i] + min(next_row[i], next_row[i+1])\n cur_row, next_row = next_row, cur_row\n return next_row[0]\n```\n\n***Time Complexity :*** **`O(N^2)`**\n***Space Complexity :*** **`O(N)`**\n\n---\n\n*Best Runtime -*\n\n<table><tr><td><img src= /></td></tr></table>\n\n\n\n---\n---\n\n\uD83D\uDCBB\uD83D\uDC31\u200D\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, please do comment below \uD83D\uDC47 \n\n---\n---
11,843
Triangle
triangle
Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
Array,Dynamic Programming
Medium
null
30,254
190
\n # O(n*n/2) space, top-down \n def minimumTotal1(self, triangle):\n if not triangle:\n return \n res = [[0 for i in xrange(len(row))] for row in triangle]\n res[0][0] = triangle[0][0]\n for i in xrange(1, len(triangle)):\n for j in xrange(len(triangle[i])):\n if j == 0:\n res[i][j] = res[i-1][j] + triangle[i][j]\n elif j == len(triangle[i])-1:\n res[i][j] = res[i-1][j-1] + triangle[i][j]\n else:\n res[i][j] = min(res[i-1][j-1], res[i-1][j]) + triangle[i][j]\n return min(res[-1])\n \n # Modify the original triangle, top-down\n def minimumTotal2(self, triangle):\n if not triangle:\n return \n for i in xrange(1, len(triangle)):\n for j in xrange(len(triangle[i])):\n if j == 0:\n triangle[i][j] += triangle[i-1][j]\n elif j == len(triangle[i])-1:\n triangle[i][j] += triangle[i-1][j-1]\n else:\n triangle[i][j] += min(triangle[i-1][j-1], triangle[i-1][j])\n return min(triangle[-1])\n \n # Modify the original triangle, bottom-up\n def minimumTotal3(self, triangle):\n if not triangle:\n return \n for i in xrange(len(triangle)-2, -1, -1):\n for j in xrange(len(triangle[i])):\n triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1])\n return triangle[0][0]\n \n # bottom-up, O(n) space\n def minimumTotal(self, triangle):\n if not triangle:\n return \n res = triangle[-1]\n for i in xrange(len(triangle)-2, -1, -1):\n for j in xrange(len(triangle[i])):\n res[j] = min(res[j], res[j+1]) + triangle[i][j]\n return res[0]
11,866
Triangle
triangle
Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
Array,Dynamic Programming
Medium
null
3,464
26
### Intuition\n\nWe can use the ```triangle``` array to perform our DP. This allows us to use O(1) auxiliary space. Why?\n\n- For any given coordinate in the triangle ```(x, y)``` where ```0 <= x < len(triangle)``` and ```0 <= y < len(triangle[x])```, the minimum path sum of the path that ends up on ```(x, y)``` is given by **```triangle[x][y]``` plus the minimum path sum of the previous coordinate**.\n- Once we compute the minimum path sum at ```(x, y)```, we **no longer require the standalone value for ```(x, y)``` to perform any calculation**. Instead, per above, we will use the minimum sum.\n\nWhich coordinates are considered "previous" to any given coordinate ```(x, y)```? Since from any ```(x, y)``` in the ```triangle``` we can move to ```(x+1, y)``` or ```(x+1, y+1)```, we can use this information in reverse: **For any given coordinate ```(x, y)```, its "previous" coordinates are either ```(x-1, y-1)``` or ```(x-1, y)```**.\n\n---\n\n### Approach 1: Top-Down Approach\n\nFrom the discussion above, we can implement a top-down DP using the following pseudocode:\n\n- For each row in the ```triangle```, calculate the minimum sum at each element.\n- After all computation is complete, return the minimum sum from the last row (i.e. ```min(triangle[-1])```).\n\n```python\nclass Solution:\n def minimumTotal(self, triangle: List[List[int]]) -> int:\n for i in range(1, len(triangle)): # for each row in triangle (skipping the first),\n for j in range(i+1): # loop through each element in the row\n triangle[i][j] += min(triangle[i-1][j-(j==i)], # minimum sum from coordinate (x-1, y)\n triangle[i-1][j-(j>0)]) # minimum sum from coordinate (x-1, y-1)\n return min(triangle[-1]) # obtain minimum sum from last row\n```\n\n**TC: O(n<sup>2</sup>)**, since we visit each element in the array\n**SC: O(1)**, as discussed above.\n\n---\n\n### Approach 2: Bottom-Up Approach\n\nWe can use the same pseudocode but implement it in reverse. This saves on the min check at the end (which runs in O(n) time), since we know that **the last element for a bottom-up approach has to be `triangle[0][0]`, and therefore that is where our answer is stored**.\n\n```python\nclass Solution:\n def minimumTotal(self, triangle: List[List[int]]) -> int:\n for i in range(len(triangle)-2, -1, -1): # for each row in triangle (skipping the last),\n for j in range(i+1): # loop through each element in the row\n triangle[i][j] += min(triangle[i+1][j], # minimum sum from coordinate (x+1, y)\n triangle[i+1][j+1]) # minimum sum from coordinate (x+1, y+1)\n return triangle[0][0]\n```\n\n**TC: O(n<sup>2</sup>)**, as discussed above.\n**SC: O(1)**, as discussed above.\n\n---\n\nPlease upvote if this has helped you! Appreciate any comments as well :)
11,879
Triangle
triangle
Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
Array,Dynamic Programming
Medium
null
2,447
27
*(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\n---\n\n#### ***Idea:***\n\nIn order to find the best path from the top of the input triangle array (**T**) to the bottom, we should be able to find the best path to any intermediate spot along that path, as well. That should immediately bring to mind a **dynamic programming** (**DP**) solution, as we can divide this solution up into smaller pieces and then build those up to our eventual solution.\n\nThe naive idea here might be to do a **bottom-up** DP approach (which is actually from the start of the path, or the top of **T**, to the end of the path, or the bottom of **T**), since that reflects the normal path progression and branching. If we do this, however, we\'ll need to write extra code to avoid going out-of-bounds when checking the previously completed rows of the DP array. We\'ll also have to then check the entire bottom row of our DP array to find the best value.\n\nIf we use a **top-down** DP approach (visually bottom to top of **T**), however, we can avoid having to check for out-of-bounds conditions, as we\'ll be going from larger rows to smaller rows. Also, we won\'t need to search for the best solution, because it will automatically be isolated in **T[0][0]**.\n\nFurthermore, since we\'ll never need to backtrack to previous rows, we can use **T** as its own **in-place** DP array, updating the values as we go, in order to achieve a **space complexity** of **O(1)** extra space.\n\nIn order to accomplish this, we\'ll just need to iterate backwards through the rows, starting from the second to the last, and figure out what the best path to the bottom would be from each location in the row. Since the values in the row below will already represent the best path from that point, we can just add the lower of the two possible branches to the current location (**T[i][j]**) at each iteration.\n\nOnce we\'re done, we can simply **return T[0][0]**.\n\n---\n\n#### ***Implementation:***\n\nFor Java, using an **in-place DP** approach, while saving on **space complexity**, is significantly less performant than using an **O(N)** DP array.\n\n---\n\n#### ***Javascript Code:***\n\nThe best result for the code below is **72ms / 38.8MB** (beats 98% / 93%).\n```javascript\nvar minimumTotal = function(T) {\n for (let i = T.length - 2; ~i; i--) \n for (let j = T[i].length - 1; ~j; j--) \n T[i][j] += Math.min(T[i+1][j], T[i+1][j+1])\n return T[0][0]\n}\n```\n\n---\n\n#### ***Python Code:***\n\nThe best result for the code below is **48ms / 14.9MB** (beats 99% / 85%).\n```python\nclass Solution:\n def minimumTotal(self, T: List[List[int]]) -> int:\n for i in range(len(T)-2,-1,-1):\n for j in range(len(T[i])-1,-1,-1):\n T[i][j] += min(T[i+1][j], T[i+1][j+1])\n return T[0][0]\n```\n\n---\n\n#### ***Java Code:***\n\nThe best result for the code below is **4ms / 38.6MB** (beats 32% / 96%).\n```java\nclass Solution {\n public int minimumTotal(List<List<Integer>> T) {\n for (int i = T.size() - 2; i >= 0; i--) \n for (int j = T.get(i).size() - 1; j >= 0; j--) {\n int min = Math.min(T.get(i+1).get(j), T.get(i+1).get(j+1));\n T.get(i).set(j, T.get(i).get(j) + min);\n }\n return T.get(0).get(0);\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n\nThe best result for the code below is **0ms / 8.3MB** (beats 100% / 94%).\n```c++\nclass Solution {\npublic:\n int minimumTotal(vector<vector<int>>& T) {\n for (int i = T.size() - 2; ~i; i--) \n for (int j = T[i].size() - 1; ~j; j--) \n T[i][j] += min(T[i+1][j], T[i+1][j+1]);\n return T[0][0];\n }\n};\n```
11,881
Triangle
triangle
Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
Array,Dynamic Programming
Medium
null
1,929
23
**As a professional with a passion for problem-solving and collaboration, I am always looking to expand my network of like-minded individuals on LinkedIn. By connecting with me, we can work together to tackle complex challenges, share ideas, and grow both professionally and personally.**\n\n**Whether you\'re an expert in your field or just starting out, I welcome connections from all backgrounds and experiences. By building a diverse and collaborative network, we can leverage our unique perspectives and skill sets to push the boundaries of what\'s possible.**\n\n**So, if you\'re interested in connecting and exploring the potential for future collaborations, please don\'t hesitate to reach out. Let\'s start a conversation and see where it takes us!**\n\n---\n\n\n\n\n\n---\n```\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 int minimumTotal(List<List<Integer>> triangle) {\n int[] A = new int[triangle.size()+1];\n for(int i=triangle.size()-1;i>=0;i--){\n for(int j=0;j<triangle.get(i).size();j++){\n A[j] = Math.min(A[j],A[j+1])+triangle.get(i).get(j);\n }\n }\n return A[0];\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 int minTotalUtil(vector<vector<int>>& triangle, int h, int j) {\n \n if(h == triangle.size()) {\n return 0;\n } \n \n return triangle[h][j]+min(minTotalUtil(triangle, h+1, j),minTotalUtil(triangle, h+1, j+1));\n }\n int minimumTotal(vector<vector<int>>& triangle) {\n \n return minTotalUtil(triangle, 0, 0);\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```\nclass Solution:\n def minimumTotal(self, triangle: List[List[int]]) -> int:\n if not triangle:\n return \n res = triangle[-1]\n for i in range(len(triangle)-2, -1, -1):\n for j in range(len(triangle[i])):\n res[j] = min(res[j], res[j+1]) + triangle[i][j]\n return res[0]\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 minimumTotal(triangle: number[][]): number {\n if (triangle.length === 1) return triangle[0][0];\n \n let height = triangle.length - 2;\n \n for (let level: number = height; level >= 0; level--) {\n for (let col: number = 0; col < triangle[level].length; col++) {\n triangle[level][col] += Math.min(triangle[level + 1][col], triangle[level + 1][col + 1]);\n }\n }\n \n return triangle[0][0];\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```\nclass Solution {\n\tfun minimumTotal(triangle: List<MutableList<Int>>): Int {\n\t\tval row = triangle.size\n\t\tfor (idx in row-1 downTo 0) {\n\t\t\tval size = triangle[idx].size\n\t\t\tfor (col in 0 until size-1) {\n\t\t\t\tval num1 = triangle[idx][col]\n\t\t\t\tval num2 = if (col+1<size) triangle[idx][col+1] else MAX_VALUE\n\t\t\t\ttriangle[idx-1][col] += min(num1, num2)\n\t\t\t}\n\t\t\tif (size == 2) break\n\t\t}\n\t\treturn triangle[0][0]\n\t}\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 func minimumTotal(_ triangle: [[Int]]) -> Int {\n let len = triangle.count\n guard len >= 1 && len <= 200 else { return 0 }\n var last = triangle.last!\n for i in stride(from: len - 2, through: 0, by: -1) {\n for j in 0...i { last[j] = min(last[j], last[j+1]) + triangle[i][j] }\n }\n return last[0]\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***
11,887
Best Time to Buy and Sell Stock
best-time-to-buy-and-sell-stock
You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Array,Dynamic Programming
Easy
null
294,094
2,099
**The question is saying us to find the best day to buy and sell stock, so we will get maiximum profit.**\n\n**Some body might think that we can find min and max number from the array so that we can get the max profit. But here is one catch\nFor Example:\nprices=[3,4,1,6]\nmin=1\nmax=6\nprofit=max-min=5 which is correct\nin this Example:\n```\nprices = [7,6,4,3,1]\n```\nmin = 1 price at day 6\nmax = 7 price at day 1\nmax_profit = 7-1 = 6 u can think like this but you can\'t buy the stock at day 6 and sell it at day 1.**\n\n---\n\n**So what is the best way to find the max profit lets see \uD83D\uDE03\n<ins>Explanation:</ins>\nlet use initialize Left and Right pointer to first and second position of array\nHere Left is to buy stock and Right is to sell stock**\n\n\n` Then we initialize our max_profit as 0. `\n\n#### Now we will start our while loop and we will run till our \n\n**Right pointer less then length of array \n<ins>For Example: </ins>\nprices=[7,1,5,3,6,4]\nNote:\nprices[left] --> buy stock\nprices[right] --> sell stock\nnow we will check price at right and left pointer**\n\n\n**step 1:** <br>\nprice[left]=7 price[right]=1 profit=-6\nhere price[left] is greater than price[right] so we will move left pointer to the right position and increment our right pointer by 1. We always want our left point to be minimum\n\n**step 2:** <br>\nprice[left]=1 price[right]=5 profit=4\nhere price[left] is less than price[right] which means we will get profit so we will update our max_profit and move our right pointer alone\n\n**step 3:** <br>\nprice[left]=1 price[right]=3 profit=2\nhere price[left] is less than price[right] which means we will get profit so we will check our max_profit previously it\n\nwas 4 now our current profit is 2 so we will check which is maximum and update our max_profit and move our right pointer alone\n\n**step 4:** <br>\nprice[left]=1 price[right]=6 profit=5\nhere price[left] is less than price[right] which means we will get profit so we will check our max_profit previously it was 4 now our current profit is 5 so we will check which is maximum and update our max_profit and move our right pointer alone\n\n**step 5:** <br>\nprice[left]=1 price[right]=4 profit=3\nsame logic as above\n\n\n```\nBig O :\nn--> length of array\nTime Complexity: O(n)\nSpace Complexity: O(1)\n```\n\n**My Hand Writting will not be good ,please adjust it \uD83D\uDE05**\n\n![image]()\n\n\n## lets go to the solution:\n\npython:\n```python []\nclass Solution:\n def maxProfit(self,prices):\n left = 0 #Buy\n right = 1 #Sell\n max_profit = 0\n while right < len(prices):\n currentProfit = prices[right] - prices[left] #our current Profit\n if prices[left] < prices[right]:\n max_profit =max(currentProfit,max_profit)\n else:\n left = right\n right += 1\n return max_profit\n```\n\njavascript:\n```javascript []\nconst maxProfit = (prices) => {\n let left = 0; // Buy\n let right = 1; // sell\n let max_profit = 0;\n while (right < prices.length) {\n if (prices[left] < prices[right]) {\n let profit = prices[right] - prices[left]; // our current profit\n\n max_profit = Math.max(max_profit, profit);\n } else {\n left = right;\n }\n right++;\n }\n return max_profit;\n};\n```\n`UPVOTE if you like \uD83D\uDE03 , If you have any question, feel free to ask.`\n
11,900
Best Time to Buy and Sell Stock
best-time-to-buy-and-sell-stock
You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Array,Dynamic Programming
Easy
null
34,281
250
# Approach\nTo solve this problem, I employed a straightforward approach that iterates through the array of stock prices. At each step, I kept track of the minimum stock price seen so far (`min_price`) and calculated the potential profit that could be obtained by selling at the current price (`prices[i] - min_price`). I updated the `maxprof` (maximum profit) variable with the maximum of its current value and the calculated profit. Additionally, I updated the `min_price` to be the minimum of the current stock price and the previously seen minimum.\n\n# Complexity\n- Time complexity: $$O(n)$$\nThe algorithm iterates through the array of stock prices once, performing constant-time operations at each step. Therefore, the time complexity is linear in the size of the input array.\n\n- Space complexity: $$O(1)$$\nThe algorithm uses a constant amount of extra space to store variables like `min_price` and `maxprof`. The space complexity remains constant regardless of the size of the input array.\n\n\n# Code\n``` cpp []\nclass Solution {\npublic:\n int maxProfit(vector<int>& prices) {\n int min_price = prices[0];\n int maxprof = 0;\n\n for(int i=1;i<prices.size();i++){\n maxprof = max(maxprof,prices[i]-min_price);\n min_price = min(prices[i],min_price);\n }\n\n return maxprof;\n }\n};\n```\n\n``` java []\nclass Solution {\n public int maxProfit(int[] prices) {\n int min_price = prices[0];\n int maxprof = 0;\n\n for(int i=1;i<prices.length;i++){\n maxprof = Math.max(maxprof,prices[i]-min_price);\n min_price = Math.min(prices[i],min_price);\n }\n\n return maxprof;\n }\n}\n```\n\n``` python3 []\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n min_price = prices[0]\n max_profit = 0\n \n for price in prices[1:]:\n max_profit = max(max_profit, price - min_price)\n min_price = min(min_price, price)\n \n return max_profit\n```\n\nHope you liked the Solution,\nIf you have any questions or suggestions, feel free to share \u2013 happy coding!\n\n---\n\n\n![pleaseupvote.jpg]()\n
11,902
Best Time to Buy and Sell Stock
best-time-to-buy-and-sell-stock
You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Array,Dynamic Programming
Easy
null
15,263
93
# Intuition of this Problem:\nThe intuition behind the code is to keep track of the minimum stock value seen so far while traversing the array from left to right. At each step, if the current stock value is greater than the minimum value seen so far, we calculate the profit that can be earned by selling the stock at the current value and buying at the minimum value seen so far, and update the maximum profit seen so far accordingly.\n\nBy keeping track of the minimum stock value and the maximum profit seen so far, we can solve the problem in a single pass over the array, without needing to consider all possible pairs of buy-sell transactions. This makes the code efficient and easy to implement.\n<!-- Describe your first thoughts on how to solve this problem. -->\n**NOTE - PLEASE READ APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n# Approach for this Problem:\n1. Initialize a variable n to the size of the input vector prices.\n2. Initialize variables maximumProfit and minStockVal to 0 and INT_MAX respectively.\n3. Initialize a loop variable i to 0.\n4. While i is less than n, do the following:\n - a. Set minStockVal to the minimum value between minStockVal and the value of prices at index i.\n - b. If minStockVal is less than or equal to the value of prices at index i, set maximumProfit to the maximum value between maximumProfit and the difference between prices at index i and minStockVal.\n - c. Increment i by 1.\n1. Return maximumProfit.\n<!-- Describe your approach to solving the problem. -->\n\n# Humble Request:\n- If my solution is helpful to you then please **UPVOTE** my solution, your **UPVOTE** motivates me to post such kind of solution.\n- Please let me know in comments if there is need to do any improvement in my approach, code....anything.\n- **Let\'s connect on** \n\n![57jfh9.jpg]()\n\n# Code:\n```C++ []\nclass Solution {\npublic:\n int maxProfit(vector<int>& prices) {\n int n = prices.size();\n int maximumProfit = 0, minStockVal = INT_MAX;\n int i = 0;\n while (i < n) {\n minStockVal = min(minStockVal, prices[i]);\n // whenever the price of current stock is greater then then the stock value which we bought then only we will sell the stock \n if (prices[i] >= minStockVal)\n maximumProfit = max(maximumProfit, prices[i] - minStockVal);\n i++;\n }\n return maximumProfit;\n }\n};\n```\n```Java []\nclass Solution {\n public int maxProfit(int[] prices) {\n int n = prices.length;\n int maximumProfit = 0, minStockVal = Integer.MAX_VALUE;\n int i = 0;\n while (i < n) {\n minStockVal = Math.min(minStockVal, prices[i]);\n // whenever the price of current stock is greater then then the stock value which we bought then only we will sell the stock \n if (prices[i] >= minStockVal)\n maximumProfit = Math.max(maximumProfit, prices[i] - minStockVal);\n i++;\n }\n return maximumProfit;\n }\n}\n\n```\n```Python []\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n n = len(prices)\n maximumProfit, minStockVal = 0, float(\'inf\')\n i = 0\n while i < n:\n minStockVal = min(minStockVal, prices[i])\n if prices[i] >= minStockVal:\n maximumProfit = max(maximumProfit, prices[i] - minStockVal)\n i += 1\n return maximumProfit\n\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(n)**, where n is the size of the input vector prices.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(1)**, as we are only using constant extra space for variables.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
11,933
Best Time to Buy and Sell Stock
best-time-to-buy-and-sell-stock
You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Array,Dynamic Programming
Easy
null
880
6
\n\nA brute force approach would calculate every possible buy-sell combination and would run in O(n^2), but we can reduce this to O(n) by avoiding unncessary computations. The strategy below iterates once for every sell date, and handles two cases:\n1. If buy price < sell price, calculate the profit and compare it to the max profit so far. If it is greater than the max profit, replace it. Also, there is no need to go back and calculate profits using this <i>sell</i> date as a buy date, since we can always achieve a higher profit from using the original buy date (which is at a lower price).\n2. If sell price <= buy date, simply update the buy date to be the current sell date, since we have found a lower price to buy from.\n\nAt the end, return `profit`, which will contain the maximum profit achievable.\n\n# Code\n```\nclass Solution(object):\n def maxProfit(self, prices):\n profit = 0\n buy = prices[0]\n for sell in prices[1:]:\n if sell > buy:\n profit = max(profit, sell - buy)\n else:\n buy = sell\n \n return profit\n```
11,946
Best Time to Buy and Sell Stock
best-time-to-buy-and-sell-stock
You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Array,Dynamic Programming
Easy
null
19,002
133
Given an array prices where prices[i] is the price of a given stock on the ith day.\nmaximize our profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.\nReturn the maximum profit achieve from this transaction. If you cannot achieve any profit, return 0\n\n**Example:**\nInput: prices = [7,1,5,3,6,4]\nOutput: 5\n**Explanation:** Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\n**Note that, buying on day 2 and selling on day 1 is not allowed because we must buy before sell.**\n# **Java Solution:**\nRuntime: 1 ms, faster than 98.59% of Java online submissions for Best Time to Buy and Sell Stock.\n```\nclass Solution {\n public int maxProfit(int[] prices) {\n // Base case...\n // If the array is empty or its length <= 1, return 0...\n if(prices == null || prices.length <= 1) return 0;\n // Initialize the minimum price to buy...\n int minBuy = prices[0];\n // Initialize the maximum profit...\n int profit = 0;\n // Traverse all elements through a for loop...\n for(int i = 1; i < prices.length; i++) {\n // Get the minimum price to buy...\n minBuy = Math.min(minBuy, prices[i]);\n // Get maximum profit...\n profit = Math.max(profit, prices[i] - minBuy);\n }\n return profit; //return the maximum profit...\n }\n}\n```\n\n# **C++ Solution:**\n```\nclass Solution {\npublic:\n int maxProfit(vector<int>& prices) {\n if(prices.size() == 0) return 0;\n int profit = 0;\n int low = prices[0], high = prices[0];\n for(int i = 0; i < prices.size(); i++){\n if(prices[i] < low){\n profit = max(profit, high - low);\n low = prices[i];\n high = prices[i];\n }else{\n high = max(high, prices[i]);\n }\n }\n profit = max(profit, high - low);\n return profit;\n }\n};\n```\n\n# **Python Solution:**\n```\nclass Solution(object):\n def maxProfit(self, prices):\n if len(prices) == 0: return 0\n else:\n profit = 0\n minBuy = prices[0]\n for i in range(len(prices)):\n profit = max(prices[i] - minBuy, profit)\n minBuy = min(minBuy, prices[i])\n return profit\n```\n \n# **JavaScript Solution:**\n```\nvar maxProfit = function(prices) {\n if(prices == null || prices.length <= 1) return 0;\n let minBuy = prices[0];\n let profit = 0;\n for(let i = 1; i < prices.length; i++) {\n minBuy = Math.min(minBuy, prices[i]);\n profit = Math.max(profit, prices[i] - minBuy);\n }\n return profit;\n};\n```\n\n# **Python3 Solution:**\n```\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n if len(prices) == 0: return 0\n else:\n profit = 0\n minBuy = prices[0]\n for i in range(len(prices)):\n profit = max(prices[i] - minBuy, profit)\n minBuy = min(minBuy, prices[i])\n return profit\n```\n**I am working hard for you guys...\nPlease upvote if you found any help with this code...**
11,948
Best Time to Buy and Sell Stock
best-time-to-buy-and-sell-stock
You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Array,Dynamic Programming
Easy
null
35,965
308
**Suggestions to make it better are always welcomed.**\n\nWe might think about using sliding window technique, but obviously we don\'t need subarray here. We just need one value from the given input list. So, this technique is not useful.\n\n**Solution:**\nWe always need to know what is the maxProfit we can make if we sell the stock on i-th day. So, keep track of maxProfit.\nThere might be a scenario where if stock bought on i-th day is minimum and we sell it on (i + k)th day. So, keep track of minPurchase as well.\n\n```\ndef maxProfit(self, prices: List[int]) -> int:\n\tif not prices:\n\t\treturn 0\n\n\tmaxProfit = 0\n\tminPurchase = prices[0]\n\tfor i in range(1, len(prices)):\t\t\n\t\tmaxProfit = max(maxProfit, prices[i] - minPurchase)\n\t\tminPurchase = min(minPurchase, prices[i])\n\treturn maxProfit\n```\n\n**I hope that you\'ve found this useful.\nIn that case, please upvote. It only motivates me to write more such posts\uD83D\uDE03**
11,954
Best Time to Buy and Sell Stock II
best-time-to-buy-and-sell-stock-ii
You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve.
Array,Dynamic Programming,Greedy
Medium
null
58,661
655
Method_#1\nO(n) sol by DP + state machine\n\nDefine "**Hold**" as the state of **holding stock**. (\u6301\u6709\u80A1\u7968)\nDefine "**NotHold**" as the state of **keep cash**. (\u6301\u6709\u73FE\u91D1)\n\nGeneral rule aka recursive relationship.\n\n```\nDP[Hold] \n= max(keep holding stock, or just buy stock & hold today)\n= max( DP[Previous Hold], DP[previous NotHold] - stock price)\n```\n---\n\n```\nDP[NotHold] \n= max(keep cash, or just sell out stock today)\n= max( DP[Previous NotHold], DP[previous Hold] + stock price)\n```\n\n---\n\n**State machine diagram**:\n\n<img src="" width="1000" height="600">\n\n---\n\n**Implementation** by botoom-up DP + iteration:\n<iframe src="" frameBorder="0" width="1000" height="600"></iframe>\n\nTime Complexity: O(n), for single level for loop\nSpace Complexity: O(1), for fixed size of temporary variables\n\n---\n\n**Implementation** with Top down DP + recursion \n<iframe src="" frameBorder="0" width="1000" height="600"></iframe>\n\nTime Complexity: O(n), for single level for loop\nSpace Complexity: O(n), for 1D DP recursion call depth\n\n---\n\nMethod_#2\nO(n) sol by Greedy\n\nShare another O(n) solution by price gain collection with **greedy** value taking concept.\n\nMax profit with [long position]((finance)) ,\'\u505A\u591A\' in chinese, is met by **collecting all price gain** in the stock price sequence.\n\nTake care that holding **multiple position at the same time is NOT allowed** by [description]().\n\n---\n\n**Visualization**:\n\n![image]()\n\n---\n\n**Implementation** based on container and summation function:\n\n\n```python []\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n\n price_gain = []\n \n for idx in range( len(prices)-1 ):\n \n if prices[idx] < prices[idx+1]:\n \n price_gain.append( prices[idx+1]- prices[idx])\n \n return sum( price_gain )\n```\n```Java []\nclass Solution {\n \n \n public int maxProfit(int[] prices) {\n\n ArrayList<Integer> priceGain = new ArrayList<Integer>();\n \n for(int idx = 0 ; idx < prices.length-1; idx++){\n \n if( prices[idx] < prices[idx+1] ){\n priceGain.add( prices[idx+1]- prices[idx]);\n }\n \n }\n return priceGain.stream().mapToInt(n->n).sum();\n \n }\n}\n```\n```Javascript []\nconst accumulate = ( (prev, cur) => (prev + cur) );\n\nvar maxProfit = function(prices) {\n \n let profit = new Array();\n \n for( let i = 0 ; i < prices.length-1 ; i++ ){\n \n if( prices[i] < prices[i+1] ){\n profit.push( prices[i+1] - prices[i] );\n }\n }\n return profit.reduce(accumulate, 0);\n}\n```\n```Go []\nfunc Accumulate(elements ...int) int { \n sum := 0 \n for _, elem := range elements { \n sum += elem \n } \n return sum \n} \n\n\nfunc maxProfit(prices []int) int {\n \n profit := make([]int, 0)\n \n for i := 0 ; i < len(prices)-1 ; i++{\n \n if( prices[i] < prices[i+1] ){\n profit = append(profit, ( prices[i+1] - prices[i] ))\n }\n }\n\n return Accumulate(profit...)\n}\n```\n```C++ []\nclass Solution {\npublic:\n int maxProfit(vector<int>& prices) {\n \n vector<int> profit;\n \n for( size_t i = 0 ; i < prices.size()-1 ; i++ ){\n \n if( prices[i] < prices[i+1] ){\n profit.push_back( prices[i+1] - prices[i] );\n }\n \n }\n return accumulate( profit.begin(), profit.end(), 0);\n }\n};\n```\n\nTime Complexity: O(n), for single level for loop\nSpace Complexity: O(n), for array storage sapce\n\n\n---\n\n**Implementation** based on generator expression and sum( ... ):\n\n```\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n\n return sum( ( prices[idx+1]-prices[idx] ) for idx in range(len(prices)-1) if prices[idx] < prices[idx+1] )\n```\n\n---\n\n**Implementation** based on O(1) aux space:\n\n```python []\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n \n profit_from_price_gain = 0\n for idx in range( len(prices)-1 ):\n \n if prices[idx] < prices[idx+1]:\n profit_from_price_gain += ( prices[idx+1] - prices[idx])\n \n return profit_from_price_gain\n```\n```Javascript []\nvar maxProfit = function(prices) {\n \n let profitFromPriceGain = 0;\n \n for( let i = 0 ; i < prices.length-1 ; i++ ){\n \n if( prices[i] < prices[i+1] ){\n profitFromPriceGain += ( prices[i+1] - prices[i] );\n }\n }\n \n return profitFromPriceGain;\n}\n```\n```Java []\nclass Solution {\n public int maxProfit(int[] prices) { \n int profitFromPriceGain = 0;\n \n for( int i = 0 ; i < prices.length-1 ; i++ ){\n \n if( prices[i] < prices[i+1] ){\n profitFromPriceGain += ( prices[i+1] - prices[i] );\n }\n }\n \n return profitFromPriceGain;\n }\n}\n```\n```Go []\nfunc maxProfit(prices []int) int {\n \n profitFromPriceGain := 0\n \n for i := 0 ; i < len(prices)-1 ; i++{\n \n if( prices[i] < prices[i+1] ){\n profitFromPriceGain += ( prices[i+1] - prices[i] )\n }\n }\n\n return profitFromPriceGain\n}\n```\n```C++ []\nclass Solution {\npublic:\n int maxProfit(vector<int>& prices) {\n \n int profitFromPriceGain = 0;\n \n for( size_t i = 0 ; i < prices.size()-1 ; i++ ){\n \n if( prices[i] < prices[i+1] ){\n profitFromPriceGain += ( prices[i+1] - prices[i] );\n }\n \n }\n return profitFromPriceGain;\n }\n};\n```\n\nTime Complexity: O(n), for single level for loop\nSpace Complexity: O(1), for fixed size of temporary variables\n\n\n---\n\nRelated leetcode challenge:\n\n[Leetcode #121 Best Time to Buy and Sell Stock]()\n\n[Leetcode #123 Best Time to Buy and Sell Stock III ]()\n\n[Leetcode #188 Best Time to Buy and Sell Stock IV ]()\n\n[Leetcode #309 Best Time to Buy and Sell Stock with Cooldown]()\n\n[Leetcode #714 Best Time to Buy and Sell Stock with Transaction Fee ]() \n\n---\n\nReference:\n\n[1] [Python official docs about generator expression]()\n\n[2] [Python official docs about sum( ... )]()
12,004
Best Time to Buy and Sell Stock II
best-time-to-buy-and-sell-stock-ii
You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve.
Array,Dynamic Programming,Greedy
Medium
null
5,617
34
# Please Upvote \uD83D\uDE07\n\n## Python3\n```\nclass Solution:\n def maxProfit(self, a: List[int]) -> int:\n ans=0\n x=a[0]\n for i in range(1,len(a)):\n if(x>a[i]):\n x=a[i]\n else:\n ans+=a[i]-x\n x=a[i]\n return ans\n\n \n```
12,050
Best Time to Buy and Sell Stock II
best-time-to-buy-and-sell-stock-ii
You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve.
Array,Dynamic Programming,Greedy
Medium
null
2,102
26
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n maxprofit=0\n for i in range(len(prices)-1):\n if prices[i+1]>prices[i]:\n maxprofit+=prices[i+1]-prices[i]\n return maxprofit\n #please upvote me it would encourage me alot\n\n```
12,079
Best Time to Buy and Sell Stock II
best-time-to-buy-and-sell-stock-ii
You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve.
Array,Dynamic Programming,Greedy
Medium
null
1,108
5
# Approach\n1. For every day $$d_i$$, if $$prices[d_i] < prices[d_{i + 1}]$$ then buy the stock on $$d_i$$ and sell it on $$d_{i + 1}$$ else do nothing.\n\n2. Continue this for each day and return the `sum` of all the profits.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\nwhere, `n is length of prices`.\n\n# Code\n```python\nclass Solution:\n def maxProfit(self, prices: list[int]) -> int:\n return sum(max(b - a, 0) for a, b in pairwise(prices))\n\n\n```
12,091
Best Time to Buy and Sell Stock II
best-time-to-buy-and-sell-stock-ii
You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve.
Array,Dynamic Programming,Greedy
Medium
null
5,448
18
# Intuition:\nThe intuition behind this approach is to find all the local minima and maxima in the given array of prices. We buy the stock at the local minima and sell it at the corresponding local maxima. By doing this, we can accumulate the maximum profit.\n\n# Approach:\n1. Initialize the variables `profit` and `minPrice` to 0 and `INT_MAX` respectively.\n2. Iterate through the prices array using a for loop.\n3. For each price at index `i`:\n a. Update the `minPrice` by taking the minimum of the current `minPrice` and `prices[i]`.\n b. If the difference between `prices[i]` and `minPrice` is greater than 0, it means there is a profit to be made.\n - Add this profit to the `profit` variable.\n - Update the `minPrice` to `prices[i]` since we have sold the stock at this price.\n4. Return the `profit`.\n\n# Complexity:\n- The time complexity of this approach is O(n), where n is the size of the prices array, since we iterate through the array once.\n- The space complexity is O(1) as we are using a constant amount of extra space to store the `profit` and `minPrice` variables.\n\n# Code\n```\nclass Solution {\npublic:\n int maxProfit(vector<int>& prices) {\n int profit=0;\n int minPrice=INT_MAX;\n for(int i=0;i<prices.size();i++){\n minPrice = min(minPrice,prices[i]);\n if((prices[i]-minPrice)>0){\n profit=profit+(prices[i]-minPrice);\n minPrice=prices[i];\n }\n }\n return profit;\n }\n};\n```\n\n---\n# Java\n```\nclass Solution {\n public int maxProfit(int[] prices) {\n int profit = 0;\n int minPrice = Integer.MAX_VALUE;\n for (int i = 0; i < prices.length; i++) {\n minPrice = Math.min(minPrice, prices[i]);\n if (prices[i] - minPrice > 0) {\n profit += prices[i] - minPrice;\n minPrice = prices[i];\n }\n }\n return profit;\n }\n}\n\n```\n---\n# Python\n```\nclass Solution(object):\n def maxProfit(self, prices):\n profit = 0\n minPrice = float(\'inf\')\n for price in prices:\n minPrice = min(minPrice, price)\n if price - minPrice > 0:\n profit += price - minPrice\n minPrice = price\n return profit\n\n```\n\n---\n# JavaScript\n```\nvar maxProfit = function(prices){\n let profit = 0;\n let minPrice = Infinity;\n for (let i = 0; i < prices.length; i++) {\n minPrice = Math.min(minPrice, prices[i]);\n if (prices[i] - minPrice > 0) {\n profit += prices[i] - minPrice;\n minPrice = prices[i];\n }\n }\n return profit;\n}\n\n```
12,092
Best Time to Buy and Sell Stock II
best-time-to-buy-and-sell-stock-ii
You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve.
Array,Dynamic Programming,Greedy
Medium
null
248
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. --> Not the best solution but very easy to understand. Any improvements are welcome :)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def maxProfit(self, prices):\n profit = 0\n for i in range(len(prices) - 1):\n if prices[i] < prices[i + 1]:\n profit += prices[i + 1] - prices[i]\n\n return profit\n```
12,099
Best Time to Buy and Sell Stock III
best-time-to-buy-and-sell-stock-iii
You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete at most two transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Array,Dynamic Programming
Hard
null
3,813
29
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe basic idea is to iterate over the array of stock prices and update four variables:\n\nbuy1 - the minimum price seen so far for the first transaction\nsell1 - the maximum profit seen so far for the first transaction\nbuy2 - the minimum price seen so far for the second transaction, taking into account the profit from the first transaction\nsell2 - the maximum profit seen so far for the second transaction\nAt the end of the iteration, the value of sell2 is returned as the maximum profit achievable with two transactions.\n\nThe if not prices check is included to handle the edge case where the input array is empty.\n\nHere\'s how the algorithm works step by step for the input [3,3,5,0,0,3,1,4]:\n\n1. Initialize buy1, buy2, sell1, and sell2 to inf, inf, 0, and 0, respectively.\n2. For the first price of 3, update buy1 to 3, sell1 to 0, buy2 to -3, and sell2 to 0.\n3. For the second price of 3, update buy1 to 3, sell1 to 0, buy2 to -3, and sell2 to 0 (no change).\n4. For the third price of 5, update buy1 to 3, sell1 to 2, buy2 to -1, and sell2 to 2.\n5. For the fourth price of 0, update buy1 to 0, sell1 to 2, buy2 to -1, and sell2 to 2 (no change).\n6. For the fifth price of 0, update buy1 to 0, sell1 to 2, buy2 to -2, and sell2 to 2 (no change).\n7. For the sixth price of 3, update buy1 to 0, sell1 to 3, buy2 to 0, and sell2 to 3.\n8. For the seventh price of 1, update buy1 to 0, sell1 to 3, buy2 to -3, and sell2 to 3 (no change).\n9. For the eighth price of 4, update buy1 to 0, sell1 to 4, buy2 to 0, and sell2 to 4\n# Complexity\n- Time complexity:\nBeats\n88.20%\n\n- Space complexity:\nBeats\n91.19%\n\n# Code\n```\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n if not prices:\n return 0\n\n # initialize variables for first buy, first sell, second buy, and second sell\n buy1, buy2 = float(\'inf\'), float(\'inf\')\n sell1, sell2 = 0, 0\n\n # iterate over prices to update buy and sell values\n for price in prices:\n # update first buy and sell values\n buy1 = min(buy1, price)\n sell1 = max(sell1, price - buy1)\n # update second buy and sell values\n buy2 = min(buy2, price - sell1)\n sell2 = max(sell2, price - buy2)\n\n return sell2\n\n```
12,129
Best Time to Buy and Sell Stock III
best-time-to-buy-and-sell-stock-iii
You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete at most two transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Array,Dynamic Programming
Hard
null
1,109
7
# Dynamic programming\n```\nclass Solution:\n def maxProfit(self, A: List[int]) -> int:\n N=len(A)\n sell=[0]*N\n for _ in range(2):\n buy=-A[0]\n profit=0\n for i in range(1,N):\n buy=max(buy,sell[i]-A[i])\n profit=max(profit,A[i]+buy)\n sell[i]=profit\n return sell[-1]\n```\n# please upvote me it would encourage me alot\n
12,131
Best Time to Buy and Sell Stock III
best-time-to-buy-and-sell-stock-iii
You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete at most two transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Array,Dynamic Programming
Hard
null
4,134
26
```\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```\nclass Solution {\n public int maxProfit(int[] prices) {\n if(prices == null || prices.length < 1) return 0;\n int buy1 = -prices[0], sell1 = 0, buy2 = -prices[0], sell2 = 0;\n for(int i = 1; i < prices.length; i++) {\n buy1 = Math.max(buy1, -prices[i]);\n sell1 = Math.max(sell1, buy1 + prices[i]);\n buy2 = Math.max(buy2, sell1 - prices[i]);\n sell2 = Math.max(sell2, buy2 + prices[i]);\n }\n return sell2;\n }\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 \n int solve(vector<int>&prices, int day, int transactionsLeft){\n \n if(day == prices.size()){\n return 0;\n }\n \n if(transactionsLeft == 0){\n return 0;\n }\n \n // choice 1\n // no transaction today\n int ans1 = solve(prices, day + 1, transactionsLeft);\n \n \n // choice 2\n // doing the possible transaction today \n int ans2 = 0;\n bool buy = (transactionsLeft % 2 == 0);\n \n if(buy == true){ // buy\n ans2 = -prices[day] + solve(prices, day + 1, transactionsLeft - 1);\n }else{ // sell\n ans2 = prices[day] + solve(prices, day + 1, transactionsLeft - 1);\n }\n \n return max(ans1, ans2);\n \n \n }\n \n \n int maxProfit(vector<int>& prices) {\n \n int ans = solve(prices, 0, 4); // starting with day 0 and max 4 transactions can be done\n return ans;\n \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```\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n buy, sell = [inf]*2, [0]*2\n for x in prices:\n for i in range(2): \n if i: buy[i] = min(buy[i], x - sell[i-1])\n else: buy[i] = min(buy[i], x)\n sell[i] = max(sell[i], x - buy[i])\n return sell[1]\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```\nvar maxProfit = function(prices) {\n if(prices.length == 0) return 0\n \n let dp = new Array(prices.length).fill(0);\n let min = prices[0];\n let max = 0;\n for (let i = 1; i < prices.length; i++) {\n min = Math.min(min, prices[i]); // or Math.min(min, prices[i] - dp[i]) , FYI: dp[i] is 0\n max = Math.max(max, prices[i] - min);\n dp[i] = max;\n }\n \n // 1st run dp = [0,0,2,2,2,3,3,4];\n \n min = prices[0];\n max = 0;\n for (let i = 1; i < prices.length; i++) {\n min = Math.min(min, prices[i] - dp[i]); // substract dp[i] = current price - what profit we made during 1st run.\n max = Math.max(max, prices[i] - min);\n dp[i] = max;\n }\n \n // 2nd run dp = [0,0,2,2,2,5,5,6];\n \n return dp.pop();\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* ***C***\n```\nint maxProfit(int* prices, int pricesSize){\n int *s1 = (int *)malloc(sizeof(int) * pricesSize);\n int *s2 = (int *)malloc(sizeof(int) * pricesSize);\n \n memset(s1, 0, sizeof(int) * pricesSize);\n memset(s2, 0, sizeof(int) * pricesSize);\n \n int max = INT_MIN, min= prices[0];\n\n for(int i=1; i<pricesSize-1; i++){\n if(min > prices[i]) min = prices[i]; \n \n if(max < (prices[i]- min)) max = prices[i] - min;\n s1[i] = max;\n }//for i\n \n min= INT_MIN, max=prices[pricesSize-1];\n s2[pricesSize-1] = 0;\n\n for(int i=pricesSize-2; i>=0; i--){\n if(prices[i] > max) max = prices[i]; \n if(min < (max- prices[i])) min = max - prices[i];\n \n s2[i] = min;\n }//for i\n \n max=INT_MIN;\n for(int i=0;i<pricesSize;i++){\n max = max < (s1[i] + s2[i]) ? (s1[i] + s2[i]) : max;\n }\n\n return max;\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 length of the prices.\n // - space: O(1), only constant space is used.\n\n func maxProfit(_ prices: [Int]) -> Int {\n var buy1 = Int.max\n var buy2 = Int.max\n var sell1 = 0\n var sell2 = 0\n\n for price in prices {\n buy1 = min(buy1, price)\n sell1 = max(sell1, price - buy1)\n\n buy2 = min(buy2, price - sell1)\n sell2 = max(sell2, price - buy2)\n }\n\n return sell2\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***
12,156
Best Time to Buy and Sell Stock III
best-time-to-buy-and-sell-stock-iii
You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete at most two transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Array,Dynamic Programming
Hard
null
17,829
143
Two passes through the list, O(n) time, O(n) space:\n\n \n def maxProfit(self, prices):\n if not prices:\n return 0\n \n # forward traversal, profits record the max profit \n # by the ith day, this is the first transaction\n profits = []\n max_profit = 0\n current_min = prices[0]\n for price in prices:\n current_min = min(current_min, price)\n max_profit = max(max_profit, price - current_min)\n profits.append(max_profit)\n \n # backward traversal, max_profit records the max profit\n # after the ith day, this is the second transaction \n total_max = 0 \n max_profit = 0\n current_max = prices[-1]\n for i in range(len(prices) - 1, -1, -1):\n current_max = max(current_max, prices[i])\n max_profit = max(max_profit, current_max - prices[i])\n total_max = max(total_max, max_profit + profits[i])\n \n return total_max
12,158
Best Time to Buy and Sell Stock III
best-time-to-buy-and-sell-stock-iii
You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete at most two transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Array,Dynamic Programming
Hard
null
5,161
41
Python sol by DP and state machine\n\n---\n\n**State machine diagram**\n\n![image]()\n\n---\n\n**Implementation** by DP:\n\n```\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n \n\t\t\'\'\'\n\t\tdp_2_hold: max profit with 2 transactions, and in hold state\n\t\tdp_2_not_hold: max profit with 2 transactions, and not in hold state\n \n\t\tdp_1_hold: max profit with 1 transaction, and in hold state\n\t\tdp_1_not_hold: max profit with 1 transaction, and not in hold state\n\t\t\n\t\tNote: it is impossible to have stock in hand and sell on first day, therefore -infinity is set as initial profit value for hold state\n\t\t\'\'\'\n\t\t\n\t\tdp_2_hold, dp_2_not_hold = -float(\'inf\'), 0\n dp_1_hold, dp_1_not_hold = -float(\'inf\'), 0\n \n for stock_price in prices:\n \n\t\t\t# either keep being in not-hold state, or sell with stock price today\n dp_2_not_hold = max( dp_2_not_hold, dp_2_hold + stock_price )\n\t\t\t\n\t\t\t# either keep being in hold state, or just buy with stock price today ( add one more transaction )\n dp_2_hold = max( dp_2_hold, dp_1_not_hold - stock_price )\n \n\t\t\t# either keep being in not-hold state, or sell with stock price today\n dp_1_not_hold = max( dp_1_not_hold, dp_1_hold + stock_price )\n\t\t\t\n\t\t\t# either keep being in hold state, or just buy with stock price today ( add one more transaction )\n dp_1_hold = max( dp_1_hold, 0 - stock_price )\n \n \n return dp_2_not_hold\n```\n\n---\n\nor, we can use **reduction** from ( general template Leetcode #188 ) **Trade at most k times** with k=2 to solve this problem.\n\nReduction from [Leetcode #188 Best Time to Buy and Sell Stock IV]()\n<details>\n<summary>Click to show source code</summary>\n\n```\nclass Solution:\n\tdef maxProfit(self, prices: List[int]) -> int:\n\t\t\n\t\t# Reduction from Leetcode #188 Best Time to Buy and Sell Stock IV\n\t\tdef trade_at_most_k_times( k: int, prices: List[int]) -> int:\n\n\t\t\tn = len(prices)\n\n\t\t\tif n == 0:\n\n\t\t\t\t## Base case:\n\t\t\t\t# Price sequence is empty, we can do nothing : )\n\t\t\t\treturn 0\n\n\n\t\t\t## General case:\n\n\t\t\t# DP[ k ][ d ] = max profit on k, d\n\t\t\t# where k stands for k-th transaction, d stands for d-th trading day.\n\t\t\tdp = [ [ 0 for _ in range(n)] for _ in range(k+1) ]\n\n\n\t\t\t# Update by each transction as well as each trading day\n\t\t\tfor trans_k in range(1, k+1):\n\n\t\t\t\t# Balance before 1st transaction must be zero\n\t\t\t\t# Buy stock on first day means -prices[0]\n\t\t\t\tcur_balance_with_buy = 0 - prices[0]\n\n\t\t\t\tfor day_d in range(1, n):\n\n\t\t\t\t\t# Either we have finished all k transactions before, or just finished k-th transaction today\n\t\t\t\t\tdp[trans_k][day_d] = max( dp[trans_k][day_d-1], cur_balance_with_buy + prices[day_d] )\n\n\t\t\t\t\t# Either keep holding the stock we bought before, or just buy in today\n\t\t\t\t\tcur_balance_with_buy = max(cur_balance_with_buy, dp[trans_k-1][day_d-1] - prices[day_d] )\n\n\t\t\treturn dp[k][n-1]\n\t\t# --------------------------------------------\n\t\treturn trade_at_most_k_times(k=2, prices=prices)\n```\n</br>\n</details>\n\n\n\n---\n\nRelated leetcode challenge:\n\n[Leetcode #121 Best Time to Buy and Sell Stock]()\n\n[Leetcode #122 Best Time to Buy and Sell Stock II]()\n\n[Leetcode #123 Best Time to Buy and Sell Stock III ]()\n\n[Leetcode #188 Best Time to Buy and Sell Stock IV ]()\n\n[Leetcode #309 Best Time to Buy and Sell Stock with Cooldown]()\n\n[Leetcode #714 Best Time to Buy and Sell Stock with Transaction Fee ]() \n\n---
12,172
Best Time to Buy and Sell Stock III
best-time-to-buy-and-sell-stock-iii
You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete at most two transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Array,Dynamic Programming
Hard
null
867
14
```python\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n @lru_cache(maxsize=None)\n def dp(i, t, bought):\n if i >= len(prices) or t == 0:\n return 0\n \n # Skip\n profit = dp(i + 1, t, bought);\n\n # Sell\n if bought:\n profit = max(profit, dp(i + 1, t - 1, not bought) + prices[i])\n # Buy\n else:\n profit = max(profit, dp(i + 1, t, not bought) - prices[i])\n\n return profit\n \n return dp(0, 2, False)\n \n\'\'\'\nApproach: top-down recursive with memoization. On each day, we have three options: buy, sell, or skip (do nothing). In practice,\nthe recursion tree for this program will only have two branches because we can represent the choice to skip by not decrementing the number of transactions we can still make.\nT: O(n), S: O(n)\n\'\'\'\n```
12,191
Binary Tree Maximum Path Sum
binary-tree-maximum-path-sum
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree, return the maximum path sum of any non-empty path.
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Hard
null
76,106
2,529
This problem requires quite a bit of quirky thinking steps. Take it slow until you fully grasp it.\n\n# **Basics**\n![image]()\n\n\n# **Base cases**\n![image]()\n\n\n# **Important Observations**\n* These important observations are very important to understand `Line 9` and `Line 10` in the code.\n\t* For example, in the code (`Line 9`), we do something like `max(get_max_gain(node.left), 0)`. The important part is: why do we take maximum value between 0 and maximum gain we can get from left branch? Why 0?\n\t* Check the two images below first.\n![image]()\n![image]()\n\n* The important thing is "We can only get any sort of gain IF our branches are not below zero. If they are below zero, why do we even bother considering them? Just pick 0 in that case. Therefore, we do `max(<some gain we might get or not>, 0)`.\n\n# **Going down the recursion stack for one example**\n![image]()\n![image]()\n![image]()\n\n* Because of this, we do `Line 12` and `Line 13`. It is important to understand the different between looking for the maximum path INVOLVING the current node in process and what we return for the node which starts the recursion stack. `Line 12` and `Line 13` takes care of the former issue and `Line 15` (and the image below) takes care of the latter issue.\n\n![image]()\n\n* Because of this fact, we have to return like `Line 15`. For our example, for node 1, which is the recursion call that node 3 does for `max(get_max_gain(node.left), 0)`, node 1 cannot include both node 6 and node 7 for a path to include node 3. Therefore, we can only pick the max gain from left path or right path of node 1.\n\n\n**Python**\n``` python\n1. class Solution:\n2. def maxPathSum(self, root: TreeNode) -> int:\n3. \t\tmax_path = float("-inf") # placeholder to be updated\n4. \t\tdef get_max_gain(node):\n5. \t\t\tnonlocal max_path # This tells that max_path is not a local variable\n6. \t\t\tif node is None:\n7. \t\t\t\treturn 0\n8. \t\t\t\t\n9. \t\t\tgain_on_left = max(get_max_gain(node.left), 0) # Read the part important observations\n10. \t\tgain_on_right = max(get_max_gain(node.right), 0) # Read the part important observations\n11. \t\t\t\n12. \t\tcurrent_max_path = node.val + gain_on_left + gain_on_right # Read first three images of going down the recursion stack\n13. \t\tmax_path = max(max_path, current_max_path) # Read first three images of going down the recursion stack\n14. \t\t\t\n15. \t\treturn node.val + max(gain_on_left, gain_on_right) # Read the last image of going down the recursion stack\n16. \t\t\t\n17. \t\t\t\n18. \tget_max_gain(root) # Starts the recursion chain\n19. \treturn max_path\t\t\n```
12,200
Binary Tree Maximum Path Sum
binary-tree-maximum-path-sum
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree, return the maximum path sum of any non-empty path.
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Hard
null
392
5
# Intuition\nThe problem involves finding the maximum path sum in a binary tree. A path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections.\n\n# Approach\nThe approach is to perform a Depth-First Search (DFS) traversal of the binary tree. At each node, calculate the maximum path sum that includes the current node. Update the global maximum path sum if needed. The DFS function returns the maximum path sum that extends from the current node to its parent.\n\n1. **DFS Function**: Implement a recursive DFS function that calculates the maximum path sum at each node.\n\n **Reason**: Recursive DFS is a natural fit for exploring the tree and updating the maximum path sum.\n\n2. **Base Case**: Check for the base case where the current node is `None`. If true, return `0`.\n\n **Reason**: A `None` node contributes zero to the path sum.\n\n3. **Recursive Calls**: Recursively calculate the maximum path sum for the left and right subtrees.\n\n **Reason**: To explore the entire tree and compute the maximum path sum.\n\n4. **Update Global Maximum**: Update the global maximum path sum considering the current node.\n\n **Reason**: The maximum path sum may include the current node and its left and right subtrees.\n\n5. **Return Maximum Path Sum**: Return the maximum path sum that extends from the current node to its parent.\n\n **Reason**: The DFS function should provide the maximum path sum that includes the current node.\n\n6. **Initial Call**: Perform the initial call to the DFS function with the root of the tree.\n\n **Reason**: Start the DFS traversal from the root.\n\n7. **Return Result**: Return the final result, which represents the maximum path sum in the entire binary tree.\n\n **Reason**: The result should reflect the maximum path sum in the binary tree.\n\n# Complexity\n- **Time complexity**: O(n)\n - The algorithm processes each node once.\n- **Space complexity**: O(h)\n - The recursion stack space is proportional to the height of the tree, where h is the height.\n\n# Code\n\n\n<details open>\n <summary>Python Solution</summary>\n\n```python\nclass Solution:\n def maxPathSum(self, root: Optional[TreeNode]) -> int:\n ans = [root.val]\n\n def DFS(root):\n if root == None:\n return 0\n\n lmax = DFS(root.left)\n rmax = DFS(root.right)\n lmax = 0 if lmax < 0 else lmax\n rmax = 0 if rmax < 0 else rmax\n\n ans[0] = max(ans[0] , root.val + lmax + rmax)\n\n return root.val + max(lmax , rmax) \n\n DFS(root) \n return ans[0] \n \n```\n</details>\n\n<details open>\n <summary>C++ Solution</summary>\n\n```cpp\nclass Solution {\npublic:\n int maxPathSum(TreeNode* root) {\n int maxPath = INT_MIN;\n DFS(root, maxPath);\n return maxPath;\n }\nprivate:\n int DFS(TreeNode* root, int& maxPath) {\n if (root == NULL) {\n return 0;\n }\n \n int lmax = max(DFS(root->left, maxPath), 0);\n int rmax = max(DFS(root->right, maxPath), 0);\n \n maxPath = max(maxPath, root->val + lmax + rmax);\n \n return root->val + max(lmax, rmax);\n }\n};\n```\n</details>\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg]()\n\n\n
12,212
Binary Tree Maximum Path Sum
binary-tree-maximum-path-sum
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree, return the maximum path sum of any non-empty path.
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Hard
null
11,552
102
The idea is to **update node values with the biggest, positive cumulative sum gathered by its children**:\n* If both contributions are negative, no value is added. \n* If both are positive, only the biggest one is added, so that we don\'t include both children during the rest of the tree exploration. \n* Leaves return its own value and we recursively work our way upwards.\n\nA global maximum sum variable is maintained so that **every path can be individually checked**, while updated node values on the tree **allow for exploration of other valid paths outside of the current subtree**. \nMore details in the code comments:\n\n```\nclass Solution:\n def maxPathSum(self, root: TreeNode) -> int:\n self.max_sum = float(\'-inf\')\n self.dfs(root)\n return self.max_sum\n \n def dfs(self, node):\n if not node: return 0\n \n # only add positive contributions\n leftST_sum = max(0, self.dfs(node.left))\n rightST_sum = max(0, self.dfs(node.right))\n\n # check if cumulative sum at current node > global max sum so far\n # this evaluates a candidate path\n self.max_sum = max(self.max_sum, leftST_sum + rightST_sum + node.val)\n \n # add to the current node ONLY one of the children contributions\n # in order to maintain the constraint of considering only paths\n # if not, we would be exploring explore the whole tree - against problem definition\n return max(leftST_sum, rightST_sum) + node.val\n```\n\nThe key is to always choose the maximum cumulative sum path, while updating the "global" maximum value, from the leaves upwards.
12,250
Binary Tree Maximum Path Sum
binary-tree-maximum-path-sum
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree, return the maximum path sum of any non-empty path.
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Hard
null
147
7
The logic for finding the maximum path sum in a binary tree involves traversing the tree in a post-order manner.\n\nAt each node, we consider three scenarios: \n1. the maximum path sum passing through the current node and including its left child\n2. the maximum path sum passing through the current node and including its right child\n3. the maximum path sum being just the value of the current node itself.\n\nWe update the value of each node to represent the maximum path sum possible from that node. \n\nThroughout the traversal, we keep track of the overall maximum path sum found so far and return it as the result.\n\n\n\n\n\n\n# Code\n```\n\nclass Solution:\n def maxPathSum(self, root: Optional[TreeNode]) -> int:\n self.res=root.val\n def traverse_leaf_to_root(root):\n if root is None:\n return\n\n if root.left is None and root.right is None:\n self.res=max(self.res,root.val)\n return\n\n traverse_leaf_to_root(root.left)\n traverse_leaf_to_root(root.right)\n\n vals=[root.val,root.val,root.val]\n cp=root.val\n if root.left:\n vals[1]+=root.left.val\n cp+=root.left.val\n if root.right:\n vals[2]+=root.right.val\n cp+=root.right.val\n root.val=max(vals)\n self.res=max(self.res,max(root.val,cp))\n\n res=root.val\n traverse_leaf_to_root(root)\n return self.res\n\n \n```
12,262
Binary Tree Maximum Path Sum
binary-tree-maximum-path-sum
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree, return the maximum path sum of any non-empty path.
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Hard
null
4,374
20
```\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```\n// just returns the nodes in post-order\npublic Iterable<TreeNode> topSort(TreeNode root) {\n Deque<TreeNode> result = new LinkedList<>();\n if (root != null) {\n Deque<TreeNode> stack = new LinkedList<>();\n stack.push(root);\n while (!stack.isEmpty()) {\n TreeNode curr = stack.pop();\n result.push(curr);\n if (curr.right != null) stack.push(curr.right);\n if (curr.left != null) stack.push(curr.left);\n }\n }\n return result;\n}\n\npublic int maxPathSum(TreeNode root) {\n int result = Integer.MIN_VALUE;\n Map<TreeNode, Integer> maxRootPath = new HashMap<>(); // cache\n maxRootPath.put(null, 0); // for simplicity we want to handle null nodes\n for (TreeNode node : topSort(root)) {\n // as we process nodes in post-order their children are already cached\n int left = Math.max(maxRootPath.get(node.left), 0);\n int right = Math.max(maxRootPath.get(node.right), 0); \n maxRootPath.put(node, Math.max(left, right) + node.val);\n result = Math.max(left + right + node.val, result);\n }\n return result;\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```\nint maxSum(TreeNode* root, int& ans) {\n /* This function return the Branch Sum......\n So if the node is NULL then it won\'t have a branch....so the branch sum will be 0.\n */\n //Base Case\n if(root == NULL){\n return 0;\n }\n \n //Recursive Case \n //BS = Branch Sum\n int leftBS = root->val + maxSum( root->left , ans );\n int rightBS = root->val + maxSum( root->right , ans );\n \n ans = max({\n ans, //we may have found the maximum ans already\n root->val, //may be the current root val is the maximum sum possible\n leftBS, //may be the answer contain root->val + left branch value\n rightBS, //may be the answer contain root->val + right branch value\n leftBS + rightBS - root->val // may be ans conatin left branch + right branch + root->val\n // Since the root val is added twice from leftBS and rightBS so we are sunstracting it.\n });\n \n //Return the max branch Sum\n return max({ leftBS , rightBS , root->val });\n}\n\nint maxPathSum(TreeNode* root) {\n int ans = INT_MIN;\n maxSum(root, ans);\n return ans;\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```\nclass Solution:\n def __init__(self):\n self.maxSum = float(\'-inf\')\n def maxPathSum(self, root: TreeNode) -> int:\n def traverse(root):\n if root:\n left = traverse(root.left)\n right = traverse(root.right)\n self.maxSum = max(self.maxSum,root.val, root.val + left, root.val + right, root.val + left + right)\n return max(root.val,root.val + left,root.val + right)\n else:\n return 0\n traverse(root)\n return self.maxSum\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```\nvar maxPathSum = function(root) {\n var max = -Number.MAX_VALUE;\n getMaxSum(root);\n return max;\n function getMaxSum(node) {\n if (!node) return 0;\n var leftSum = getMaxSum(node.left);\n var rightSum = getMaxSum(node.right);\n max = Math.max(max, node.val + leftSum + rightSum);\n return Math.max(0, node.val + leftSum, node.val + rightSum);\n }\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```\nclass Solution {\n fun maxPathSum(root: TreeNode?) = postorder(root).maxSum\n\n private fun postorder(node: TreeNode?): Res {\n if (node == null)\n return Res(Int.MIN_VALUE, 0)\n\n val (leftMaxSum, leftPathSum) = postorder(node.left)\n val (rightMaxSum, rightPathSum) = postorder(node.right)\n\n val value = node.`val`\n val sum = leftPathSum + rightPathSum + value\n\n return Res(maxOf(leftMaxSum, rightMaxSum, sum), maxOf(0, value + maxOf(leftPathSum, rightPathSum)))\n }\n\n private data class Res(val maxSum: Int, val pathSum: Int)\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 in binary tree.\n // - space: O(n), where n is the number of nodes in binary tree.\n \n func maxPathSum(_ root: TreeNode?) -> Int {\n guard let root = root else { return 0 }\n var currMaxSum = Int.min\n return max(maxPathSum(root, currMaxSum: &currMaxSum), currMaxSum)\n }\n\n \n private func maxPathSum(_ currNode: TreeNode?, currMaxSum: inout Int) -> Int {\n guard let currNode = currNode else { return 0 }\n\n let leftSum = max(maxPathSum(currNode.left, currMaxSum: &currMaxSum), 0)\n let rightSum = max(maxPathSum(currNode.right, currMaxSum: &currMaxSum), 0)\n\n currMaxSum = max(currNode.val + leftSum + rightSum, currMaxSum)\n return max(leftSum, rightSum) + currNode.val\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***
12,284
Valid Palindrome
valid-palindrome
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise.
Two Pointers,String
Easy
null
1,792
8
\n\nTo test if a string is a palindrome, we\'ll use a two pointer approach that starts at the ends of the string. At each step, if the characters at the two pointers are equal, then we\'ll move both pointers inwards and compare the next set of characters. Since a palindrome reads the same forwards and backwards, each pair of characters should be equal at each step.\n\nHowever, for this problem, we also need to ignore non-alphanumeric characters and ignore case. To do this, we\'ll use two Python string methods:\n\nThe `.isalnum()` method returns true if a string is alphanumeric, and returns false otherwise. The `.lower()` method converts the entire string into lowercase characters and returns the result.\n\nSo inside of the `while` loop, we check if the characters at index `l` and `r` are alphanumeric. If they are not, then we skip that character by moving that pointer inwards. Once both characters are alphanumeric, we convert both characters to lowercase and check for equality.\n\nIf both characters are equal to each other, then we can move on to the next set of characters by moving both pointers inwards. If, at this point, they are not equal to each other, then that means that the string is not a palindrome, so we go into the `else` block and just return false immediately.\n\n# Code\n```\nclass Solution:\n def isPalindrome(self, s: str) -> bool:\n l = 0\n r = len(s) - 1\n while l < r:\n if not s[l].isalnum():\n l += 1\n elif not s[r].isalnum():\n r -= 1\n elif s[l].lower() == s[r].lower():\n l += 1\n r -= 1\n else:\n return False\n\n return True\n \n```
12,313
Valid Palindrome
valid-palindrome
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise.
Two Pointers,String
Easy
null
10,348
39
```python3 []\nclass Solution:\n def isPalindrome(self, s: str) -> bool:\n s = [c.lower() for c in s if c.isalnum()]\n return all (s[i] == s[~i] for i in range(len(s)//2))\n```\n```python3 []\nclass Solution:\n def isPalindrome(self, s: str) -> bool:\n i, j = 0, len(s) - 1\n while i < j:\n while i < j and not s[i].isalnum(): i += 1\n while i < j and not s[j].isalnum(): j -= 1\n\n if s[i].lower() != s[j].lower(): return False\n i += 1\n j -= 1\n\n return True\n```\nOperator **~** is the bitwise NOT operator (`~x == -x-1` => `~0 == -1` => `~1 == -2` and etc). It performs [logical negation]() on a given number by flipping all of its bits:\n![not.gif]()\n\n![Screenshot 2023-08-04 at 22.24.01.png]()\n\n### Bonus: problems to practise using operator ~\n[344. Reverse String]()\n```python3 []\nclass Solution:\n def reverseString(self, s: List[str]) -> None:\n for i in range(len(s)//2):\n s[i], s[~i] = s[~i], s[i]\n```\n[1572. Matrix Diagonal Sum]()\n~ using to traverse by matrix antidiagonal (the second diagonal)\n```python3 []\nclass Solution:\n def diagonalSum(self, mat: List[List[int]]) -> int:\n res = 0\n for i in range(len(mat)):\n res = res + mat[i][i] + mat[i][~i]\n\n if (len(mat)) % 2:\n mid = len(mat)//2\n res -= mat[mid][mid]\n \n return res\n```\n\n\n
12,317
Valid Palindrome
valid-palindrome
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise.
Two Pointers,String
Easy
null
5,549
20
# Your upvote is my motivation!\n\n\n# Code\n```\n<!-- Optimize Code -->\n\nclass Solution:\n def isPalindrome(self, s: str) -> bool:\n s1 = \'\'\n for c in s.lower():\n if c.isalnum():\n s1 += c\n\n return True if s1==s1[::-1] else False\n\n============================================================\n<!-- # Practice Code Understand -->\n============================================================\nclass Solution:\n def isPalindrome(self, s: str) -> bool:\n s1 = \'\'\n for c in s.lower():\n if c.isalpha() or c.isnumeric():\n s1 += c\n print(s1)\n\n s = s1[::-1]\n return True if s1==s else False\n```
12,318
Valid Palindrome
valid-palindrome
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise.
Two Pointers,String
Easy
null
12,785
39
# Intuition\nThe code aims to determine whether a given string is a palindrome or not. A palindrome is a string that reads the same forwards and backwards. The code uses two pointers, l and r, to traverse the string from the beginning and end simultaneously. It skips non-alphanumeric characters and compares the corresponding characters at l and r positions. If at any point the characters are not equal, the string is not a palindrome. If the pointers meet or cross each other, the string is a palindrome.\n\n# Approach\n1. Initialize l and r as the left and right pointers.\n2. While l is less than r:\n 1. Increment l until it points to an alphanumeric character.\n 2. Decrement r until it points to an alphanumeric character.\n 3. If l becomes greater than r, return True as the string is a palindrome.\n 4. Compare characters at l and r (case-insensitive):\n 1. If they are not equal, return False as the string is not a palindrome.\n 2. If they are equal, increment l and decrement r.\n3. Return True if the loop completes without finding any mismatch.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n\nSolution 1: (Two Pointers | Beats 99.99%)\n```\nclass Solution:\n def isPalindrome(self, s: str) -> bool:\n l = 0\n r = len(s) - 1\n \n while l < r:\n \n while l < r and s[l].isalnum() == False: \n l += 1\n while r > l and s[r].isalnum() == False: \n r -= 1\n if l > r or s[l].lower() != s[r].lower():\n return False\n else:\n l += 1\n r -= 1\n return True\n \n```\n\nSolution 2: (Simple two liner)\n```\nclass Solution:\n def isPalindrome(self, s: str) -> bool:\n s = [char.lower() for char in s if char.isalnum()]\n return s == s[::-1]\n```\n\nPlease "Upvote" if you find it useful.
12,321
Valid Palindrome
valid-palindrome
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise.
Two Pointers,String
Easy
null
6,278
7
# Intuition\n*two pointers at the start and end and keep shifting as inwards as long as left < right and both the values in string falls under alphanumeric*\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis code checks whether a given string `s` is a palindrome or not. The approach used is to use two pointers, `left` and `right`, starting from the beginning and end of the string respectively, and then move them towards each other until they meet in the middle.\n\nAt each step, we check if the character at the `left` index is alphanumeric. If it\'s not, we move `left` one position to the right. Similarly, if the character at the `right` index is not alphanumeric, we move `right` one position to the left. \n\nIf both the characters at `left` and `right` indices are alphanumeric, we check if they are equal or not. If they are not equal, the string is not a palindrome and we return `False`. Otherwise, we continue moving the pointers towards each other.\n\nIf the pointers meet in the middle of the string and no mismatches have been found, the string is a palindrome and we return `True`.\n\n\n\n# Complexity\n- Time complexity: \n O(n)\n\n- Space complexity:\nO(1)\n\nThe `time complexity` of this code is `O(n)` because we need to traverse the string once. The `space complexity` is `O(1)` because we are not using any extra data structures to store the string.\n\n# Code\n```\nclass Solution:\n def isPalindrome(self, s: str) -> bool:\n left, right = 0, len(s) - 1\n while left < right:\n if not s[left].isalnum():\n left += 1\n elif not s[right].isalnum():\n right -= 1\n elif s[left].lower() != s[right].lower():\n return False\n else:\n left += 1\n right -= 1\n return True\n\n```
12,362
Valid Palindrome
valid-palindrome
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise.
Two Pointers,String
Easy
null
3,837
11
### Upvote if it helps!\n\n# The REGEX:\n<!-- Describe your approach to solving the problem. -->\nLet\'s explain the REGEX expression:\n- ```re.sub(pattern, replaceString)```: *all matching occurrences of the specified pattern are replaced by the replace string (here the empty string because we want to remove).*\n\n- Let\'s explain the **pattern**:\n - ``` [^ ] ```: *Matches a single character not present in the list below.*\n - ```a-zA-Z```: *Matches all the upper case **and** lower case letters.*\n - ```0-9```: *Matches the numbers.*\n - ```\\s+```: *Matches a string of non-whitespace characters*. \n - *Do not forget to add a leading ```\\```, the first one *"ask"* Python not to interpret the next one.*\n\n- Finally, the pattern matches all non-alphanumeric characters and ```re.sub()``` allows us to remove all the occurences from the string.\n- ```new_s[::-1]``` is used to reverse the string.\n\n\n# Code:\n```\nimport re\n\nclass Solution(object):\n def isPalindrome(self, s):\n new_s = re.sub(r"[^a-zA-Z0-9\\\\s+]", "", s).lower()\n return new_s == new_s[::-1]\n```\n\n
12,365
Valid Palindrome
valid-palindrome
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise.
Two Pointers,String
Easy
null
102,595
369
\n def isPalindrome(self, s):\n l, r = 0, len(s)-1\n while l < r:\n while l < r and not s[l].isalnum():\n l += 1\n while l <r and not s[r].isalnum():\n r -= 1\n if s[l].lower() != s[r].lower():\n return False\n l +=1; r -= 1\n return True
12,376
Valid Palindrome
valid-palindrome
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise.
Two Pointers,String
Easy
null
15,336
21
# Intuition:\nThe idea behind this solution is to use two pointers, one starting from the left end of the string (`left`) and the other starting from the right end of the string (`right`). We iterate through the string until the two pointers meet in the middle.\n\n# Approach:\n1. Initialize the `left` pointer to 0 (indicating the start of the string) and the `right` pointer to `s.length()-1` (indicating the end of the string).\n2. Iterate while `left < right`:\n - If `s[left]` is not an alphanumeric character, increment `left` by 1 and move to the next character.\n - If `s[right]` is not an alphanumeric character, decrement `right` by 1 and move to the previous character.\n - If the lowercase of `s[left]` is not equal to the lowercase of `s[right]`, the string is not a palindrome. Return `false`.\n - If the characters are equal, increment `left` by 1 and decrement `right` by 1 to continue checking the next pair of characters.\n3. If the loop completes without returning `false`, it means the string is a palindrome. Return `true`.\n\n# Complexity:\n- The time complexity of this solution is O(n), where n is the length of the input string `s`. We iterate through the string once.\n- The space complexity is O(1) because we are using a constant amount of extra space for the pointers and temporary variables.\n\n---\n# C++\n```\nclass Solution {\npublic:\n bool isPalindrome(string s) {\n \n int left = 0, right = s.length()-1;\n while(left<right)\n { \n if(!isalnum(s[left])) \n left++;\n else if(!isalnum(s[right])) \n right--;\n else if(tolower(s[left])!=tolower(s[right])) \n return false;\n else {\n left++; \n right--;\n }\n }\n return true;\n }\n};\n```\n\n---\n# Java\n```\nclass Solution {\n public boolean isPalindrome(String s) {\n int left = 0, right = s.length() - 1;\n while (left < right) {\n if (!Character.isLetterOrDigit(s.charAt(left)))\n left++;\n else if (!Character.isLetterOrDigit(s.charAt(right)))\n right--;\n else if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right)))\n return false;\n else {\n left++;\n right--;\n }\n }\n return true;\n }\n}\n\n```\n\n---\n# Python\n```\nclass Solution(object):\n def isPalindrome(self, s):\n left, right = 0, len(s) - 1\n while left < right:\n if not s[left].isalnum():\n left += 1\n elif not s[right].isalnum():\n right -= 1\n elif s[left].lower() != s[right].lower():\n return False\n else:\n left += 1\n right -= 1\n return True\n\n```\n---\n# JavaScript\n```\nvar isPalindrome = function(s){\n let left = 0, right = s.length - 1;\n while (left < right) {\n if (!isAlphaNumeric(s[left]))\n left++;\n else if (!isAlphaNumeric(s[right]))\n right--;\n else if (s[left].toLowerCase() !== s[right].toLowerCase())\n return false;\n else {\n left++;\n right--;\n }\n }\n return true;\n}\n\nfunction isAlphaNumeric(char) {\n const code = char.charCodeAt(0);\n return (code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122);\n}\n```
12,383
Valid Palindrome
valid-palindrome
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise.
Two Pointers,String
Easy
null
5,951
6
\nThis simple two liner approach to solving this problem relies on generator comprehension to make this a quick and concise solution.\n\n# Code\n```\n# The first line of code removes all non-alphanumeric characters and converts\n# the whole string to lowercase making it easy to reverse the string cleanly\n# using generator comprehension and storing it in the variable "raw".\n\n# The second line of code is fairly straightforward. It finds out whether or\n# not the reversed form of the "raw" variable is equal to the unreversed\n# form of itself also using generator comprehension.\n\nclass Solution:\n def isPalindrome(self, s: str) -> bool:\n raw = \'\'.join(ch for ch in s if ch.isalnum()).lower()\n return raw[::-1] == raw\n```
12,388
Word Ladder II
word-ladder-ii
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].
Hash Table,String,Backtracking,Breadth-First Search
Hard
null
4,920
79
**Intuition**\n\n1. Most approaches start off with an adjacency list with a pattern node for quick lookups.\n\n1. Then we perform **BFS** until we reach an `endWord`. Since the question requires us to return all possible paths, it is very tempting to start constructing the path during our BFS\n\ta. **However**, this will always give us TLE. Algorithmically, this feels wrong since we need to explore and hit all the nodes at least once to form our path (i.e. `O(n)`).\n\tb. But looking at it more closely, we are creating/destroying paths at every node of a BFS traversal. Space and compute are not free.\n\n1. What if we can defer our path creation to later? That\'s good, but not enough because we would have to start our traversal from `beginWord` all over again.\n\n1. What about the **paths** we traversed via BFS? Most of them led to **dead-ends**. If only we don\'t have to traverse down these paths. **This is the crux of the optimization**. We can do this by traversing in reverse from `endWord` to `beginWord` instead!\n\n1. When we perform **BFS** (step 2), we construct a tree where the key is a `child` node and values are `parent` nodes. When `endWord` is found, the `wordTree` will contain a way to traverse from `endWord` to `beginWord`.\n\n1. Then we perform **DFS** on the `wordTree` and return our results.\n\np.s. this was **HARD** to figure out...rip if anyone ever needs to make this optimization in an interview.\n\n**Solution**\n```\nclass Solution:\n\n WILDCARD = "."\n \n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n """\n Given a wordlist, we perform BFS traversal to generate a word tree where\n every node points to its parent node.\n \n Then we perform a DFS traversal on this tree starting at the endWord.\n """\n if endWord not in wordList:\n # end word is unreachable\n return []\n \n # first generate a word tree from the wordlist\n word_tree = self.getWordTree(beginWord, endWord, wordList)\n \n # then generate a word ladder from the word tree\n return self.getLadders(beginWord, endWord, word_tree)\n \n \n def getWordTree(self,\n beginWord: str,\n endWord: str,\n wordList: List[str]) -> Dict[str, List[str]]:\n """\n BFS traversal from begin word until end word is encountered.\n \n This functions constructs a tree in reverse, starting at the endWord.\n """\n # Build an adjacency list using patterns as keys\n # For example: ".it" -> ("hit"), "h.t" -> ("hit"), "hi." -> ("hit")\n adjacency_list = defaultdict(list)\n for word in wordList:\n for i in range(len(word)):\n pattern = word[:i] + Solution.WILDCARD + word[i+1:]\n adjacency_list[pattern].append(word)\n \n # Holds the tree of words in reverse order\n # The key is an encountered word.\n # The value is a list of preceding words.\n # For example, we got to beginWord from no other nodes.\n # {a: [b,c]} means we got to "a" from "b" and "c"\n visited_tree = {beginWord: []}\n \n # start off the traversal without finding the word\n found = False\n \n q = deque([beginWord])\n while q and not found:\n n = len(q)\n \n # keep track of words visited at this level of BFS\n visited_this_level = {}\n\n for i in range(n):\n word = q.popleft()\n \n for i in range(len(word)):\n # for each pattern of the current word\n pattern = word[:i] + Solution.WILDCARD + word[i+1:]\n\n for next_word in adjacency_list[pattern]:\n if next_word == endWord:\n # we don\'t return immediately because other\n # sequences might reach the endWord in the same\n # BFS level\n found = True\n if next_word not in visited_tree:\n if next_word not in visited_this_level:\n visited_this_level[next_word] = [word]\n # queue up next word iff we haven\'t visited it yet\n # or already are planning to visit it\n q.append(next_word)\n else:\n visited_this_level[next_word].append(word)\n \n # add all seen words at this level to the global visited tree\n visited_tree.update(visited_this_level)\n \n return visited_tree\n \n \n def getLadders(self,\n beginWord: str,\n endWord: str,\n wordTree: Dict[str, List[str]]) -> List[List[str]]:\n """\n DFS traversal from endWord to beginWord in a given tree.\n """\n def dfs(node: str) -> List[List[str]]:\n if node == beginWord:\n return [[beginWord]]\n if node not in wordTree:\n return []\n\n res = []\n parents = wordTree[node]\n for parent in parents:\n res += dfs(parent)\n for r in res:\n r.append(node)\n return res\n\n return dfs(endWord)\n```
12,413
Word Ladder II
word-ladder-ii
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].
Hash Table,String,Backtracking,Breadth-First Search
Hard
null
2,007
21
A key observation of this problem is to convert `wordList` into a graph g = (V, E), where the vertices are all words in `wordList` and `beginWord`, and the edges connect all words that differ by one character. The graph representation of the example testcase is shown below:\n![image]()\n\n\nGiven this graph, we perform a modified BFS traversal to find all shortest paths from start to end words. The psuedo-code for a standard BFS algorithm is:\n![image]()\n\nIn this problem, we modify this algorithm as follows. \n\n\t"""\n\tIn a nutshell, this problem is an advanced graph traversal algorithm. Here, we use BFS to find all shortest paths\n\tfrom beginWord to endWord in a constructed graph g = (V, E). \n\t\t- |V| = k+1 if beginWord is not in wordList and |V| = k otherwise.\n\t\t- an edge (u, v) is in E if and only if wordList[u] and wordList[v] differ by exactly one character.\n\tCheck the docstrings for all the necessary methods for an in-depth explanation of this modified BFS algorithm.\n\t"""\n\n\tfrom typing import List\n\timport math\n\t\n\tdef differ(str1, str2):\n\t\t"""\n\t\tdetermines if two strings differ by one character.\n\t\t"""\n\t\tdiff = 0\n\n\t\tfor i in range(len(str1)):\n\t\t\tif str1[i] != str2[i]:\n\t\t\t\tdiff += 1\n\n\t\treturn diff == 1\n\n\n\tdef convert(words):\n\t\t"""\n\t\tconverts words into the adjacency list representation of a graph, as detailed above.\n\t\t"""\n\t\tedges = []\n\t\tgraph = [[] for _ in range(len(words))]\n\n\t\tfor i in range(len(words)):\n\t\t\tfor j in range(i, len(words)):\n\t\t\t\tif differ(words[i], words[j]):\n\t\t\t\t\tedges.append([i, j])\n\n\t\tfor pair in edges:\n\t\t\tgraph[pair[0]].append(pair[1])\n\t\t\tgraph[pair[1]].append(pair[0])\n\n\t\treturn graph\n\n\n\tdef bfs(graph, start):\n\t\t"""\n\t\tperforms a modified bfs search on graph with start node start.\n\n\t\tReturns:\n\t\t\t- parents, a dictionary that maps each node in the graph to a list of parents that have the shortest distance from the start node.\n\n\t\tstart is the index such that wordList[start] = beginWord\n\t\t"""\n\t\tdist = {start: 0} # dictionary that maps each node in graph to the shortest distance away from start.\n\t\tparents = {start: None}\n\n\t\tfor i in range(len(graph)):\n\t\t\tif i != start:\n\t\t\t\tdist[i] = math.inf\n\t\t\t\tparents[i] = []\n\n\t\tqueue = [start]\n\n\t\twhile queue:\n\t\t\tnode = queue.pop()\n\n\t\t\tfor neighbor in graph[node]:\n\t\t\t\tif dist[neighbor] == math.inf: # neighbor has not been visited yet\n\t\t\t\t\tdist[neighbor] = dist[node] + 1\n\t\t\t\t\tparents[neighbor].append(node)\n\t\t\t\t\tqueue.insert(0, neighbor)\n\n\t\t\t\telse: # neighbor has been visited!\n\t\t\t\t\tif dist[node] + 1 == dist[neighbor]:\n\t\t\t\t\t\tparents[neighbor].append(node)\n\t\t\t\t\telif dist[node] + 1 < dist[neighbor]: # found a quicker path to neighbor\n\t\t\t\t\t\tdist[neighbor] = dist[node] + 1\n\t\t\t\t\t\tparents[neighbor].clear()\n\t\t\t\t\t\tparents[neighbor].append(node)\n\n\t\treturn parents\n\n\n\tdef findPaths(pathList, currPath, currNode, parents, wordList):\n\t\t"""\n\t\ttraces back to find all paths from the end node to the start node given the parents dictionary. Returns nothing,\n\t\tbut modifies the input pathList to include all possible paths.\n\t\t"""\n\t\tif parents[currNode] is None:\n\t\t\tcurrPath.reverse()\n\t\t\tpathList.append(currPath)\n\n\t\tif parents[currNode]:\n\t\t\tfor parent in parents[currNode]:\n\t\t\t\tfindPaths(pathList, currPath + [wordList[parent]], parent, parents, wordList)\n\n\n\tclass Solution:\n\t\tdef findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n\t\t\tif beginWord not in wordList:\n\t\t\t\twordList.append(beginWord)\n\n\t\t\tif endWord not in wordList:\n\t\t\t\treturn []\n\n\t\t\tendIndex = wordList.index(endWord)\n\t\t\tbeginIndex = wordList.index(beginWord)\n\n\t\t\tgraph = convert(wordList)\n\t\t\tparents = bfs(graph, beginIndex)\n\n\t\t\tpathList = []\n\t\t\tcurrPath = [endWord]\n\t\t\tfindPaths(pathList, currPath, endIndex, parents, wordList)\n\n\t\t\treturn pathList\n\n\n\n
12,416
Word Ladder II
word-ladder-ii
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].
Hash Table,String,Backtracking,Breadth-First Search
Hard
null
19,797
215
An intuitive solution is to use BFS to find shorterst transformation path from begin word to end word. A valid transformation is to change any one character and transformed word should be in the a word list.\n\nWhat is tricker than #127 is that we need to find all shortest paths. Thus, we need to build a search tree during BFS and backtrack along that tree to restore all shortest paths. \nSo we can\'t stop BFS once we found a transformed word is endword but instead finishing searching is this BFS layer since there could be more than one shortest path.\nAnd we still need to rule out all node that we have searched previously. Meanwhile if two nodes have a same child node, we need to add that child node to both node\'s children list as we need to backtrack all valid paths. So unlike a regular BFS, we can\'t use a "seen" set but a more like "explored" set. Otherwise, e.g. tree: {x->z, y->z}, z won\'t be added to y\'s children list if x is visited first and z is already seen in x\'s search.\n```\ndef findLadders(beginWord, endWord, wordList):\n\ttree, words, n = collections.defaultdict(set), set(wordList), len(beginWord)\n\tif endWord not in wordList: return []\n\tfound, q, nq = False, {beginWord}, set()\n\twhile q and not found:\n\t\twords -= set(q)\n\t\tfor x in q:\n\t\t\tfor y in [x[:i]+c+x[i+1:] for i in range(n) for c in string.ascii_lowercase]:\n\t\t\t\tif y in words:\n\t\t\t\t\tif y == endWord: \n\t\t\t\t\t\tfound = True\n\t\t\t\t\telse: \n\t\t\t\t\t\tnq.add(y)\n\t\t\t\t\ttree[x].add(y)\n\t\tq, nq = nq, set()\n\tdef bt(x): \n\t\treturn [[x]] if x == endWord else [[x] + rest for y in tree[x] for rest in bt(y)]\n\treturn bt(beginWord)\n```\nThat\'s single one-way BFS which cost more than 2500ms. BFS\'t time complexity is O(b^d) where b is branch factor and d is depth. So if we go with a bi-directional way, expanding from both being word and end word, and choosing the queue (\'begin\' queue or \'end\' queue) with smaller size in each expansion, the branch factor will be greatly reduced.\nAnd bi-directional BFS reducing running time from 2500ms to 100ms!\n```\ndef findLadders(beginWord, endWord, wordList):\n\ttree, words, n = collections.defaultdict(set), set(wordList), len(beginWord)\n\tif endWord not in wordList: return []\n\tfound, bq, eq, nq, rev = False, {beginWord}, {endWord}, set(), False\n\twhile bq and not found:\n\t\twords -= set(bq)\n\t\tfor x in bq:\n\t\t\tfor y in [x[:i]+c+x[i+1:] for i in range(n) for c in string.ascii_lowercase]:\n\t\t\t\tif y in words:\n\t\t\t\t\tif y in eq: \n\t\t\t\t\t\tfound = True\n\t\t\t\t\telse: \n\t\t\t\t\t\tnq.add(y)\n\t\t\t\t\ttree[y].add(x) if rev else tree[x].add(y)\n\t\tbq, nq = nq, set()\n\t\tif len(bq) > len(eq): \n\t\t\tbq, eq, rev = eq, bq, not rev\n\tdef bt(x): \n\t\treturn [[x]] if x == endWord else [[x] + rest for y in tree[x] for rest in bt(y)]\n\treturn bt(beginWord)\n```
12,417
Word Ladder II
word-ladder-ii
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].
Hash Table,String,Backtracking,Breadth-First Search
Hard
null
810
12
This is an implmentation of a solution provided [here]().\n\n**Solution**:\nThe initial instinct is to used BFS to find shortest paths and keep generating partial paths as we go from one level to another. However, this approach would cause TLE because we end up creating and destroying a lot of paths. Thus, we will avoid this problem by performing these three steps:\n\n1. **Adjacency List**: We start by generating adjacency list mapped pattern to words. This approach is better than replacing each character in a word with every lower case alphabets because we avoid checking all 26 alphabets for every character. \n\n```\n i.e. wordList = ["hot","dot","dog","lot","log","cog"]\n adj = {\n \'*ot\': [\'hot\', \'dot\', \'lot\'], \n \'h*t\': [\'hot\'], \n \'ho*\': [\'hot\'], \n \'d*t\': [\'dot\'], \n \'do*\': [\'dot\', \'dog\'], \n \'*og\': [\'dog\', \'log\', \'cog\'], \n \'d*g\': [\'dog\'], \n \'l*t\': [\'lot\'], \n \'lo*\': [\'lot\', \'log\'], \n \'l*g\': [\'log\'], \n \'c*g\': [\'cog\'], \n \'co*\': [\'cog\']\n }\n```\n\n2. **BFS**: Using the adjacency list generated in the previous step, we will traverse such list using BFS from beginWord to endWord and built a reversed adjacency list. The reversed adjacency list will map a word to all words that leading to it. \n\n\tIn order to account for all paths leading to a word while preventing adding duplicate next word to the queue, we will use two sets: Visited and VisitedCurrentLevel. \n\t\n\tVisited set will be used to keep track of all words used in previous levels. Current word that isn\'t in such set will be added to the reversed adjacency list. \nNext, the VisitedCurrentLevel will be used to keep track of all words used in the current level. A next word will only be added to a queue if it doesn\'t exist in such set. \n \n\tAfter processing each level, we will merge the VisitedCurrentLevel set into the Visited set.\n\n```\n i.e. reversedAdj = {\n \'hot\': [\'hit\'], \n \'dot\': [\'hot\'], \n \'lot\': [\'hot\'], \n \'dog\': [\'dot\'], \n \'log\': [\'lot\'], \n \'cog\': [\'dog\', \'log\']\n }\n```\n\n3. **DFS**: Use dfs to traverse the reversed adjacency list from endWord to beginWord and use a single queue to maintain constructed path. We add a next word to the front of the queue before we recursively go to such word and remove such word from the front of queue as we return. Once, the first word is equal to the beginWord, we have succesfully constructed a path. \n\n```\n i.e. res = [\n [\'hit\', \'hot\', \'dot\', \'dog\', \'cog\'], \n [\'hit\', \'hot\', \'lot\', \'log\', \'cog\']\n ]\n```\n\n**Complexity**:\n```\n\tTime:\n\t\t1. AdjacencyList: O(nw) where n is length of wordList and w is the length of each word\n\t\t2. BFS: O(n)\n\t\t3. DFS: O(n)\n\tSpace:\n 1. AdjacencyList: O(nw) where n is length of wordList and w is the length of each word\n 2. BFS: O(n)\n 3. DFS: O(n)\n```\n\n```\nfrom collections import defaultdict, deque\n\n\nclass Solution:\n def findLadders(\n self, beginWord: str, endWord: str, wordList: list[str]\n ) -> list[list[str]]:\n\n # 1. Create adjacency list\n def adjacencyList():\n\n # Initialize the adjacency list\n adj = defaultdict(list)\n\n # Iterate through all words\n for word in wordList:\n\n # Iterate through all characters in a word\n for i, _ in enumerate(word):\n\n # Create the pattern\n pattern = word[:i] + "*" + word[i + 1 :]\n\n # Add a word into the adjacency list based on its pattern\n adj[pattern].append(word)\n\n return adj\n\n # 2. Create reversed adjacency list\n def bfs(adj):\n\n # Initialize the reversed adjacency list\n reversedAdj = defaultdict(list)\n\n # Initialize the queue\n queue = deque([beginWord])\n\n # Initialize a set to keep track of used words at previous level\n visited = set([beginWord])\n\n while queue:\n\n # Initialize a set to keep track of used words at the current level\n visitedCurrentLevel = set()\n\n # Get the number of words at this level\n n = len(queue)\n\n # Iterate through all words\n for _ in range(n):\n\n # Pop a word from the front of the queue\n word = queue.popleft()\n\n # Generate pattern based on the current word\n for i, _ in enumerate(word):\n\n pattern = word[:i] + "*" + word[i + 1 :]\n\n # Itereate through all next words\n for nextWord in adj[pattern]:\n\n # If the next word hasn\'t been used in previous levels\n if nextWord not in visited:\n\n # Add such word to the reversed adjacency list\n reversedAdj[nextWord].append(word)\n\n # If the next word hasn\'t been used in the current level\n if nextWord not in visitedCurrentLevel:\n\n # Add such word to the queue\n queue.append(nextWord)\n\n # Mark such word as visited\n visitedCurrentLevel.add(nextWord)\n\n # Once we done with a level, add all words visited at this level to the visited set\n visited.update(visitedCurrentLevel)\n\n # If we visited the endWord, end the search\n if endWord in visited:\n break\n\n return reversedAdj\n\n # 3. Construct paths based on the reversed adjacency list using DFS\n def dfs(reversedAdj, res, path):\n\n # If the first word in a path is beginWord, we have succesfully constructed a path\n if path[0] == beginWord:\n\n # Add such path to the result\n res.append(list(path))\n\n return res\n\n # Else, get the first word in a path\n word = path[0]\n\n # Find next words using the reversed adjacency list\n for nextWord in reversedAdj[word]:\n\n # Add such next word to the path\n path.appendleft(nextWord)\n\n # Recursively go to the next word\n dfs(reversedAdj, res, path)\n\n # Remove such next word from the path\n path.popleft()\n\n # Return the result\n return res\n\n # Do all three steps\n adj = adjacencyList()\n reversedAdj = bfs(adj)\n res = dfs(reversedAdj, [], deque([endWord]))\n\n return res\n```
12,424
Word Ladder II
word-ladder-ii
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].
Hash Table,String,Backtracking,Breadth-First Search
Hard
null
7,086
46
# Intuition\nWe just need to record all possible words that can connect from the beginning, level by level, until we hit the end at a level.\n\n![image]()\n\nThen we will traverse backward from end via the words in the record and construct our final ways.\n\n**Remember:** we will not record paths, we record only nodes. \n\n_____\n# Explanation\nFirst, because we traverse level by level, so as soon as we see the end, that is the shortest distance (shortest path) we have from beginning. This is the basic theorem of BFS in an unweighted graph: \n\nWhen we see the end, we know some of the nodes from previous level (which connect to the beginning because we traversed from there) are pointing to the end. We just need to move backward, level by level then we could collect all paths to end from begin\n_____\n# Why Other\'s Solutions Get TLE\nBecause if there are some nodes point to a same node, their solutions keep computing the same path again and again due to they see those paths are different (from the beginning node). This is the weakness of recording paths, instead of nodes.\n\nCheck the red node in the following figure for more information:\n\n![image]()\n\nIn summary:\n1. Other solutions:\n\t* Store paths, so every node could be stored multiple times.\n\t* Compute the intersections in paths again and again\n\t* Paths that does not lead to end also be computed\n2. My solution:\n\t* Store only nodes so every node is store exactly one time\n\t* Move backward to compute only the paths that can connect from begin to end\n\n_____\n# Algorithm\n* **Moving Forward: start from begin**\n\t1. Each level, find all connected nodes to the nodes of the current level in the record and add those to the record for the next level.\n\t2. Delete node from wordList to prevent revisiting and forming cycles\n\t3. Repeat the above steps until we reach end or we add no new nodes to the record for next level\n\n* **Moving Backward: start from end**\n\t1. Do the same steps as moving forward but this time we will not record nodes but contruct our paths\n\t2. Construct paths in reversing order to have paths from begin to end\n_____\n\n# Codes\n_____\n\n## JavaScript\n\n```\nvar findLadders = function(beginWord, endWord, wordList) {\n // to check if two words can connect\n let connected = (a,b) => {\n let c = 0\n for (let i = 0; i < a.length && c < 2; i++) {\n if (a[i] !== b[i]) c++\n }\n return c == 1\n }\n\n // dictionary to help us search words faster\n // and to trackback what word was used\n let dict = new Set(wordList);\n if (dict.has(endWord) == false) return []\n\n dict.delete(beginWord)\n let queue = [beginWord]\n let nodes = []\n\n \n // find all ways from beginning\n // level by level, until reach end at a level\n let reached = false; \n while (queue.length && !reached) {\n // update nodes of paths for this level\n nodes.push(queue.slice())\n\n // access whole level \n let qlen = queue.length;\n for (let i = 0; i < qlen && !reached; i++) {\n\n let from = queue.shift();\n \n // find all nodes that connect to the nodes of this level\n for (let to of dict) { \n\n if (connected(from,to) == false) continue\n\n // if connect\n // - and one of them is end word\n // - then we can stop moving forward\n if (to == endWord) {\n reached = true\n break;\n }\n\n // - otherwise,\n // - add all connected nodes to the record for the next level\n // - and delete them from dict to prevent revisiting to form cycles\n queue.push(to) \n dict.delete(to) \n }\n }\n }\n\n // try but did not find endWord\n if (!reached) return []\n\n // move backward to construct paths\n // add nodes to paths in reverse order to have paths from begin to end\n let ans = [[endWord]]\n for (let level = nodes.length - 1; level >= 0; level--) { \n let alen = ans.length\n for (let a = 0; a < alen; a++) {\n let p = ans.shift()\n let last = p[0] \n for (let word of nodes[level]) { \n if (!connected(last, word)) continue \n ans.push([word, ...p])\n }\n } \n }\n\n return ans\n}\n```\n\n____\n## C++\nThis is my first C++ code. Hope you can suggest optimizations . Thanks.\n```\nclass Solution {\npublic:\n bool isConnected(string s,string t){\n int c=0;\n for(int i=0;i<s.length();i++)\n c+=(s[i]!=t[i]);\n return c==1;\n }\n\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n vector<vector<string>> ans; \n vector<vector<string>> nodes; \n unordered_set<string> dict(wordList.begin(),wordList.end());\n \n if (!dict.count(endWord)) return ans;\n dict.erase(beginWord);\n \n \n bool reached = false;\n nodes.push_back({beginWord});\n \n while (dict.size() && !reached) { \n vector<string> last = nodes.back();\n vector<string> curr;\n \n for (int i = 0; i < last.size() && !reached; i++) {\n unordered_set<string> visited;\n string from = last[i]; \n // check all nodes that connect\n // to the nodes of the previous level \n for (auto& to : dict) { \n if (visited.count(to)) continue;\n if (!isConnected(from, to)) continue; \n // if one of them is "endWord" then we can stop \n // because this level is the shortest distance from begin\n if (to == endWord) { \n reached = true; \n break;\n }\n \n // otherwise,\n // add nodes for the current level\n curr.push_back(to); \n visited.insert(to); \n } \n // delete the visited to prevent forming cycles \n for (auto& visited : visited) { \n dict.erase(visited);\n }\n }\n \n // found endWord this level\n if (reached) break;\n \n // can not add any new nodes to our level\n if (!curr.size()) break;\n \n // otherwise, record all nodes for the current level\n nodes.push_back(curr); \n }\n \n // try but not find\n if (reached == false) return ans;\n \n // move backward\n ans.push_back({endWord}); \n for (int level = nodes.size() - 1; level >= 0; level--) { \n int alen = ans.size();\n while (alen) {\n vector<string> path = ans.back();\n ans.pop_back();\n string from = path.front(); \n for (string &to : nodes[level]) { \n if (!isConnected(from, to)) continue;\n \n vector<string> newpath = path;\n newpath.insert(newpath.begin(), to);\n ans.insert(ans.begin(), newpath);\n } \n alen--;\n } \n }\n return ans;\n }\n};\n```\n____\n## Pseudocode\n```\n// Pseudocode\nfunction findLadders(beginWord, endWord, wordList) {\n if (wordList.hasNo(endWord)) return []\n wordList.delete(beginWord)\n\n // move forward\n queue = [beginWord]\n paths = [] // 2D array\n reached = false; \n while (queue.length && !reached) {\n paths.append(queue) // deep copy\n \n // need static here to access only the nodes of this level\n qlen = queue.length; \n for (let i = 0; i < qlen && !reached; i++) {\n from = queue.takeFirst()\n forEach (to of wordList) {\n if (isConnected(from, to)) { \n if (to == endWord) {\n reached = true\n break // exit from the forEach\n }\n \n queue.push(to) \n wordList.delete(to) // delete to preven a cycle \n }\n }\n }\n }\n\n // can not reach the end eventually\n if (!reached) return []\n\n // move backward\n answer = [[endWord]] // 2D array \n for (level = paths.length - 1; level >= 0; level--) { \n path = paths[level]\n alen = answer.length\n for (a = 0; a < alen; a++) {\n p = answer.takeFirst()\n last = p[0]\n forEach (word of path) {\n if (!isConnected(last, word)) {\n answer.append([word, ...p])\n }\n \n }\n } \n }\n\n return answer\n}\n\n\n// to check if two words can connect\nfunction isConnected(a,b) {\n c = 0\n for (i = 0; i < a.length && c < 2; i++) {\n if (a[i] !== b[i]) c++\n }\n return c == 1\n}\n```\n\n____\n
12,427
Word Ladder II
word-ladder-ii
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].
Hash Table,String,Backtracking,Breadth-First Search
Hard
null
12,095
119
Solution 1, BFS, directly store the path in queue. 318 ms, 18.7 MB\nSolution 2, BFS to build graph (parents), DFS to get the shortest path, 356 ms, 20.6 MB\nSolution 3, biBFS to build graph (parents), DFS to get the shortest path, 224 ms, 18.9 MB\nNote that: propocessing words as below will greatly improve the algorithm speed. \n``` python\n# Dictionary to hold combination of words that can be formed,\n# from any given word. By changing one letter at a time.\nall_combo_dict = collections.defaultdict(list)\nfor word in wordList:\n\tfor i in range(L):\n\t\tall_combo_dict[word[:i] + "*" + word[i+1:]].append(word)\n```\n\n``` python \n## Solution 1\ndef findLadders(self, beginWord, endWord, wordList):\n\tif not endWord or not beginWord or not wordList or endWord not in wordList \\\n\t\tor beginWord == endWord:\n\t\treturn []\n\n\tL = len(beginWord)\n\n\t# Dictionary to hold combination of words that can be formed,\n\t# from any given word. By changing one letter at a time.\n\tall_combo_dict = collections.defaultdict(list)\n\tfor word in wordList:\n\t\tfor i in range(L):\n\t\t\tall_combo_dict[word[:i] + "*" + word[i+1:]].append(word)\n\n\t# Shortest path, BFS\n\tans = []\n\tqueue = collections.deque()\n\tqueue.append((beginWord, [beginWord]))\n\tvisited = set([beginWord])\n\t\n\twhile queue and not ans:\n\t\t# print(queue)\n\t\tlength = len(queue)\n\t\t# print(queue)\n\t\tlocalVisited = set()\n\t\tfor _ in range(length):\n\t\t\tword, path = queue.popleft()\n\t\t\tfor i in range(L):\n\t\t\t\tfor nextWord in all_combo_dict[word[:i] + "*" + word[i+1:]]:\n\t\t\t\t\tif nextWord == endWord:\n\t\t\t\t\t\t# path.append(endword)\n\t\t\t\t\t\tans.append(path+[endWord])\n\t\t\t\t\tif nextWord not in visited:\n\t\t\t\t\t\tlocalVisited.add(nextWord)\n\t\t\t\t\t\tqueue.append((nextWord, path+[nextWord]))\n\t\tvisited = visited.union(localVisited)\n\treturn ans\n```\n\n```python \n## Solution 2\ndef findLadders(self, beginWord, endWord, wordList):\n\t"""\n\t:type beginWord: str\n\t:type endWord: str\n\t:type wordList: List[str]\n\t:rtype: List[List[str]]\n\t"""\n\tif not endWord or not beginWord or not wordList or endWord not in wordList \\\n\t\tor beginWord == endWord:\n\t\treturn []\n\n\tL = len(beginWord)\n\n\t# Dictionary to hold combination of words that can be formed,\n\t# from any given word. By changing one letter at a time.\n\tall_combo_dict = collections.defaultdict(list)\n\tfor word in wordList:\n\t\tfor i in range(L):\n\t\t\tall_combo_dict[word[:i] + "*" + word[i+1:]].append(word)\n\n\t# Build graph, BFS\n\t# ans = []\n\tqueue = collections.deque()\n\tqueue.append(beginWord)\n\tparents = collections.defaultdict(set)\n\tvisited = set([beginWord])\n\tfound = False \n\tdepth = 0\n\twhile queue and not found:\n\t\tdepth += 1 \n\t\tlength = len(queue)\n\t\t# print(queue)\n\t\tlocalVisited = set()\n\t\tfor _ in range(length):\n\t\t\tword = queue.popleft()\n\t\t\tfor i in range(L):\n\t\t\t\tfor nextWord in all_combo_dict[word[:i] + "*" + word[i+1:]]:\n\t\t\t\t\tif nextWord == word:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif nextWord not in visited:\n\t\t\t\t\t\tparents[nextWord].add(word)\n\t\t\t\t\t\tif nextWord == endWord: \n\t\t\t\t\t\t\tfound = True\n\t\t\t\t\t\tlocalVisited.add(nextWord)\n\t\t\t\t\t\tqueue.append(nextWord)\n\t\tvisited = visited.union(localVisited)\n\t# print(parents)\n\t# Search path, DFS\n\tans = []\n\tdef dfs(node, path, d):\n\t\tif d == 0:\n\t\t\tif path[-1] == beginWord:\n\t\t\t\tans.append(path[::-1])\n\t\t\treturn \n\t\tfor parent in parents[node]:\n\t\t\tpath.append(parent)\n\t\t\tdfs(parent, path, d-1)\n\t\t\tpath.pop()\n\tdfs(endWord, [endWord], depth)\n\treturn ans\n```\n\n``` python\n## Solution 3\ndef findLadders(self, beginWord, endWord, wordList):\n\t"""\n\t:type beginWord: str\n\t:type endWord: str\n\t:type wordList: List[str]\n\t:rtype: List[List[str]]\n\t"""\n\tif not endWord or not beginWord or not wordList or endWord not in wordList \\\n\t\tor beginWord == endWord:\n\t\treturn []\n\n\tL = len(beginWord)\n\n\t# Dictionary to hold combination of words that can be formed,\n\t# from any given word. By changing one letter at a time.\n\tall_combo_dict = collections.defaultdict(list)\n\tfor word in wordList:\n\t\tfor i in range(L):\n\t\t\tall_combo_dict[word[:i] + "*" + word[i+1:]].append(word)\n\n\t# Build graph, bi-BFS\n\t# ans = []\n\tbqueue = collections.deque()\n\tbqueue.append(beginWord)\n\tequeue = collections.deque()\n\tequeue.append(endWord)\n\tbvisited = set([beginWord])\n\tevisited = set([endWord])\n\trev = False \n\t#graph\n\tparents = collections.defaultdict(set)\n\tfound = False \n\tdepth = 0\n\twhile bqueue and not found:\n\t\tdepth += 1 \n\t\tlength = len(bqueue)\n\t\t# print(queue)\n\t\tlocalVisited = set()\n\t\tfor _ in range(length):\n\t\t\tword = bqueue.popleft()\n\t\t\tfor i in range(L):\n\t\t\t\tfor nextWord in all_combo_dict[word[:i] + "*" + word[i+1:]]:\n\t\t\t\t\tif nextWord == word:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif nextWord not in bvisited:\n\t\t\t\t\t\tif not rev:\n\t\t\t\t\t\t\tparents[nextWord].add(word)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tparents[word].add(nextWord)\n\t\t\t\t\t\tif nextWord in evisited: \n\t\t\t\t\t\t\tfound = True\n\t\t\t\t\t\tlocalVisited.add(nextWord)\n\t\t\t\t\t\tbqueue.append(nextWord)\n\t\tbvisited = bvisited.union(localVisited)\n\t\tbqueue, bvisited, equeue, evisited, rev = equeue, evisited, bqueue, bvisited, not rev\n\t# print(parents)\n\t# print(depth)\n\t# Search path, DFS\n\tans = []\n\tdef dfs(node, path, d):\n\t\tif d == 0:\n\t\t\tif path[-1] == beginWord:\n\t\t\t\tans.append(path[::-1])\n\t\t\treturn \n\t\tfor parent in parents[node]:\n\t\t\tpath.append(parent)\n\t\t\tdfs(parent, path, d-1)\n\t\t\tpath.pop()\n\tdfs(endWord, [endWord], depth)\n\treturn ans\n```
12,431
Word Ladder II
word-ladder-ii
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].
Hash Table,String,Backtracking,Breadth-First Search
Hard
null
4,854
40
# Don\'t Forget To Upvote\n\n# 1. 97.81% Faster Solution:\n\n\t\tclass Solution:\n\t\t\tdef findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n\t\t\t\td = defaultdict(list)\n\t\t\t\tfor word in wordList:\n\t\t\t\t\tfor i in range(len(word)):\n\t\t\t\t\t\td[word[:i]+"*"+word[i+1:]].append(word)\n\n\t\t\t\tif endWord not in wordList:\n\t\t\t\t\treturn []\n\n\t\t\t\tvisited1 = defaultdict(list)\n\t\t\t\tq1 = deque([beginWord])\n\t\t\t\tvisited1[beginWord] = []\n\n\t\t\t\tvisited2 = defaultdict(list)\n\t\t\t\tq2 = deque([endWord])\n\t\t\t\tvisited2[endWord] = []\n\n\t\t\t\tans = []\n\t\t\t\tdef dfs(v, visited, path, paths):\n\t\t\t\t\tpath.append(v)\n\t\t\t\t\tif not visited[v]:\n\t\t\t\t\t\tif visited is visited1:\n\t\t\t\t\t\t\tpaths.append(path[::-1])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tpaths.append(path[:])\n\t\t\t\t\tfor u in visited[v]:\n\t\t\t\t\t\tdfs(u, visited, path, paths)\n\t\t\t\t\tpath.pop()\n\n\t\t\t\tdef bfs(q, visited1, visited2, frombegin):\n\t\t\t\t\tlevel_visited = defaultdict(list)\n\t\t\t\t\tfor _ in range(len(q)):\n\t\t\t\t\t\tu = q.popleft()\n\n\t\t\t\t\t\tfor i in range(len(u)):\n\t\t\t\t\t\t\tfor v in d[u[:i]+"*"+u[i+1:]]:\n\t\t\t\t\t\t\t\tif v in visited2:\n\t\t\t\t\t\t\t\t\tpaths1 = []\n\t\t\t\t\t\t\t\t\tpaths2 = []\n\t\t\t\t\t\t\t\t\tdfs(u, visited1, [], paths1)\n\t\t\t\t\t\t\t\t\tdfs(v, visited2, [], paths2)\n\t\t\t\t\t\t\t\t\tif not frombegin:\n\t\t\t\t\t\t\t\t\t\tpaths1, paths2 = paths2, paths1\n\t\t\t\t\t\t\t\t\tfor a in paths1:\n\t\t\t\t\t\t\t\t\t\tfor b in paths2:\n\t\t\t\t\t\t\t\t\t\t\tans.append(a+b)\n\t\t\t\t\t\t\t\telif v not in visited1:\n\t\t\t\t\t\t\t\t\tif v not in level_visited:\n\t\t\t\t\t\t\t\t\t\tq.append(v)\n\t\t\t\t\t\t\t\t\tlevel_visited[v].append(u)\n\t\t\t\t\tvisited1.update(level_visited)\n\n\t\t\t\twhile q1 and q2 and not ans:\n\t\t\t\t\tif len(q1) <= len(q2):\n\t\t\t\t\t\tbfs(q1, visited1, visited2, True)\n\t\t\t\t\telse:\n\t\t\t\t\t\tbfs(q2, visited2, visited1, False)\n\n\t\t\t\treturn ans\n\t\t\t\t\n\t\t\t\t\n# 2. 87% fast solution a little different approach:\n\n\n\t\tclass Solution:\n\t\t\tdef findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n\t\t\t\tres = []\n\t\t\t\tedge = collections.defaultdict(set)\n\t\t\t\twordList = set(wordList)\n\t\t\t\tfor word in wordList:\n\t\t\t\t\tfor i in range(len(word)):\n\t\t\t\t\t\tedge[word[:i] +\'*\'+word[i+1:]].add(word)\n\t\t\t\tbfsedge = {}\n\n\t\t\t\tdef bfs():\n\t\t\t\t\tminl = 0\n\t\t\t\t\tqueue = set()\n\t\t\t\t\tqueue.add(beginWord)\n\t\t\t\t\twhile queue:\n\t\t\t\t\t\tnext_queue = set()\n\t\t\t\t\t\tfor word in queue:\n\t\t\t\t\t\t\tif word in wordList:\n\t\t\t\t\t\t\t\twordList.remove(word)\n\t\t\t\t\t\tbfsedge[minl] = collections.defaultdict(set)\n\t\t\t\t\t\tfor word in queue:\n\t\t\t\t\t\t\tif word == endWord:\n\t\t\t\t\t\t\t\treturn minl\n\t\t\t\t\t\t\tfor i in range(len(word)):\n\t\t\t\t\t\t\t\tfor w in edge[word[:i]+\'*\'+word[i+1:]]:\n\t\t\t\t\t\t\t\t\tif w in wordList:\n\t\t\t\t\t\t\t\t\t\tnext_queue.add(w)\n\t\t\t\t\t\t\t\t\t\tbfsedge[minl][w].add(word)\n\t\t\t\t\t\tqueue = next_queue\n\t\t\t\t\t\tminl += 1\n\t\t\t\t\treturn minl\n\n\t\t\t\tdef dfs(seq, endWord):\n\t\t\t\t\tif seq[-1] == endWord:\n\t\t\t\t\t\tres.append(seq.copy())\n\t\t\t\t\t\treturn\n\t\t\t\t\tfor nextWord in bfsedge[minl-len(seq)][seq[-1]]:\n\t\t\t\t\t\tif nextWord not in seq:\n\t\t\t\t\t\t\tdfs(seq+[nextWord], endWord)\n\n\t\t\t\tminl = bfs()\n\t\t\t\tdfs([endWord], beginWord)\n\t\t\t\t# reverse the sequence\n\t\t\t\tfor sq in res:\n\t\t\t\t\tsq.reverse()\n\t\t\t\treturn res\n\t\t\t\t\n\t\t\t\t\n# 3.95% Memory efficient solution:\n\t\tfrom collections import deque\n\t\tclass Solution:\n\t\t\tdef findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n\t\t\t\tif endWord not in wordList:return []\n\t\t\t\twordList.append(beginWord)\n\t\t\t\twordList.append(endWord)\n\t\t\t\tdistance = {}\n\n\n\t\t\t\tself.bfs(endWord, distance, wordList)\n\n\t\t\t\tresults = []\n\t\t\t\tself.dfs(beginWord, endWord, distance, wordList, [beginWord], results)\n\n\t\t\t\treturn results\n\n\t\t\tdef bfs(self, start, distance, w):\n\t\t\t\tdistance[start] = 0\n\t\t\t\tqueue = deque([start])\n\t\t\t\twhile queue:\n\t\t\t\t\tword = queue.popleft()\n\t\t\t\t\tfor next_word in self.get_next_words(word, w):\n\t\t\t\t\t\tif next_word not in distance:\n\t\t\t\t\t\t\tdistance[next_word] = distance[word] + 1\n\t\t\t\t\t\t\tqueue.append(next_word)\n\n\t\t\tdef get_next_words(self, word, w):\n\t\t\t\twords = []\n\t\t\t\tfor i in range(len(word)):\n\t\t\t\t\tfor c in \'abcdefghijklmnopqrstuvwxyz\':\n\t\t\t\t\t\tnext_word = word[:i] + c + word[i + 1:]\n\t\t\t\t\t\tif next_word != word and next_word in w:\n\t\t\t\t\t\t\twords.append(next_word)\n\t\t\t\treturn words\n\n\t\t\tdef dfs(self, curt, target, distance, w, path, results):\n\t\t\t\tif curt == target:\n\t\t\t\t\tresults.append(list(path))\n\t\t\t\t\treturn\n\n\t\t\t\tfor word in self.get_next_words(curt, w):\n\t\t\t\t\tif distance[word] != distance[curt] - 1:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tpath.append(word)\n\t\t\t\t\tself.dfs(word, target, distance, w, path, results)\n\t\t\t\t\tpath.pop()\n
12,439
Word Ladder II
word-ladder-ii
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].
Hash Table,String,Backtracking,Breadth-First Search
Hard
null
399
9
```\nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n wordDict = defaultdict(set)\n for word in wordList:\n if word != beginWord:\n for i in range(len(word)):\n wordDict[word[:i] + "*" + word[i+1:]].add(word)\n queue = deque([beginWord])\n visited = {beginWord: 1}\n parent_list = defaultdict(set)\n ans_path = []\n # print(wordDict)\n \n while queue:\n word = queue.popleft()\n if word == endWord: \n break\n for i in range(len(word)):\n for next_word in wordDict[word[:i] + "*" + word[i+1:]]:\n if next_word not in visited:\n visited[next_word] = visited[word] + 1\n queue.append(next_word)\n parent_list[next_word].add(word)\n elif visited[next_word] > visited[word]:\n parent_list[next_word].add(word)\n \n def dfs(word, path):\n if word == beginWord:\n ans_path.append(path[::-1])\n for next_word in parent_list[word]:\n dfs(next_word, path+[next_word])\n \n dfs(endWord, [endWord])\n return ans_path\n```
12,457
Word Ladder
word-ladder
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
Hash Table,String,Breadth-First Search
Hard
null
13,799
134
```\nInput:\nbeginWord = "hit",\nendWord = "cog",\nwordList = ["hot","dot","dog","lot","log","cog"]\nOutput: 5\n```\n1. Only one letter can be changed at a time.\nIn the example, from begin word, you can change one letter in 3 ways. 3 is the length of the word.\n```\n\t\t\t\t hit\n\t\t / | \\\n\t\t *it h*t hi*\n\t\t /|\\ /|\\ /|\\ \n# In order to continue the Breath First Search(BFS) process,\n# we need to know the children of *it, h*t, and hi*.\n# so we need the information from word list.\n```\n2. Each transformed word must exist in the word list.\n\tIn the example, we need to record all the possible changes that could be made from the word list so that we can have the information to do BFS in the graph above. We use a map to store the data. The key is one-letter-change-word, for example," *it," the value is the word meet the key\'s condition in the word list.\n```\nwordList = ["hot","dot","dog","lot","log","cog"]\nchange_map ={ *ot : hot, dot, lot\n\t\t\th*t : hot\n\t\t\tho* :hot\n\t\t\td*t : dot\n\t\t\tdo* : dot, dog\n\t\t\t*og : dog, log, cog\n\t\t\td*g : dog\n\t\t\tl*t : lot\n\t\t\tlo* : lot, log\n\t\t\tl*g : log\n\t\t\tc*g: cog\n\t\t\tco* : cog \n\t\t\t}\n```\n\nWith the information in change_map, we got the information to expand the breadth first search tree.\n```\n\t\t\t\t\t\t\t\t\t\t\t hit, level = 1\n\t\t\t\t\t\t\t\t / | \\\n\t\t\t\t\t *it h*t hi*\n\t\t\t\t\t\t | | | \n\t\t\t null \t hot ,level = 2 null\n\t\t\t\t\t\t\t\t\t\t / | \\ \n\t\t\t\t\t\t\t\t\t\t/ | \\\n\t\t\t\t *ot h*t ho*\n\t\t\t\t / | \\ | |\n hot,2 dot,3 lot,3 hot,2 hot,2\t\t\t\t\t\n\n\n# as we can see, "hot" has been visited in level 2, but "hot" will still appear at the next level. \n# To avoid duplicate calculation, \n# we keep a visited map, \n# if the word in the visited map, we skip the word, i.e. don\'t append the word into the queue.\n# if the word not in the visited map, we put the word into the map, and append the word into the queue.\n```\n```\nfrom collections import defaultdict\nfrom collections import deque\nclass Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n """\n :type beginWord: str\n :type endWord: str\n :type wordList: List[str]\n :rtype: int\n """\n if endWord not in wordList or not endWord or not beginWord or not wordList:\n return 0\n L = len(beginWord)\n all_combo_dict = defaultdict(list)\n for word in wordList:\n for i in range(L):\n all_combo_dict[word[:i] + "*" + word[i+1:]].append(word) \n queue = deque([(beginWord, 1)])\n visited = set()\n visited.add(beginWord)\n while queue:\n current_word, level = queue.popleft()\n for i in range(L):\n intermediate_word = current_word[:i] + "*" + current_word[i+1:]\n for word in all_combo_dict[intermediate_word]:\n if word == endWord:\n return level + 1\n if word not in visited:\n visited.add(word)\n queue.append((word, level + 1))\n return 0\n```
12,528
Word Ladder
word-ladder
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
Hash Table,String,Breadth-First Search
Hard
null
45,251
183
from collections import deque\n \n \n class Solution(object):\n def ladderLength(self, beginWord, endWord, wordList):\n \n def construct_dict(word_list):\n d = {}\n for word in word_list:\n for i in range(len(word)):\n s = word[:i] + "_" + word[i+1:]\n d[s] = d.get(s, []) + [word]\n return d\n \n def bfs_words(begin, end, dict_words):\n queue, visited = deque([(begin, 1)]), set()\n while queue:\n word, steps = queue.popleft()\n if word not in visited:\n visited.add(word)\n if word == end:\n return steps\n for i in range(len(word)):\n s = word[:i] + "_" + word[i+1:]\n neigh_words = dict_words.get(s, [])\n for neigh in neigh_words:\n if neigh not in visited:\n queue.append((neigh, steps + 1))\n return 0\n \n d = construct_dict(wordList | set([beginWord, endWord]))\n return bfs_words(beginWord, endWord, d)
12,532
Word Ladder
word-ladder
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
Hash Table,String,Breadth-First Search
Hard
null
1,744
9
```\ndef ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n wordList=set(wordList)\n if endWord not in wordList:\n return 0\n q=deque()\n q.append((beginWord,1))\n while q:\n word,step=q.popleft()\n for i in range(len(beginWord)):\n for j in range(26):\n new=word[:i]+chr(97+j)+word[i+1:]\n if new==endWord:\n return step+1\n if new in wordList:\n q.append((new,step+1))\n wordList.remove(new)\n return 0\n```\n\n**An upvote will be encouraging**
12,556
Word Ladder
word-ladder
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
Hash Table,String,Breadth-First Search
Hard
null
1,381
5
```\nclass Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n if endWord not in wordList:\n return 0\n nei=defaultdict(list)\n wordList.append(beginWord)\n for word in wordList:\n for j in range(len(word)):\n pattern=word[:j]+"*"+word[j+1:]\n nei[pattern].append(word)\n visit=set([beginWord])\n q=deque([beginWord])\n count=1\n while q:\n for i in range(len(q)):\n word=q.popleft()\n if word==endWord:\n return count\n for j in range(len(word)):\n pattern=word[:j]+"*"+word[j+1:]\n for neiword in nei[pattern]:\n if neiword not in visit:\n visit.add(neiword)\n q.append(neiword)\n count+=1\n return 0 \n ```\n # please upvote me it would encourage me alot\n
12,557
Word Ladder
word-ladder
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
Hash Table,String,Breadth-First Search
Hard
null
31,531
100
The idea behind the first solution is to use character flopping plus bidirectional BFS. Use set operations as much as possible.\n\n class Solution:\n # @param {string} beginWord\n # @param {string} endWord\n # @param {set<string>} wordDict\n # @return {integer}\n def ladderLength(self, beginWord, endWord, wordDict):\n length = 2\n front, back = set([beginWord]), set([endWord])\n wordDict.discard(beginWord)\n while front:\n # generate all valid transformations\n front = wordDict & (set(word[:index] + ch + word[index+1:] for word in front \n for index in range(len(beginWord)) for ch in 'abcdefghijklmnopqrstuvwxyz'))\n if front & back:\n # there are common elements in front and back, done\n return length\n length += 1\n if len(front) > len(back):\n # swap front and back for better performance (fewer choices in generating nextSet)\n front, back = back, front\n # remove transformations from wordDict to avoid cycle\n wordDict -= front\n return 0\n\nThe optimizations:\n\n-- Generating next set\n\n An alternative is to immediately add a candidate to next set if it is in the dictionary.\n\n Another way to generate next set: for each word in the current set, check if a word in the dictionary can be transformed to it. If it can, add it to the next set. The time complexity of the two methods is analyzed below, assuming word length is L, size of current set and dictionary are M and N, respectively.\n\na. character flopping:\n\nLoop over current set, character of word, alphabet, the flopping itself is O(L). Time complexity is O(26ML^2)\n\nb. verify transformation:\n\nLoop over current set, dictionary, character of word. Time complexity is O(MNL)\n\nFor b) to be faster, the switching point is N = 26L. This scale can be adjusted.\n\nSince the size of dictionary shrinks during the process, it is beneficial to switch to b) in the late stage, or use it for a small dictionary.\n\n-- Removing current word set from dictionary\n\nIt seems natural to use difference_update for this job since size of dictionary is bigger than that of current word set. But is it so? Note that here we are sure that every word in current set does exist in the dictionary.\n\na. S.difference_update(T) or S -= T\n\nFor every key (entry) in T, if it is in S, remove it from T. There are len(T) removes and len(T) peeks.\n\nb. S.difference(T) or S - T\n\nCreate a new empty set. For every key (entry) in S, if it is not in T, add it to new set. There are len(S)-len(T) adds and len(S) peeks.\n\nIf the sizes of current word set and dictionary are close, using difference_update means we will remove almost everything from dictionary. If we use difference, only a handful of adds. I use size of dictionary is twice that of current word set as the switching point. This threshold can be adjusted too.\nThe following optimized code takes ~100ms.\n\n class Solution:\n # @param {string} beginWord\n # @param {string} endWord\n # @param {set<string>} wordDict\n # @return {integer}\n def ladderLength(self, beginWord, endWord, wordDict):\n def generateNextSet1(current, wordDict, wordLen):\n nextSet = set()\n for word in current:\n for index in range(wordLen):\n for ch in 'abcdefghijklmnopqrstuvwxyz':\n nextWord = word[:index] + ch + word[index+1:]\n if nextWord in wordDict:\n nextSet.add(nextWord)\n return nextSet\n \n def generateNextSet2(current, wordDict):\n nextSet = set()\n for word in current:\n for nextWord in wordDict:\n index = 0\n try:\n while word[index] == nextWord[index]:\n index += 1\n if word[index+1:] == nextWord[index+1:]:\n nextSet.add(nextWord)\n except:\n continue\n return nextSet\n \n steps, wordLen = 2, len(beginWord)\n front, back = set([beginWord]), set([endWord])\n wordDict.discard(beginWord)\n switchThreshold = 26*wordLen\n while front:\n # get all valid transformations\n if len(wordDict) >= switchThreshold:\n front = generateNextSet1(front, wordDict, wordLen)\n else:\n front = generateNextSet2(front, wordDict)\n if front & back:\n # there are common elements in front and back, done\n return steps\n steps += 1\n if len(front) >= len(back):\n # swap front and back for better performance (smaller nextSet)\n front, back = back, front\n # remove transformations from wordDict to avoid cycles\n if (len(wordDict)>>1) >= len(front):\n # s.difference_update(t): O(len(t))\n wordDict -= front\n else:\n # s.difference(t): O(len(s))\n wordDict = wordDict - front\n return 0
12,561
Word Ladder
word-ladder
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
Hash Table,String,Breadth-First Search
Hard
null
389
6
The main idea: Use BFS to find the shortest path \n\nIn **Brutal force** solution:\n\tWe simply go through all the possible permutation, until we find the word we want.\n\t\nIn **Bidirectional BFS** solution:\n\tWe do almost the same thing, but do it from the front and back simultaneously.\n\tIf the front BFS meet the back BFS, we find the shortest route.\n\tWith Bidirectional BFS, we can reduce time complexity from O(b^d) to O(b^d/2)\n\tThis is how Bidirectional BFS work:\n\t![image]()\n\n\t\nHere\'s the difference between normal BFS and bidirectional BFS: \n![image]()\n\n\t\n\nBrutal force BFS solution:\n(661 ms)\n```\nclass Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n \n # BFS brutal force\n wordDict = set(wordList)\n if endWord not in wordDict: return 0 # impossible to find route\n \n wlen = len(beginWord)\n \n # how many steps to each word\n steps = {beginWord: 1}\n \n q = deque([beginWord])\n \n while len(q) > 0:\n word = q.popleft()\n step = steps[word]\n \n # change every single charactor\n for i in range(wlen):\n c = word[i]\n \n # \'a\' ~ \'z\'\n for t in string.ascii_lowercase:\n if c == t: continue # the chractor is the same \n \n new_word = word[:i] + t + word[i + 1:]\n if new_word == endWord: return step + 1\n if new_word not in wordDict: continue\n \n # remove it from dictionary, \n\t\t\t\t\t\t\t\t\t\t# so we won\'t go through the same word twice\n wordDict.remove(new_word) \n steps[new_word] = step + 1\n q.append(new_word)\n \n return 0\n```\n\nBidrection BFS solution:\n(128 ms)\n```\nclass Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n \n # Bidirectional BFS\n wordDict = set(wordList)\n if endWord not in wordDict: return 0 # impossible to find a route\n \n wlen = len(beginWord)\n s1 = {beginWord} # s1 starts from the front\n s2 = {endWord} # s2 starts from the back\n step = 0\n \n wordDict.remove(endWord)\n \n while len(s1) > 0 and len(s2) > 0:\n step += 1\n \n # swap s1 and s2 if s2 is shorter\n if len(s1) > len(s2): s1, s2 = s2, s1\n \n s = set()\n for w in s1:\n new_words = []\n new_words = [w[:i] + t + w[i+1:] for t in string.ascii_lowercase for i in range(wlen)]\n \n for new_word in new_words:\n \n if new_word in s2: return step + 1 # front and back BFS meet\n if new_word not in wordDict: continue\n \n # remove it from dictionary, \n # so we won\'t go through the same word twice\n wordDict.remove(new_word)\n s.add(new_word)\n s1 = s\n \n return 0\n```\n**Please UPVOTE if you LIKE**\n\n![image]()\n
12,571
Word Ladder
word-ladder
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
Hash Table,String,Breadth-First Search
Hard
null
2,741
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe time complexity of this algorithm is O(M^2 * N), where M is the length of each word and N is the total number of words in the list. The space complexity is also O(M^2 * N) due to the use of the set and queue.\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```\nfrom collections import deque\n\nclass Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n # Create a set of words for faster lookup\n wordSet = set(wordList)\n if endWord not in wordSet:\n return 0\n \n # Initialize queue with the beginWord and set of visited words\n queue = deque([(beginWord, 1)])\n visited = set([beginWord])\n \n while queue:\n # Dequeue the word and its level\n word, level = queue.popleft()\n \n # Iterate over each character in the word\n for i in range(len(word)):\n # Iterate over all possible lowercase letters\n for c in \'abcdefghijklmnopqrstuvwxyz\':\n # Skip if the character is the same as in the original word\n if c == word[i]:\n continue\n \n # Create the new word by replacing the character at index i\n newWord = word[:i] + c + word[i+1:]\n \n # Check if the new word is in the wordSet and has not been visited before\n if newWord in wordSet and newWord not in visited:\n # Check if the new word is the endWord\n if newWord == endWord:\n return level + 1\n \n # Enqueue the new word and its level\n queue.append((newWord, level + 1))\n \n # Add the new word to the set of visited words\n visited.add(newWord)\n \n # No transformation sequence exists\n return 0\n\n```
12,577
Word Ladder
word-ladder
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
Hash Table,String,Breadth-First Search
Hard
null
1,711
7
# Intuition\ntry doing brute force\n\n# Approach\n1>Go for brute force\n2>use bfs as memoization.\n3>use hashing for matching and changing string.\n\n# Complexity\n- Time complexity:\nlength of wordList(o(n))\n\n- Space complexity:\nspace of the dictionary i.e. o(n)\n\n# Code\n```\nfrom collections import deque\ndef hashword(word):\n h=0\n c=1\n for i in word:\n h+=c*(ord(i)-97)\n c=c*26\n return h\nclass Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n d={}\n for i in range(len(wordList)):\n d[hashword(wordList[i])]=0\n h=hashword(beginWord)\n q=deque()\n q.append(h)\n f=hashword(endWord)\n q=deque()\n q.append([h,1])\n if h in d:\n d[h]=1\n while q:\n x=q.popleft()\n h=x[0]\n ans=x[1]\n if h==f:\n return ans\n c=1\n for i in range(10):\n for j in range(26):\n y=h-(((h%(c*26))//c)*c)+(c*j)\n if y in d:\n if d[y]==0:\n d[y]=1\n q.append([y,ans+1])\n c=c*26\n return 0\n\n\n\n \n```
12,582
Word Ladder
word-ladder
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
Hash Table,String,Breadth-First Search
Hard
null
8,316
48
def ladderLength(beginWord, endWord, wordList):\n queue = [(beginWord, 1)]\n visited = set()\n \n while queue:\n word, dist = queue.pop(0)\n if word == endWord:\n return dist\n for i in range(len(word)):\n for j in 'abcdefghijklmnopqrstuvwxyz':\n tmp = word[:i] + j + word[i+1:]\n if tmp not in visited and tmp in wordList:\n queue.append((tmp, dist+1))\n visited.add(tmp)\n return 0
12,590
Longest Consecutive Sequence
longest-consecutive-sequence
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.
Array,Hash Table,Union Find
Medium
null
50,099
459
```C++ []\nint a[100000];\n\nint init = [] {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n ofstream out("user.out");\n for (string s; getline(cin, s); out << \'\\n\') {\n if (s.length() == 2) {\n out << 0;\n continue;\n }\n int n = 0;\n for (int _i = 1, _n = s.length(); _i < _n; ++_i) {\n bool _neg = false;\n if (s[_i] == \'-\') ++_i, _neg = true;\n int v = s[_i++] & 15;\n while ((s[_i] & 15) < 10) v = v * 10 + (s[_i++] & 15);\n if (_neg) v = -v;\n a[n++] = v;\n }\n sort(a, a + n);\n int ans = 0;\n for (int i = 0; i < n;) {\n int i0 = i;\n for (++i; i < n && a[i - 1] + 1 >= a[i]; ++i);\n ans = max(ans, a[i - 1] - a[i0] + 1);\n }\n out << ans;\n }\n out.flush();\n exit(0);\n return 0;\n}();\n\nclass Solution {\npublic:\n int longestConsecutive(vector<int>) { return 999; }\n};\n```\n\n```Python3 []\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n longest = 0\n num_set = set(nums)\n\n for n in num_set:\n if (n-1) not in num_set:\n length = 1\n while (n+length) in num_set:\n length += 1\n longest = max(longest, length)\n \n return longest\n```\n\n```Java []\nclass Solution {\n public int longestConsecutive(int[] nums) {int result = 0;\n if (nums.length > 0) {\n if (nums.length < 1000) {\n Arrays.sort(nums);\n int current = 0;\n for (int i = 1; i < nums.length; i++) {\n if (nums[i] != nums[i - 1]) {\n if (nums[i] - nums[i - 1] == 1) {\n current++;\n } else {\n if (current + 1 > result) {\n result = current + 1;\n }\n current = 0;\n }\n }\n }\n if (current + 1 > result) {\n result = current + 1;\n }\n } else {\n int min = Integer.MAX_VALUE;\n int max = Integer.MIN_VALUE;\n for (int num : nums) {\n if (num > max) {\n max = num;\n }\n if (num < min) {\n min = num;\n }\n }\n byte[] bits = new byte[max - min + 1];\n for (int num : nums) {\n bits[num - min] = 1;\n }\n int current = 0;\n for (byte bit : bits) {\n if (bit > 0) {\n current++;\n } else {\n if (current > result) {\n result = current;\n }\n current = 0;\n }\n }\n if (current > result) {\n result = current;\n }\n }\n }\n return result;\n }\n}\n```\n
12,600
Longest Consecutive Sequence
longest-consecutive-sequence
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.
Array,Hash Table,Union Find
Medium
null
4,842
33
# *PLEASE UPVOTE IF IT HELPED*\n\n---\n\n\n# Approach\n***(Also explained in the code)***\n\n#### ***Approach 1: Sorting || Iteration***\n\n1. If the input vector `nums` is empty (`n == 0`), it returns 0 because there are no consecutive elements in an empty vector.\n\n1. The code starts by sorting the `nums` vector in ascending order to make it easier to identify consecutive elements.\n\n1. It uses two variables, `cnt` and `maxi`, to keep track of the current consecutive sequence length and the maximum consecutive sequence length encountered so far.\n\n1. It iterates through the sorted vector and checks if the current element is different from the previous one. If it\'s different:\n\n - If the current element is consecutive to the previous one, the `cnt` counter is incremented.\n - If the current element is not consecutive, the code updates `maxi` with the maximum of `maxi` and `cnt` and resets `cnt` to 1 to start counting the next potential consecutive sequence.\n\n1. After processing the entire sorted vector, the code returns the maximum of `maxi` and `cnt` as the result, ensuring that it correctly returns the length of the longest consecutive sequence.\n\n#### Complexity\n- **Time complexity:**\n$$O(nlogn)$$\n\n- **Space complexity:**\n$$O(1)$$\n\n#### Code\n```C++ []\nclass Solution {\npublic:\n int longestConsecutive(vector<int>& nums) {\n int n = nums.size();\n \n // Base case: If the input vector is empty, there are no consecutive elements.\n if (n == 0) {\n return 0;\n }\n\n // Step 1: Sort the input vector in ascending order.\n sort(nums.begin(), nums.end());\n\n int cnt = 1; // Initialize a counter for the current consecutive sequence length.\n int maxi = 0; // Initialize a variable to store the maximum consecutive sequence length.\n\n // Step 2: Iterate through the sorted vector.\n for (int i = 1; i < n; i++) {\n // Step 3: Check if the current element is different from the previous one.\n if (nums[i] != nums[i - 1]) {\n // Step 4: If the current element is consecutive to the previous one, increment the counter.\n if (nums[i] == nums[i - 1] + 1) {\n cnt++;\n } else {\n // Step 5: If the current element is not consecutive, update \'maxi\' and reset \'cnt\'.\n maxi = max(maxi, cnt);\n cnt = 1;\n }\n }\n }\n\n // Step 6: Return the maximum of \'maxi\' and \'cnt\' as the result.\n return max(maxi, cnt);\n }\n};\n\n```\n```C []\n#include <stdio.h>\n#include <stdlib.h>\n\nint compare(const void *a, const void *b) {\n return (*(int*)a - *(int*)b);\n}\n\nint longestConsecutive(int* nums, int numsSize) {\n if (numsSize == 0) {\n return 0;\n }\n\n qsort(nums, numsSize, sizeof(int), compare);\n\n int cnt = 1;\n int maxi = 0;\n\n for (int i = 1; i < numsSize; i++) {\n if (nums[i] != nums[i - 1]) {\n if (nums[i] == nums[i - 1] + 1) {\n cnt++;\n } else {\n maxi = (maxi > cnt) ? maxi : cnt;\n cnt = 1;\n }\n }\n }\n\n return (maxi > cnt) ? maxi : cnt;\n}\n\nint main() {\n int nums[] = {100, 4, 200, 1, 3, 2};\n int numsSize = sizeof(nums) / sizeof(nums[0]);\n printf("Longest consecutive sequence length: %d\\n", longestConsecutive(nums, numsSize));\n return 0;\n}\n\n\n```\n```Java []\nimport java.util.Arrays;\n\nclass Solution {\n public int longestConsecutive(int[] nums) {\n int n = nums.length;\n \n if (n == 0) {\n return 0;\n }\n\n Arrays.sort(nums);\n\n int cnt = 1;\n int maxi = 0;\n\n for (int i = 1; i < n; i++) {\n if (nums[i] != nums[i - 1]) {\n if (nums[i] == nums[i - 1] + 1) {\n cnt++;\n } else {\n maxi = Math.max(maxi, cnt);\n cnt = 1;\n }\n }\n }\n\n return Math.max(maxi, cnt);\n }\n}\n\n\n```\n```python []\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n n = len(nums)\n \n if n == 0:\n return 0\n\n nums.sort()\n\n cnt = 1\n maxi = 0\n\n for i in range(1, n):\n if nums[i] != nums[i - 1]:\n if nums[i] == nums[i - 1] + 1:\n cnt += 1\n else:\n maxi = max(maxi, cnt)\n cnt = 1\n\n return max(maxi, cnt)\n\n```\n```Javascript []\nvar longestConsecutive = function(nums) {\n const n = nums.length;\n \n if (n === 0) {\n return 0;\n }\n\n nums.sort((a, b) => a - b);\n\n let cnt = 1;\n let maxi = 0;\n\n for (let i = 1; i < n; i++) {\n if (nums[i] !== nums[i - 1]) {\n if (nums[i] === nums[i - 1] + 1) {\n cnt++;\n } else {\n maxi = Math.max(maxi, cnt);\n cnt = 1;\n }\n }\n }\n\n return Math.max(maxi, cnt);\n};\n\n```\n\n---\n#### ***Approach 2: Sorting || Iteration***\n\n1. It starts by sorting the `nums` vector in ascending order to make it easier to identify consecutive elements.\n\n1. It handles the base case when the vector is empty (size `n` is 0), returning 0 because there are no consecutive elements.\n\n1. Inside the loop, it checks if the current number is consecutive to the previous one (`nums[i] - 1 == last_number`) and increments the counter `cnt`.\n\n1. If the current number is not consecutive, it resets the counter `cnt` to 1 and updates `last_number` with the current number.\n\n1. It updates the `longest` variable with the maximum of its current value and the `cnt` counter.\n\n1. After processing the entire sorted vector, it returns `longest` as the result, representing the length of the longest consecutive sequence.\n\n#### Complexity\n- **Time complexity:**\n$$O(nlogn)$$\n\n- **Space complexity:**\n$$O(1)$$\n\n#### Code\n```C++ []\nclass Solution {\npublic:\n int longestConsecutive(vector<int>& nums) {\n int n = nums.size();\n \n // Step 1: Sort the input vector in ascending order.\n sort(nums.begin(), nums.end());\n \n // Step 2: Handle the base case when the vector is empty.\n if (n == 0) {\n return 0;\n }\n \n int last_number = INT_MIN; // Initialize a variable to track the last processed number.\n int cnt = 0; // Initialize a counter for the current consecutive sequence length.\n int longest = 1; // Initialize a variable to store the maximum consecutive sequence length.\n\n // Step 3: Iterate through the sorted vector.\n for (int i = 0; i < n; i++) {\n if (nums[i] - 1 == last_number) {\n // Step 4: If the current number is consecutive to the previous one, increment the counter.\n cnt++;\n last_number = nums[i];\n } else if (nums[i] != last_number) {\n // Step 5: If the current number is not consecutive, update \'cnt\' and \'last_number\'.\n cnt = 1;\n last_number = nums[i];\n }\n \n // Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n longest = max(longest, cnt);\n }\n\n // Step 7: Return \'longest\' as the result, representing the length of the longest consecutive sequence.\n return longest;\n }\n};\n\n\n```\n```C []\n#include <stdio.h>\n#include <stdlib.h>\n#include <limits.h>\n\nint compare(const void *a, const void *b) {\n return (*(int*)a - *(int*)b);\n}\n\nint longestConsecutive(int* nums, int numsSize) {\n // Step 1: Sort the input array in ascending order.\n qsort(nums, numsSize, sizeof(int), compare);\n\n // Step 2: Handle the base case when the array is empty.\n if (numsSize == 0) {\n return 0;\n }\n\n int last_number = INT_MIN; // Initialize a variable to track the last processed number.\n int cnt = 0; // Initialize a counter for the current consecutive sequence length.\n int longest = 1; // Initialize a variable to store the maximum consecutive sequence length.\n\n // Step 3: Iterate through the sorted array.\n for (int i = 0; i < numsSize; i++) {\n if (nums[i] - 1 == last_number) {\n // Step 4: If the current number is consecutive to the previous one, increment the counter.\n cnt++;\n last_number = nums[i];\n } else if (nums[i] != last_number) {\n // Step 5: If the current number is not consecutive, update \'cnt\' and \'last_number\'.\n cnt = 1;\n last_number = nums[i];\n }\n\n // Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n if (cnt > longest) {\n longest = cnt;\n }\n }\n\n // Step 7: Return \'longest\' as the result, representing the length of the longest consecutive sequence.\n return longest;\n}\n\nint main() {\n int nums[] = {100, 4, 200, 1, 3, 2};\n int numsSize = sizeof(nums) / sizeof(nums[0]);\n printf("Longest consecutive sequence length: %d\\n", longestConsecutive(nums, numsSize));\n return 0;\n}\n\n```\n```Java []\n\nimport java.util.Arrays;\n\nclass Solution {\n public int longestConsecutive(int[] nums) {\n // Step 1: Sort the input array in ascending order.\n Arrays.sort(nums);\n\n // Step 2: Handle the base case when the array is empty.\n if (nums.length == 0) {\n return 0;\n }\n\n int last_number = Integer.MIN_VALUE; // Initialize a variable to track the last processed number.\n int cnt = 0; // Initialize a counter for the current consecutive sequence length.\n int longest = 1; // Initialize a variable to store the maximum consecutive sequence length.\n\n // Step 3: Iterate through the sorted array.\n for (int num : nums) {\n if (num - 1 == last_number) {\n // Step 4: If the current number is consecutive to the previous one, increment the counter.\n cnt++;\n last_number = num;\n } else if (num != last_number) {\n // Step 5: If the current number is not consecutive, update \'cnt\' and \'last_number\'.\n cnt = 1;\n last_number = num;\n }\n\n // Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n longest = Math.max(longest, cnt);\n }\n\n // Step 7: Return \'longest\' as the result, representing the length of the longest consecutive sequence.\n return longest;\n }\n}\n\n\n```\n```python []\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n # Step 1: Sort the input list in ascending order.\n nums.sort()\n\n # Step 2: Handle the base case when the list is empty.\n if not nums:\n return 0\n\n last_number = float(\'-inf\') # Initialize a variable to track the last processed number.\n cnt = 0 # Initialize a counter for the current consecutive sequence length.\n longest = 1 # Initialize a variable to store the maximum consecutive sequence length.\n\n # Step 3: Iterate through the sorted list.\n for num in nums:\n if num - 1 == last_number:\n # Step 4: If the current number is consecutive to the previous one, increment the counter.\n cnt += 1\n last_number = num\n elif num != last_number:\n # Step 5: If the current number is not consecutive, update \'cnt\' and \'last_number\'.\n cnt = 1\n last_number = num\n\n # Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n longest = max(longest, cnt)\n\n # Step 7: Return \'longest\' as the result, representing the length of the longest consecutive sequence.\n return longest\n\n\n```\n```Javascript []\n\nvar longestConsecutive = function(nums) {\n // Step 1: Sort the input array in ascending order.\n nums.sort((a, b) => a - b);\n\n // Step 2: Handle the base case when the array is empty.\n if (nums.length === 0) {\n return 0;\n }\n\n let last_number = Number.MIN_SAFE_INTEGER; // Initialize a variable to track the last processed number.\n let cnt = 0; // Initialize a counter for the current consecutive sequence length.\n let longest = 1; // Initialize a variable to store the maximum consecutive sequence length.\n\n // Step 3: Iterate through the sorted array.\n for (let num of nums) {\n if (num - 1 === last_number) {\n // Step 4: If the current number is consecutive to the previous one, increment the counter.\n cnt++;\n last_number = num;\n } else if (num !== last_number) {\n // Step 5: If the current number is not consecutive, update \'cnt\' and \'last_number\'.\n cnt = 1;\n last_number = num;\n }\n\n // Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n longest = Math.max(longest, cnt);\n }\n\n // Step 7: Return \'longest\' as the result, representing the length of the longest consecutive sequence.\n return longest;\n};\n\n\n```\n\n---\n\n#### ***Approach 3: With Unordered Set***\n\n1. It handles the base case when the vector is empty (size `n` is 0), returning 0 because there are no consecutive elements.\n\n1. It uses an unordered set `s` to store unique elements from the input vector, ensuring efficient lookup.\n\n1. It iterates through the elements of the unordered set and checks if each element `a` is the start of a sequence (no `a-1` in `s`).\n\n1. If `a` is the start of a sequence, it resets the counter `cnt` to 1 and initializes `x` to `a`. Then, it iterates to find consecutive elements by incrementing `x`.\n\n1. It updates the `longest` variable with the maximum of its current value and the `cnt` counter.\n\n1. After processing all elements in the unordered set, it returns `longest` as the result, representing the length of the longest consecutive sequence.\n\n#### Complexity\n- **Time complexity:**\n$$O(n)$$\n\n- **Space complexity:**\n$$O(n)$$\n\n#### Code\n```C++ []\nclass Solution {\npublic:\n int longestConsecutive(vector<int>& nums) {\n int n = nums.size();\n \n // Step 1: Handle the base case when the vector is empty.\n if (n == 0) {\n return 0;\n }\n\n unordered_set<int> s; // Create an unordered set to store unique elements.\n int cnt = 1; // Initialize a counter for the current consecutive sequence length.\n int longest = 1; // Initialize a variable to store the maximum consecutive sequence length.\n\n // Step 2: Insert all elements of \'nums\' into the unordered set \'s\'.\n for (int i = 0; i < n; i++) {\n s.insert(nums[i]);\n }\n \n int x = 0; // Initialize a variable to keep track of the current element being processed.\n\n // Step 3: Iterate through the elements of the unordered set.\n for (auto a : s) {\n // Step 4: If the current element \'a\' is the start of a sequence (no \'a-1\' in \'s\'),\n if (s.find(a - 1) == s.end()) {\n cnt = 1; // Reset the counter.\n x = a; // Update \'x\' to the current element \'a\'.\n\n // Step 5: While consecutive elements exist in \'s\', increment \'cnt\' and \'x\'.\n while (s.find(x + 1) != s.end()) {\n cnt++;\n x = x + 1;\n }\n }\n \n // Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n longest = max(longest, cnt);\n }\n\n // Step 7: Return \'longest\' as the result, representing the length of the longest consecutive sequence.\n return longest;\n }\n};\n\n\n\n```\n```C []\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <limits.h>\n\nstruct SetNode {\n int key;\n struct SetNode* next;\n};\n\nstruct HashSet {\n struct SetNode** buckets;\n int capacity;\n};\n\nstruct HashSet* createHashSet(int capacity) {\n struct HashSet* set = (struct HashSet*)malloc(sizeof(struct HashSet));\n set->capacity = capacity;\n set->buckets = (struct SetNode**)malloc(sizeof(struct SetNode*) * capacity);\n for (int i = 0; i < capacity; i++) {\n set->buckets[i] = NULL;\n }\n return set;\n}\n\nint hash(int key, int capacity) {\n return key % capacity;\n}\n\nvoid insert(struct HashSet* set, int key) {\n int index = hash(key, set->capacity);\n struct SetNode* newNode = (struct SetNode*)malloc(sizeof(struct SetNode));\n newNode->key = key;\n newNode->next = set->buckets[index];\n set->buckets[index] = newNode;\n}\n\nint contains(struct HashSet* set, int key) {\n int index = hash(key, set->capacity);\n struct SetNode* current = set->buckets[index];\n while (current != NULL) {\n if (current->key == key) {\n return 1;\n }\n current = current->next;\n }\n return 0;\n}\n\nvoid freeHashSet(struct HashSet* set) {\n for (int i = 0; i < set->capacity; i++) {\n struct SetNode* current = set->buckets[i];\n while (current != NULL) {\n struct SetNode* next = current->next;\n free(current);\n current = next;\n }\n }\n free(set->buckets);\n free(set);\n}\n\nint longestConsecutive(int* nums, int numsSize) {\n // Step 1: Handle the base case when the array is empty.\n if (numsSize == 0) {\n return 0;\n }\n\n struct HashSet* set = createHashSet(numsSize);\n\n // Step 2: Insert all elements of \'nums\' into the hash set \'set\'.\n for (int i = 0; i < numsSize; i++) {\n insert(set, nums[i]);\n }\n\n int cnt = 1; // Initialize a counter for the current consecutive sequence length.\n int longest = 1; // Initialize a variable to store the maximum consecutive sequence length.\n\n // Step 3: Iterate through the elements of \'nums\'.\n for (int i = 0; i < numsSize; i++) {\n int num = nums[i];\n // Step 4: If the current element \'num\' is the start of a sequence (no \'num-1\' in \'set\'),\n if (!contains(set, num - 1)) {\n int x = num; // Update \'x\' to the current element \'num\'.\n\n // Step 5: While consecutive elements exist in \'set\', increment \'cnt\' and \'x\'.\n while (contains(set, x + 1)) {\n cnt++;\n x = x + 1;\n }\n }\n \n // Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n longest = (cnt > longest) ? cnt : longest;\n }\n\n // Step 7: Free the hash set and return \'longest\' as the result.\n freeHashSet(set);\n return longest;\n}\n\nint main() {\n int nums[] = {100, 4, 200, 1, 3, 2};\n int numsSize = sizeof(nums) / sizeof(nums[0]);\n printf("Longest consecutive sequence length: %d\\n", longestConsecutive(nums, numsSize));\n return 0;\n}\n\n```\n```Java []\nimport java.util.HashSet;\n\nclass Solution {\npublic int longestConsecutive(int[] nums) {\n// Step 1: Handle the base case when the array is empty.\nif (nums.length == 0) {\nreturn 0;\n}\n\n HashSet<Integer> set = new HashSet<>();\n\n // Step 2: Insert all elements of \'nums\' into the hash set \'set\'.\n for (int num : nums) {\n set.add(num);\n }\n\n int cnt = 1; // Initialize a counter for the current consecutive sequence length.\n int longest = 0; // Initialize a variable to store the maximum consecutive sequence length.\n\n // Step 3: Iterate through the elements of \'nums\'.\n for (int num : nums) {\n // Step 4: If the current element \'num\' is the start of a sequence (no \'num-1\' in \'set\'),\n if (!set.contains(num - 1)) {\n int x = num; // Update \'x\' to the current element \'num\'.\n cnt = 1;\n // Step 5: While consecutive elements exist in \'set\', increment \'cnt\' and \'x\'.\n while (set.contains(x + 1)) {\n cnt++;\n x = x + 1;\n }\n }\n \n // Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n longest = Math.max(longest, cnt);\n }\n\n // Step 7: Return \'longest\' as the result.\n return longest;\n}\n}\n\n\n```\n```python []\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n # Step 1: Handle the base case when the list is empty.\n if not nums:\n return 0\n\n num_set = set(nums)\n\n cnt = 1 # Initialize a counter for the current consecutive sequence length.\n longest = 1 # Initialize a variable to store the maximum consecutive sequence length.\n\n # Step 3: Iterate through the elements of \'nums\'.\n for num in nums:\n # Step 4: If the current element \'num\' is the start of a sequence (no \'num-1\' in \'num_set\'),\n if num - 1 not in num_set:\n x = num # Update \'x\' to the current element \'num\'.\n\n # Step 5: While consecutive elements exist in \'num_set\', increment \'cnt\' and \'x\'.\n while x + 1 in num_set:\n cnt += 1\n x += 1\n \n # Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n longest = max(longest, cnt)\n\n # Step 7: Return \'longest\' as the result.\n return longest\n\n\n```\n```Javascript []\nvar longestConsecutive = function(nums) {\n // Step 1: Handle the base case when the array is empty.\n if (nums.length === 0) {\n return 0;\n }\n\n let numSet = new Set(nums);\n\n let cnt = 1; // Initialize a counter for the current consecutive sequence length.\n let longest = 1; // Initialize a variable to store the maximum consecutive sequence length.\n\n // Step 3: Iterate through the elements of \'nums\'.\n for (let num of nums) {\n // Step 4: If the current element \'num\' is the start of a sequence (no \'num-1\' in \'numSet\'),\n if (!numSet.has(num - 1)) {\n let x = num; // Update \'x\' to the current element \'num\'.\n\n // Step 5: While consecutive elements exist in \'numSet\', increment \'cnt\' and \'x\'.\n while (numSet.has(x + 1)) {\n cnt++;\n x++;\n }\n }\n \n // Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n longest = Math.max(longest, cnt);\n }\n\n // Step 7: Return \'longest\' as the result.\n return longest;\n};\n\n\n```\n\n# *PLEASE UPVOTE IF IT HELPED*\n\n---
12,610
Longest Consecutive Sequence
longest-consecutive-sequence
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.
Array,Hash Table,Union Find
Medium
null
9,622
58
Let\'s break down the code and its logic in more detail:\n\n1. `std::unordered_map<int, std::pair<int, int>> mp;`\n\n- `mp` is an unordered map used to store intervals (ranges) of consecutive numbers. Each key represents the right endpoint of an interval, and the corresponding value is a pair `(r, l)` where `r` is the right endpoint and `l` is the left endpoint of the interval.\n2. `std::unordered_map<int, bool> bl;`\n\n- `bl` is an unordered map used to keep track of whether an element `i` has been visited. If an element has been visited, its corresponding value in this map will be `true;` otherwise, it will be `false.`\n3. `int mx = 0;`\n\n- `mx` is a variable that keeps track of the maximum length of consecutive sequence found.\n4. The main loop iterates through each element `i` in the input `nums` array.\nInside the loop:\na. `if (bl[i]) { continue; }`\nIf the current element `i` has already been visited, skip it and continue to the next iteration of the loop.\nb. `bl[i] = true;`\nMark the current element `i` as visited by setting its corresponding value in the `bl` map to `true`.\nc. Initialize `l` and `r` to the current element `i`, representing the left and right endpoints of the current interval.\nd. Check if there is an interval with the right endpoint `i + 1` in the `mp` map using `mp.find(i + 1)`. If such an interval exists, update the right endpoint `r` to the right endpoint of that interval.\ne. Similarly, check if there is an interval with the right endpoint `i - 1` in the `mp` map using `mp.find(i - 1)`. If such an interval exists, update the left endpoint `l` to the left endpoint of that interval.\nf. Update the `mp` map:\nSet `mp[r]` to a pair `(r, l)`, indicating the interval with right endpoint `r` and left endpoint l.\nSet `mp[l]` to the same pair `(r, l)`.\ng. Calculate the length of the current consecutive sequence as `r - l + 1` and update the maximum length `mx` if this length is greater than the current maximum.\n\n5. Finally, return the maximum length mx, which represents the length of the longest consecutive sequence found in the input array.\nExplanation from chatgpt. The solution is from me \uD83D\uDE07.\n# Code\n<iframe src="" frameBorder="0" width="800" height="500"></iframe>\n\n![image.png]()
12,611
Longest Consecutive Sequence
longest-consecutive-sequence
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.
Array,Hash Table,Union Find
Medium
null
439
6
# Intuition\nFor every element we need to check if it has a sequence. If yes, what are it\'s sequential numbers and sequence\'s length? Also, when we visit a number, since we know it\'s sequential numbers, we can skip checking them.\n\nUsually a search operation like `in` takes longer time on lists vs sets. Average search time on Set is usually O(1) and unlike lists we don\'t have to worry about iterating through duplicates as set values are unique.\n\n# Approach\n* Convert the list to set.\n* We can safely assume that if the current maximum possible sequence length >= number of unvisited numbers, it is the longest sequence in given list.\n* So we can keep searching for longest possible sequences until we hit this condition.\n* As you visit a number keep deleting them from set, so you don\'t have to check twice. Check consecutive sequence of the number in the set, delete them as you visit and save the highest number of that sequence.\n* Similarly now you check for the presence of it\'s preceding sequential numbers and find the lowest number of that sequence.\n* When you subtract the highest and lowest numbers of a sequence, you get sequence\'s length.\n* Update the max, and repeat the steps until your max sequence length >= number of unvisited integers in set (length of set since you deleted visited numbers).\n\n# Complexity\n- Time complexity: $$O(n)$$\n - Conversion of list to set `numSet = set(nums)\n` is linear time *O(n)*.\n - In worst case scenario where each element in `nums` is unique and doesn\'t have any sequences, each number is only visited once, which is also linear time *O(n)*. \n - Ignore the constants and you get ***O(n)** where, n = length of list*.\n\n\n- Space complexity: $$O(n)$$\n - `numSet` requires space, which is ***O(n)** where, n = number of unique numbers in list*.\n\n\n# Code\n```\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n numSet = set(nums)\n maxSeqLen = 0\n while maxSeqLen < len(numSet):\n num = numSet.pop()\n longest = num+1\n while longest in numSet:\n numSet.remove(longest)\n longest += 1\n num = num-1\n while num in numSet:\n numSet.remove(num)\n num -= 1\n maxSeqLen = max(maxSeqLen, longest-num-1)\n return maxSeqLen\n \n```
12,617
Longest Consecutive Sequence
longest-consecutive-sequence
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.
Array,Hash Table,Union Find
Medium
null
25,206
196
\u2714\uFE0F ***Solution - I (Sorting)***\n\nWe can simply sort the given array and compare consecutive elements. Following cases exists:\n1. **`nums[i] == nums[i-1] + 1`**: This means the current element is consecutive to previous, so increment current streak count.\n2. **`nums[i] == nums[i-1]`**: We have found the same element as previous. Skip it, and see if we can still extend the sequence with next elements.\n3. **None of above** : We can\'t extend the sequence any further. Update *`longest`* to store longest formed streak till now and reset *`curlongest`*.\n\n**C++**\n```\nint longestConsecutive(vector<int>& nums) {\n\tif(!size(nums)) return 0;\n\tsort(begin(nums), end(nums));\n\tint longest = 0, cur_longest = 1;\n\tfor(int i = 1; i < size(nums); i++) \n\t\tif(nums[i] == nums[i - 1]) continue;\n\t\telse if(nums[i] == nums[i - 1] + 1) cur_longest++; // consecutive element - update current streak length\n\t\telse longest = max(longest, cur_longest), cur_longest = 1; // reset current streak length\n\treturn max(longest, cur_longest);\n}\n```\n\n---\n\n**Python**\n```\ndef longestConsecutive(self, nums: List[int]) -> int:\n\tnums.sort()\n\tlongest, cur_longest = 0, min(1, len(nums))\n\tfor i in range(1,len(nums)):\n\t\tif nums[i] == nums[i - 1] : continue\n\t\tif nums[i] == nums[i - 1] + 1: cur_longest += 1\n\t\telse: longest, cur_longest = max(longest, cur_longest), 1\n\treturn max(longest, cur_longest)\n```\n\n***Time Complexity :*** **`O(NlogN)`**, where *`N`* is the number of elements in nums\n***Time Complexity :*** **`O(1)`**, ignoring the space required by sorting algorithm.\n\n---\n\n\u2714\uFE0F ***Solution - II (Using Hashset)***\n\nWe need to find the longest consecutive sequence in linear time. We can do this if we insert all the elements of *`nums`* into a hashset. Once we have inserted all the elements, we can just iterate over the hashset to find longest consecutive sequence involving the current element(let\'s call it *`num`*) under iteration. This can simply be done by **iterating over elements that are consecutive to *`num`* till we keep finding them in the set**. Each time we will also delete those elements from set to ensure we only visit them once.\n\n**C++**\n```\nint longestConsecutive(vector<int>& nums) {\n\tunordered_set<int> s(begin(nums), end(nums)); // inserting all elements into hashset\n\tint longest = 0;\n\tfor(auto& num : s) {\n\t\tint cur_longest = 1;\n\t\t// find consecutive elements in the backward and forward direction from num\n\t\tfor(int j = 1; s.count(num - j); j++) s.erase(num - j), cur_longest++;\n\t\tfor(int j = 1; s.count(num + j); j++) s.erase(num + j), cur_longest++;\n\t\tlongest = max(longest, cur_longest); // update longest to hold longest consecutive sequence till now\n\t}\n\treturn longest;\n}\n```\n\n---\n\n**Python**\n```\ndef longestConsecutive(self, nums: List[int]) -> int:\n\tlongest, s = 0, set(nums)\n\tfor num in nums:\n\t\tcur_longest, j = 1, 1\n\t\twhile num - j in s: \n\t\t\ts.remove(num - j)\n\t\t\tcur_longest, j = cur_longest + 1, j + 1\n\t\tj = 1\n\t\twhile num + j in s: \n\t\t\ts.remove(num + j)\n\t\t\tcur_longest, j = cur_longest + 1, j + 1\n\t\tlongest = max(longest, cur_longest)\n\treturn longest\n```\n\n***Time Complexity :*** **`O(N)`**\n***Space Complexity :*** **`O(N)`**\n\n---\n\n\u2714\uFE0F ***Solution - III (Using Hashset - w/ optimizations)***\n\nWe can form a solution without the need to spend time erasing elements from the hashset. \n\nInstead of taking the first element that we find in the hashset and iterating both forward and backward, we can just keep skipping till we find that hashset contains `num - 1`. Finally, we can just iterate in the forward direction till we find consecutive elements in hashset and update `longest` at the end\n\n**C++**\n```\nint longestConsecutive(vector<int>& nums) {\n\tunordered_set<int> s(begin(nums), end(nums));\n\tint longest = 0;\n\tfor(auto& num : s) {\n if(s.count(num - 1)) continue;\n\t\tint j = 1;\n\t\twhile(s.count(num + j)) j++;\n\t\tlongest = max(longest, j);\n\t}\n\treturn longest;\n}\n```\n\n---\n\n**Python**\n```\ndef longestConsecutive(self, nums):\n\ts, longest = set(nums), 0\n\tfor num in s:\n\t\tif num - 1 in s: continue\n\t\tj = 1\n\t\twhile num + j in s: j += 1\n\t\tlongest = max(longest, j)\n\treturn longest\n```\n\n***Time Complexity :*** **`O(N)`**\n***Space Complexity :*** **`O(N)`**\n\n---\n---\n\n\uD83D\uDCBB\uD83D\uDC31\u200D\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, please do comment below \uD83D\uDC47 \n\n---\n---
12,629
Longest Consecutive Sequence
longest-consecutive-sequence
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.
Array,Hash Table,Union Find
Medium
null
11,532
96
Given an *unsorted* array of integers `nums`, we need to return the length of the longest consecutive elements sequence.\ne.g.:\n\n```text\nnums = [0, 3, 2, 1, 5, 6, 9]\n\nConsecutive Elements of length\n1: [0], [1], [2], [3], [5], [6], [9]\n2: [5, 6]\n4: [0, 1, 2, 3]\n\nHence, we return 4\n```\n\nIt is explicitly mentioned in the problem statement that the algorithm should be of time complexity `O(n)`, so sorting the array is out of the question.\n\nI then thought of a solution that is `O(n)` which is as follows:\n\n1. Use a boolean array, where the index represents the number itself to store if the number is present or not.\n2. Then traverse through this array to find the longest consecutive `True` values.\n\ne.g.:\n\n```text\nnums = [0, 3, 2, 1, 5, 6, 9]\nbool_arr = [True, True, True, True, False, True, True, False, False, True]\n | | | | | | | | | |\n 0 1 2 3 4 5 6 7 8 9\n\nThe largest consecutive sequence with True values is of length 4, which is our answer.\n```\n\nI then looked at the constraints, which mention `-10\u2079 <= nums[i] <= 10\u2079`, so this approach also cannot be used as both time and space complexity would be of order ~`2*10\u2079`, which is high.\n\nSo, let\'s think of a brute-force approach and then optimize it.\n___\n___\n\u274C **Solution I: Brute-force [TLE]**\n\nStarting from each `num` in the `nums` array, we try to build a consecutive sequence and check if it is the longest. We can do this by checking if `num + 1` is present or not; if present, then check if `num + 2` is present or not and so on.\n\n<iframe src="" frameBorder="0" width="1080" height="330"></iframe>\n\n- **Time Complexity:** `O(n\xB3)`\n > The outer `for` loop runs `n` times. The inner `while` loop can run upto `n` times for the worst case if the entire array forms consecutive sequence, and finding `curr_num + 1 in nums` has complexity `0(n)`.\n- **Space Complexity:** `O(1)`\n\n___\n\u274C **Solution II: Optimized Brute-force + HashSet [TLE]**\n\nWe are checking if `curr_num + 1` is present in the array in `O(n)` time. We can optimize this lookup to `O(1)` using a HashSet.\n\n<iframe src="" frameBorder="0" width="1080" height="340"></iframe>\n\n- **Time Complexity:** `O(n\xB2)`\n > We reduced the lookup to `O(1)` and everything else remains the same.\n- **Space Complexity:** `O(n)`\n\n___\n\u2705 **Solution III: Super Optimized Brute-force + HashSet [Accepted]**\n\nWe are still doing many repetitive works. This can be understood by the following example:\n\n```text\nnums = [1, 2, 3, 4, 5]\n1. num = 1\n a. curr_num = 1, curr_len = 1, while condition: True\n b. curr_num = 2, curr_len = 2, while condition: True\n c. curr_num = 3, curr_len = 3, while condition: True\n d. curr_num = 4, curr_len = 4, while condition: True\n e. curr_num = 5, curr_len = 5, while condition: False\n\n2. num = 2\n a. curr_num = 2, curr_len = 1, while condition: True\n b. curr_num = 3, curr_len = 2, while condition: True\n c. curr_num = 4, curr_len = 3, while condition: True\n d. curr_num = 5, curr_len = 4, while condition: False\n.\n.\n.\n```\n\nThis redundancy can be removed in multiple ways. One way could be to use an extra HashSet to store the information that the number is already a part of a sequence that was processed earlier. So, in the previous example, no need to run the inner `while` loop as `2` was already processed. Furthermore, the inner `while` loop won\'t run for `num = 3, 4 and 5`.\nThere is one more interesting way. Considering the previous example, after `num = 1` has been processed, `num` becomes `2`. Now we can check if `1,` i.e. `num - 1` is present in the array or not. If present, there is no need to run the inner `while` loop, as it was processed earlier or will be processed later. What do I mean by "will be processed later"? This will become clear in the following example.\n\n```text\nnums = [2, 3, 1, 4, 5]\n1. num = 2\n 1 is present -> Don\'t run the inner loop\n2. num = 3\n 2 is present -> Don\'t run the inner loop\n3. curr_num = 1\n 0 is not present -> Run the inner loop\n a. curr_num = 1, curr_len = 1, while condition: True\n b. curr_num = 2, curr_len = 2, while condition: True\n c. curr_num = 3, curr_len = 3, while condition: True\n d. curr_num = 4, curr_len = 4, while condition: True\n e. curr_num = 5, curr_len = 5, while condition: False\n```\n\n<iframe src="" frameBorder="0" width="1080" height="380"></iframe>\n\nIn short, the inner while loop will only start if any `num` in `nums` is the start of a new consecutive sequence.\n\n- **Time Complexity:** `O(n)`\n > This is actually tricky. One may think there are two nested loops, and the complexity should be `O(n\xB2)`. But, this is not the case. To understand this, focus on my statement just after the code. The `while` loop will only execute when `num` is the start of a sequence and will run up to `n` times for the worst case. So, let\'s say `nums = [3, 5, 1, 2, 7, 6]`. The `while` loop will only execute when `num = 1 or 5`, which will run till `3` and `7`, respectively. So, the array is covered only once!\n- **Space Complexity:** `O(n)`\n\n___\n**Update:**\nThe code can be made even faster if we run the `for` loop through the set instead of the original array. This is because we are not considering duplicate elements. Thanks to [@dennisthomas2002]() and [@shivangtomar]() for their suggestions.\n\n```python\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n max_len = 0\n num_set = set(nums)\n for num in num_set:\n if num - 1 not in num_set:\n curr_num = num\n curr_len = 1\n while curr_num + 1 in num_set:\n curr_num += 1\n curr_len += 1\n max_len = max(max_len, curr_len)\n return max_len\n```\n\nThis solution was inspired by [@StefanPochmann]()\'s solution [here]((n)-with-Explanation-Just-walk-each-streak).\n___\n___\nIf you like the solution, please **upvote**! \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F\n
12,631