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
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
44,211
334
```\nclass Solution(object):\n def mergeKLists(self, lists):\n if not lists:\n return None\n if len(lists) == 1:\n return lists[0]\n mid = len(lists) // 2\n l, r = self.mergeKLists(lists[:mid]), self.mergeKLists(lists[mid:])\n return self.merge(l, r)\n \n def merge(self, l, r):\n dummy = p = ListNode()\n while l and r:\n if l.val < r.val:\n p.next = l\n l = l.next\n else:\n p.next = r\n r = r.next\n p = p.next\n p.next = l or r\n return dummy.next\n \n def merge1(self, l, r):\n if not l or not r:\n return l or r\n if l.val< r.val:\n l.next = self.merge(l.next, r)\n return l\n r.next = self.merge(l, r.next)\n return r\n```
2,254
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
1,508
27
```C++ []\nofstream ans("user.out");\nint main() {\n vector<int> v;\n v.reserve(1e4);\n string s;\n while (getline(cin, s)) {\n s.erase(remove(begin(s), end(s), \'[\'), end(s));\n s.erase(remove(begin(s), end(s), \']\'), end(s));\n for (auto &i: s) if (i == \',\') i = \' \';\n istringstream iss(s);\n int temp;\n v.clear();\n while (iss >> temp) v.push_back(temp);\n sort(v.begin(), v.end());\n ans << \'[\';\n for (int i = 0; i < v.size(); ++i) {\n if (i) ans << \',\';\n ans << v[i];\n }\n ans << "]\\n";\n }\n}\nclass Solution {\npublic:\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n return nullptr;\n }\n};\n```\n\n```Python3 []\nf = open("user.out", \'w\')\nfor s in sys.stdin:\n print(\'[\', \',\'.join(\n map(str, sorted(int(v) for v in s.rstrip().replace(\'[\', \',\').replace(\']\', \',\').split(\',\') if v))), \']\', sep=\'\',\n file=f)\nexit(0)\n```\n\n```Java []\nclass Solution {\n\n ListNode merge(ListNode list1, ListNode list2) {\n\n if (list1 == null) {\n return list2;\n } else if (list2 == null) {\n return list1;\n }\n\n ListNode head = null, curr = head;\n ListNode curr1 = list1, curr2 = list2;\n while (curr1 != null && curr2 != null) {\n\n ListNode minNode = null;\n if (curr1.val < curr2.val) {\n minNode = curr1;\n curr1 = curr1.next;\n } else {\n minNode = curr2;\n curr2 = curr2.next;\n }\n\n if (head == null) {\n curr = head = minNode;\n } else {\n curr.next = minNode;\n curr = curr.next;\n }\n }\n\n if (curr1 != null) {\n curr.next = curr1;\n } else if (curr2 != null) {\n curr.next = curr2;\n }\n\n return head;\n }\n\n ListNode mergeSort(ListNode[] lists, int beg, int end) {\n\n if (beg == end) {\n return lists[beg];\n }\n\n int mid = (beg + end) / 2;\n ListNode list1 = mergeSort(lists, beg, mid);\n ListNode list2 = mergeSort(lists, mid + 1, end);\n ListNode head = merge(list1, list2);\n return head;\n }\n\n public ListNode mergeKLists(ListNode[] lists) {\n\n if (lists.length == 0) {\n return null;\n }\n return mergeSort(lists, 0, lists.length - 1);\n }\n}\n```\n
2,269
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
711
5
```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n \n if not lists or len(lists)==0:\n return None\n \n \n while(len(lists)>1):\n mergedlist =[]\n \n for i in range(0,len(lists),2):\n \n l1 = lists[i]\n l2 = lists[i+1] if i+1<len(lists) else None\n \n mergedlist.append(self.mergetwo(l1,l2))\n \n lists = mergedlist\n \n return lists[0]\n \n def mergetwo(self,l1,l2):\n \n dummy = ListNode()\n tail = dummy\n \n while l1 and l2:\n if l1.val<l2.val:\n tail.next = l1\n l1 = l1.next\n else:\n tail.next = l2\n l2 = l2.next\n \n tail = tail.next\n \n \n if l1:\n tail.next = l1\n \n if l2:\n tail.next = l2\n \n return dummy.next \n \n```
2,295
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
3,407
44
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThe main challenge in the problem is the fact that the number of lists `k` can be huge and iterating over list heads every time attaching a new node to the result would be time-consuming. Essentially what is important to know on every merging step is what is the smallest node among all list heads. We can utilize the priority queue to fast access the current smallest node. \n\nFirst, we form the initial heap with tuples containing val and node itself. Notice that in Python implementation of the heap, the first element of the tuple is considered as a priority. In case the heap already has an element with the same priority, the Python compares the next element of the tuple. That is why we need index `i` in the second place.\n\nThen we run a cycle until the heap is empty. On every step, we pop out the smallest node and attach it to the result. Right away we push to the heap the next node.\n\nTime: **O(k * n * log(k))** - scan and manipulation with heap\nSpace: **O(k)** - for the heap\n\nRuntime: 96 ms, faster than **93.66%** of Python3 online submissions for Merge k Sorted Lists.\nMemory Usage: 17.9 MB, less than **61.96%** of Python3 online submissions for Merge k Sorted Lists.\n\n```\ndef mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n\theap, res = [], ListNode()\n\tfor i, list in enumerate(lists):\n\t\tif list: \n\t\t\theappush(heap, (list.val, i, list))\n\n\tcur = res\n\twhile heap:\n\t\t_, i, list = heappop(heap)\n\t\tif list.next:\n\t\t\theappush(heap, (list.next.val, i, list.next))\n\n\t\tcur.next, cur = list, list\n\n\treturn res.next\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**
2,298
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
36,310
174
**UPVOTE if you like (\uD83C\uDF38-_-\'), If you have any question, feel free to ask.**\n\nJust a bunch of placeholders, edge cases, and strange errors about a cycle meanwhile :(\n\nprev cur cur porev next cur prev pasdfaslfjgnzdsf;ljgfsdaz;lkjkfgn\n\nTime: **O(n)** - iterate\nSpace: **O(1)**\n\n```\ndef swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:\n\tif not head: return head\n\n\tprev, cur, ans = None, head, head.next\n\twhile cur and cur.next:\n\t\tadj = cur.next\n\t\tif prev: prev.next = adj\n\n\t\tcur.next, adj.next = adj.next, cur\n\t\tprev, cur = cur, cur.next\n\n\treturn ans or head\n```\n\n**UPVOTE if you like (\uD83C\uDF38-_-\'), If you have any question, feel free to ask.**
2,302
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
10,284
54
**!! BIG ANNOUNCEMENT !!**\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. This is only for first 10,000 Subscribers. **DON\'T FORGET** to Subscribe\n\n# Search \uD83D\uDC49 `Tech Wired Leetcode` to Subscribe\n\n# Video Solution\n\n# Search \uD83D\uDC49 `Swap Nodes in Pairs by Tech Wired`\n\n# or\n\n# Click the Link in my Profile\n\n# Approach:\nThe approach used in the code is to traverse the linked list and swap adjacent pairs of nodes. This is done iteratively by maintaining a current pointer that points to the previous node before the pair to be swapped. The swapping is done by modifying the next pointers of the nodes.\n\n# Intuition:\nThe intuition behind the code is to break down the problem into smaller subproblems. By swapping two nodes at a time, we can gradually swap adjacent pairs throughout the linked list. This is achieved by manipulating the next pointers of the nodes.\n\nThe use of a dummy node helps in handling the edge case where the head of the list needs to be swapped. It serves as a placeholder for the new head of the modified list.\n\nThe while loop iterates as long as there are at least two nodes remaining in the list. In each iteration, the current pair of nodes is swapped by adjusting the next pointers accordingly.\n\n\n\n```Python []\nclass Solution:\n def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:\n\n if not head or not head.next: return head\n\n dummy = ListNode(0)\n dummy.next = head\n curr = dummy\n\n while curr.next and curr.next.next:\n first = curr.next\n second = curr.next.next\n curr.next = second\n first.next = second.next\n second.next = first\n curr = curr.next.next\n \n return dummy.next\n```\n```Java []\nclass Solution {\n public ListNode swapPairs(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n \n ListNode dummy = new ListNode(0);\n dummy.next = head;\n ListNode curr = dummy;\n \n while (curr.next != null && curr.next.next != null) {\n ListNode first = curr.next;\n ListNode second = curr.next.next;\n curr.next = second;\n first.next = second.next;\n second.next = first;\n curr = curr.next.next;\n }\n \n return dummy.next;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n ListNode* swapPairs(ListNode* head) {\n if (head == nullptr || head->next == nullptr) {\n return head;\n }\n \n ListNode* dummy = new ListNode(0);\n dummy->next = head;\n ListNode* curr = dummy;\n \n while (curr->next != nullptr && curr->next->next != nullptr) {\n ListNode* first = curr->next;\n ListNode* second = curr->next->next;\n curr->next = second;\n first->next = second->next;\n second->next = first;\n curr = curr->next->next;\n }\n \n return dummy->next;\n }\n};\n```\n# An Upvote will be encouraging \uD83D\uDC4D\n\n
2,337
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
4,862
24
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTraverse the list and swap pairs of nodes one by one.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- The node "ans" is to point to the head of the original list. It then uses a "curr" node to traverse the list and swap pairs of nodes. The loop continues as long as there are at least two more nodes to swap.\n\n- Inside the loop, the solution uses two temporary nodes, "t1" and "t2", to hold the first and second nodes of the pair. Then, it updates the pointers to swap the nodes, and moves "curr" two nodes ahead. At the end, it returns the modified list starting from the next node of the "ans" node.\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```java []\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode swapPairs(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n ListNode ans =new ListNode(0);\n ans.next=head;\n ListNode curr=ans;\n while (curr.next != null && curr.next.next != null) {\n ListNode t1 = curr.next;\n ListNode t2 = curr.next.next;\n curr.next = t2;\n t1.next = t2.next;\n t2.next = t1;\n curr = curr.next.next;\n } \n return ans.next;\n }\n}\n```\n```python []\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not head or not head.next:\n return head\n \n ans = ListNode(0)\n ans.next = head\n curr = ans\n \n while curr.next and curr.next.next:\n t1 = curr.next\n t2 = curr.next.next\n curr.next = t2\n t1.next = t2.next\n t2.next = t1\n curr = curr.next.next\n \n return ans.next\n```\n```C++ []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* swapPairs(ListNode* head) {\n if (head == NULL || head->next == NULL) {\n return head;\n }\n struct ListNode* ans = (struct ListNode*) malloc(sizeof(struct ListNode));\n ans->next = head;\n struct ListNode* curr = ans;\n while (curr->next != NULL && curr->next->next != NULL) {\n struct ListNode* t1 = curr->next;\n struct ListNode* t2 = curr->next->next;\n curr->next = t2;\n t1->next = t2->next;\n t2->next = t1;\n curr = curr->next->next;\n }\n return ans->next;\n }\n};\n```\n```Javascript []\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nvar swapPairs = function(head) {\n if (head == null || head.next == null) {\n return head;\n }\n let ans = new ListNode(0);\n ans.next = head;\n let curr = ans;\n while (curr.next != null && curr.next.next != null) {\n let t1 = curr.next;\n let t2 = curr.next.next;\n curr.next = t2;\n t1.next = t2.next;\n t2.next = t1;\n curr = curr.next.next;\n }\n return ans.next;\n};\n```\n```C# []\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * public int val;\n * public ListNode next;\n * public ListNode(int val=0, ListNode next=null) {\n * this.val = val;\n * this.next = next;\n * }\n * }\n */\npublic class Solution {\n public ListNode SwapPairs(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n ListNode ans = new ListNode(0);\n ans.next = head;\n ListNode curr = ans;\n while (curr.next != null && curr.next.next != null) {\n ListNode t1 = curr.next;\n ListNode t2 = curr.next.next;\n curr.next = t2;\n t1.next = t2.next;\n t2.next = t1;\n curr = curr.next.next;\n }\n return ans.next; \n }\n}\n```\n```Kotlin []\n/**\n * Example:\n * var li = ListNode(5)\n * var v = li.`val`\n * Definition for singly-linked list.\n * class ListNode(var `val`: Int) {\n * var next: ListNode? = null\n * }\n */\nclass Solution {\n fun swapPairs(head: ListNode?): ListNode? {\n if (head == null || head.next == null) {\n return head\n }\n val ans = ListNode(0)\n ans.next = head\n var curr: ListNode? = ans\n while (curr?.next != null && curr.next?.next != null) {\n val t1 = curr.next\n val t2 = curr.next?.next\n curr.next = t2\n t1.next = t2?.next\n t2?.next = t1\n curr = curr.next?.next\n }\n return ans.next\n }\n}\n```\n```C []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * struct ListNode *next;\n * };\n */\nstruct ListNode* swapPairs(struct ListNode* head){\n if (head == NULL || head->next == NULL) {\n return head;\n }\n struct ListNode* ans = (struct ListNode*) malloc(sizeof(struct ListNode));\n ans->next = head;\n struct ListNode* curr = ans;\n while (curr->next != NULL && curr->next->next != NULL) {\n struct ListNode* t1 = curr->next;\n struct ListNode* t2 = curr->next->next;\n curr->next = t2;\n t1->next = t2->next;\n t2->next = t1;\n curr = curr->next->next;\n }\n return ans->next;\n}\n```\n\nUPVOTES ARE ENCOURAGING!
2,361
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
83,375
403
Three different implementations of the same algorithm, taking advantage of different strengths of the three languages. I suggest reading all three, even if you don't know all three languages.\n\nAll three of course work swap the current node with the next node by rearranging pointers, then move on to the next pair, and repeat until the end of the list.\n\n---\n\n**C++**\n\nPointer-pointer `pp` points to the pointer to the current node. So at first, `pp` points to `head`, and later it points to the `next` field of ListNodes. Additionally, for convenience and clarity, pointers `a` and `b` point to the current node and the next node.\n\nWe need to go from `*pp == a -> b -> (b->next)` to `*pp == b -> a -> (b->next)`. The first three lines inside the loop do that, setting those three pointers (from right to left). The fourth line moves `pp` to the next pair.\n\n ListNode* swapPairs(ListNode* head) {\n ListNode **pp = &head, *a, *b;\n while ((a = *pp) && (b = a->next)) {\n a->next = b->next;\n b->next = a;\n *pp = b;\n pp = &(a->next);\n }\n return head;\n }\n\n---\n\n**Python**\n\nHere, `pre` is the previous node. Since the head doesn't have a previous node, I just use `self` instead. Again, `a` is the current node and `b` is the next node.\n\nTo go from `pre -> a -> b -> b.next` to `pre -> b -> a -> b.next`, we need to change those three references. Instead of thinking about in what order I change them, I just change all three at once.\n\n def swapPairs(self, head):\n pre, pre.next = self, head\n while pre.next and pre.next.next:\n a = pre.next\n b = a.next\n pre.next, b.next, a.next = b, a, b.next\n pre = a\n return self.next\n\n---\n\n**Ruby**\n\nAgain, `pre` is the previous node, but here I create a dummy as previous node of the head. And again, `a` is the current node and `b` is the next node. This time I go one node further and call it `c`.\n\nTo go from `pre -> a -> b -> c` to `pre -> b -> a -> c`, we need to change those three references. Here I chain the assignments, pretty much directly saying "`pre` points to `b`, which points to `a`, which points to `c`".\n\n def swap_pairs(head)\n pre = dummy = ListNode.new 0\n pre.next = head\n while a = pre.next and b = a.next\n c = b.next\n ((pre.next = b).next = a).next = c\n pre = a\n end\n dummy.next\n end
2,363
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
1,371
12
\n\n\n\n# BRUTE\n```JAVA []\npublic ListNode swapPairs(ListNode head) {\n List<ListNode> list = new ArrayList<>();\n ListNode temNode = head;\n while (temNode != null) {\n list.add(temNode);\n temNode = temNode.next;\n }\n for (int i = 0; i < list.size() - 1; i += 2) {\n int swapElement = list.get(i).val;\n list.get(i).val = list.get(i + 1).val;\n list.get(i + 1).val = swapElement;\n }\n return head;\n}\n```\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Intuition & Approach\n<!-- Describe your approach to solving the problem. -->\nwe first check if the input head is null or has only one node. If so, we return the head as it is. Otherwise, we create two nodes first and second and set them to the first and second nodes of the linked list, respectively. We then recursively call the swapPairs function on the next of the second node and set the next of the first node to the result. We then swap the next pointers of the first and second nodes and return the second node.\n\n# BETTER\n```JAVA []\npublic ListNode swapPairs(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n ListNode first = head;\n ListNode second = head.next;\n first.next = swapPairs(second.next);\n second.next = first;\n return second;\n}\n```\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(LOG(N))\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# OPTIMAL\nWe create a dummy node and set its next to the head. We then create a current node and initialize it to the dummy node. We use a single loop to swap every two adjacent nodes. We do this by creating two nodes first and second and swapping their next pointers. We then update the current node to point to the second node and continue the loop. Finally, we return the next of the dummy node.The time complexity of this solution is O(n) as we need to traverse the entire linked list once.\n```JAVA []\npublic ListNode swapPairs(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n ListNode dummy = new ListNode(0);\n dummy.next = head;\n ListNode current = dummy;\n while (current.next != null && current.next.next != null) {\n ListNode first = current.next;\n ListNode second = current.next.next;\n first.next = second.next;\n second.next = first;\n current.next = second;\n current = current.next.next;\n }\n return dummy.next;\n}\n```\n```c++ []\nListNode* swapPairs(ListNode* head) {\n ListNode* dummy = new ListNode(0);\n dummy->next = head;\n ListNode* current = dummy;\n while (current->next != NULL && current->next->next != NULL) {\n ListNode* first = current->next;\n ListNode* second = current->next->next;\n first->next = second->next;\n second->next = first;\n current->next = second;\n current = current->next->next;\n }\n return dummy->next;\n}\n```\n```python []\ndef swapPairs(self, head: ListNode) -> ListNode:\n dummy = ListNode(0)\n dummy.next = head\n current = dummy\n while current.next and current.next.next:\n first = current.next\n second = current.next.next\n first.next = second.next\n second.next = first\n current.next = second\n current = current.next.next\n return dummy.next\n```\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n![BREUSELEE.webp]()\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A\n \u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \n
2,375
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
2,715
15
# Approach\n\n1. Check if the list is empty or contains only one node. If so, there is no need to perform any swaps, so the original head is returned.\n2. Initialize three pointers: `newHead` to store the new head after swapping, `prev` to keep track of the previous node, and `curr` to iterate through the list.\n3. Enter a loop that continues as long as both `curr` and `curr->next` are not null.\n4. Inside the loop, create a pointer `next` to store the next node after `curr`.\n5. Update the next pointers of `curr` and `next` to perform the swap. Set `curr->next` to `next->next` to connect `curr` with the next pair of nodes.\n6. Set `next->next` to `curr` to swap the positions of `curr` and `next`.\n7. If `prev` is not null, update its `next` pointer to `next` to connect the previous pair with the swapped pair.\n8. Update `prev` to `curr` and `curr` to `curr->next` to move forward in the list.\n9. After the loop ends, return `newHead`, which stores the new head of the swapped list.\n\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this algorithm is O(n), where n is the number of nodes in the linked list. This is because the algorithm iterates through the list once. The space complexity is O(1) because it uses a constant amount of additional space to store the pointers.\n\n# C++\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* swapPairs(ListNode* head) {\n if (!head || !head->next) {\n return head;\n }\n ListNode* newHead = head->next;\n ListNode* prev = nullptr;\n ListNode* curr = head;\n \n while (curr && curr->next) {\n ListNode* next = curr->next;\n curr->next = next->next;\n next->next = curr;\n \n if (prev) {\n prev->next = next;\n }\n \n prev = curr;\n curr = curr->next;\n }\n \n return newHead;\n }\n};\n```\n---\n# JAVA\n```\nclass Solution {\n public ListNode swapPairs(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n \n ListNode newHead = head.next;\n ListNode prev = null;\n ListNode curr = head;\n \n while (curr != null && curr.next != null) {\n ListNode next = curr.next;\n curr.next = next.next;\n next.next = curr;\n \n if (prev != null) {\n prev.next = next;\n }\n \n prev = curr;\n curr = curr.next;\n }\n \n return newHead;\n }\n}\n```\n---\n# Python\n```\nclass Solution(object):\n def swapPairs(self, head):\n if not head or not head.next:\n return head\n \n new_head = head.next\n prev = None\n curr = head\n \n while curr and curr.next:\n next = curr.next\n curr.next = next.next\n next.next = curr\n \n if prev:\n prev.next = next\n \n prev = curr\n curr = curr.next\n \n return new_head\n```\n---\n# JavaScript\n```\nvar swapPairs = function(head) {\n if (!head || !head.next) {\n return head;\n }\n \n var newHead = head.next;\n var prev = null;\n var curr = head;\n \n while (curr && curr.next) {\n var next = curr.next;\n curr.next = next.next;\n next.next = curr;\n \n if (prev) {\n prev.next = next;\n }\n \n prev = curr;\n curr = curr.next;\n }\n \n return newHead;\n};\n\n```
2,380
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
508
7
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere we are using a very simple and easy ***recursive*** approach to solve this\n\n\n**Steps:**\n\n1. At first we will check, if head value is null we will return null.\n\n `if(head==null) return null;`\n2. Then we check, if next head value is null we will return current head.\n\n `if (head.next == null) return head;`\n3. Later we will swap the 2 value of by creating a temp variable & recursively swapping the values.\n \n - Storing the next head to a temp ListNode that we will return at last. `ListNode temp = head.next;`\n - Then we get the call the function recursively for next head. \n `head.next = swapPairs(temp.next);`\n - Then we swap value next temp with the head.\n `temp.next = head;`\n4. At last we will return the temp ListNode we created .\n \n `return temp;`\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n\n\n```\nclass Solution {\n public ListNode swapPairs(ListNode head) {\n \n if(head==null) return null;\n if (head.next == null) return head;\n\n ListNode temp = head.next;\n head.next = swapPairs(temp.next);\n temp.next = head;\n\n return temp;\n }\n}\n```\n\n<!-- ---\n**Iterative** \n```\npublic ListNode swapPairs1(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n ListNode pre = new ListNode(0), p = head, ret = head.next;\n while (p != null && p.next != null) {\n ListNode nxt = p.next;\n p.next = nxt.next;\n nxt.next = p;\n pre.next = nxt;\n pre = p;\n p = p.next;\n }\n return ret;\n}\n``` -->\n\n![please-upvote-and.jpg]()\n\n\n\n\n
2,384
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
837
11
```\nclass Solution:\n def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n count=0\n temp=head\n while temp:\n temp=temp.next\n count+=1\n n=count//k #No. of groups to be reversed\n prev=dummy=ListNode()\n dummy.next=head\n while n:\n curr=prev.next\n nex=curr.next\n for i in range(1,k): #If we have to reverse k nodes then k-1 links will be reversed\n curr.next=nex.next\n nex.next=prev.next\n prev.next=nex\n nex=curr.next\n prev=curr\n n-=1\n return dummy.next\n```\n**An upvote will be encouraging**
2,428
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
44,334
334
Use a dummy head, and\n\nl, r : define reversing range\n\npre, cur : used in reversing, standard reverse linked linked list method\n\njump : used to connect last node in previous k-group to first node in following k-group\n\n def reverseKGroup(self, head, k):\n dummy = jump = ListNode(0)\n dummy.next = l = r = head\n \n while True:\n count = 0\n while r and count < k: # use r to locate the range\n r = r.next\n count += 1\n if count == k: # if size k satisfied, reverse the inner linked list\n pre, cur = r, l\n for _ in range(k):\n cur.next, cur, pre = pre, cur.next, cur # standard reversing\n jump.next, jump, l = pre, l, r # connect two k-groups\n else:\n return dummy.next
2,437
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
2,448
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nReverse k nodes and then do recursion.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**IMPORTANT: Read the comments in the code, they are self-explanatory.**\n1. Reverse k nodes initially.\n2. Call for the remaining \'len - k\' nodes, where len = length of the Linked List.\n3. Connect the kth node of the k nodes reversed linked list to the head of the remaining linked list.\n\n# Complexity\n- Time complexity: **O(len)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(len) for the length function\nO(len/k) for the loop inside reverseKGroup\nO(len) for the recursive calls inside reverseKGroup\n\nOverall ~ O(len)\n\n- Space complexity:**O(len)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nlen = length of the linked list, this is due to recursive call stack.\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n int length (ListNode* head)\n {\n int len = 0;\n while(head != NULL)\n {\n len++;\n head = head -> next;\n }\n return len;\n }\n\n ListNode* reverseKGroup(ListNode* head, int k) {\n \n //head = 1\n\n int len = length(head); //Calculate length of LL\n if(len < k) //As mentioned in aue, if len < k don\'t reverse\n {\n return head;\n }\n int cnt = 0;\n ListNode* curr = head; //1 --- After 1st step, curr = 2\n ListNode* prev = NULL; //NULL\n ListNode* forward = NULL;\n\n while(curr != NULL && cnt < k) //Reverseing \'k\' nodes initially\n {\n forward = curr -> next; //2 --- 3\n curr -> next = prev; //1 -> 2 is broken and NULL <- 1 --- 2 -> 1\n prev = curr; //prev = 1 --- prev = 2\n curr = forward; // curr = 2 --- curr = 3\n cnt++;\n }\n if(forward != NULL)\n {\n head -> next = reverseKGroup(forward, k); //Recursively calling for remaining nodes\n }\n //I\'ve stored it in head -> next bcz, head = 1 and I\'ve coneected it with 4, head of the new LL\n\n return prev; // return prev bcz, 2 is the head of our final LL and it is stored in prev\n }\n};\n```
2,438
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
6,868
21
# Intuition:\nWe can use a two-pointer approach to reverse the linked list in groups of k nodes. We will maintain a `prevGroupTail` pointer that will point to the tail of the previous reversed group, and we will connect it to the head of the current group after reversing it. We will also use a `dummy` node as the head of the resulting list to avoid edge cases.\n\n# Approach:\n1. Create a dummy node and set its next to the head of the input list.\n2. Initialize a `prevGroupTail` pointer to the dummy node.\n3. Loop through the list until we reach the end.\n4. In each iteration, set `groupStart` to the current `head`, and find `groupEnd` using the `getGroupEnd` function, which returns the end node of the current group (which is `k` nodes away from the `groupStart`). If `groupEnd` is null, then we don\'t need to reverse the remaining nodes because there are less than `k` nodes left in the list.\n5. Set `nextGroupStart` to `groupEnd->next`, and then set `groupEnd->next` to null to separate the group to be reversed from the rest of the list.\n6. Reverse the current group using the `reverseList` function and set `prevGroupTail->next` to the new head of the reversed group. Then set `groupStart->next` to `nextGroupStart`.\n7. Update `prevGroupTail` to the `groupStart`.\n8. Set `head` to `nextGroupStart`.\n9. Return the head of the resulting list (which is the `dummy->next` node).\n\n# Complexity\n- Time Complexity:\nThe time complexity of the algorithm is O(n), where n is the number of nodes in the list, since we visit each node once.\n\n- Space Complexity:\nThe space complexity of the algorithm is O(1), since we only use a constant amount of extra space for the `dummy` and `prevGroupTail` nodes, and we reverse the list in-place without using any additional data structures.\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* reverseKGroup(ListNode* head, int k) {\n ListNode* dummy = new ListNode(0);\n dummy->next = head;\n ListNode* prevGroupTail = dummy;\n \n while (head) {\n ListNode* groupStart = head;\n ListNode* groupEnd = getGroupEnd(head, k);\n \n if (!groupEnd) {\n break; // Remaining nodes are less than k, so no need to reverse\n }\n \n ListNode* nextGroupStart = groupEnd->next;\n groupEnd->next = nullptr; // Separate the group to be reversed\n \n // Reverse the group\n prevGroupTail->next = reverseList(groupStart);\n groupStart->next = nextGroupStart;\n \n prevGroupTail = groupStart;\n head = nextGroupStart;\n }\n \n ListNode* newHead = dummy->next;\n delete dummy;\n return newHead;\n }\n \nprivate:\n ListNode* getGroupEnd(ListNode* head, int k) {\n while (head && k > 1) {\n head = head->next;\n k--;\n }\n return head;\n }\n \n ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr;\n ListNode* curr = head;\n \n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n \n return prev;\n }\n};\n\n```\n\n---\n# Java\n```\nclass Solution {\n public ListNode reverseKGroup(ListNode head, int k) {\n ListNode dummy = new ListNode(0);\n dummy.next = head;\n ListNode prevGroupTail = dummy;\n\n while (head != null) {\n ListNode groupStart = head;\n ListNode groupEnd = getGroupEnd(head, k);\n\n if (groupEnd == null)\n break;\n\n prevGroupTail.next = reverseList(groupStart, groupEnd.next);\n prevGroupTail = groupStart;\n head = prevGroupTail.next;\n }\n\n ListNode newHead = dummy.next;\n return newHead;\n }\n\n private ListNode getGroupEnd(ListNode head, int k) {\n while (head != null && --k > 0)\n head = head.next;\n return head;\n }\n\n private ListNode reverseList(ListNode head, ListNode stop) {\n ListNode prev = stop;\n while (head != stop) {\n ListNode next = head.next;\n head.next = prev;\n prev = head;\n head = next;\n }\n return prev;\n }\n}\n\n```\n\n---\n\n# Python\n```\nclass Solution(object):\n def reverseKGroup(self, head, k):\n dummy = ListNode(0)\n dummy.next = head\n prevGroupTail = dummy\n\n while head:\n groupStart = head\n groupEnd = self.getGroupEnd(head, k)\n\n if not groupEnd:\n break\n\n prevGroupTail.next = self.reverseList(groupStart, groupEnd.next)\n prevGroupTail = groupStart\n head = prevGroupTail.next\n\n newHead = dummy.next\n return newHead\n\n def getGroupEnd(self, head, k):\n while head and k > 1:\n head = head.next\n k -= 1\n return head\n\n def reverseList(self, head, stop):\n prev = stop\n while head != stop:\n next = head.next\n head.next = prev\n prev = head\n head = next\n return prev\n```\n---\n# JavaScript\n```\nvar reverseKGroup = function(head, k) {\n var dummy = new ListNode(0);\n dummy.next = head;\n var prevGroupTail = dummy;\n\n while (head) {\n var groupStart = head;\n var groupEnd = getGroupEnd(head, k);\n\n if (!groupEnd)\n break;\n\n prevGroupTail.next = reverseList(groupStart, groupEnd.next);\n prevGroupTail = groupStart;\n head = prevGroupTail.next;\n }\n var newHead = dummy.next;\n return newHead;\n}\n\nvar getGroupEnd = function(head, k) {\n while (head && k > 1) {\n head = head.next;\n k--;\n }\n return head;\n}\n\nvar reverseList = function(head, stop) {\n var prev = stop;\n while (head !== stop) {\n var next = head.next;\n head.next = prev;\n prev = head;\n head = next;\n }\n return prev;\n}\n```
2,451
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
2,543
15
# Iterative solution:\n```python3 []\nclass Solution:\n def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n def getGroupEnd(cur, k):\n while k > 1 and cur.next:\n cur = cur.next \n k-=1\n return cur if k == 1 else None\n\n def reverseGroup(start, end):\n prev, cur, new_group_start = None, start, end.next\n while cur != new_group_start:\n cur.next, cur, prev = prev, cur.next, cur \n\n dummy = ListNode()\n prev_group = dummy\n while head:\n group_start = head\n group_end = getGroupEnd(head, k)\n if not group_end: break # not enough todes to make a new group\n next_group_start = group_end.next # save link to the next group start\n reverseGroup(group_start, group_end) # reverse the current group\n prev_group.next = group_end # group_end is the start of the reversed group\n prev_group = group_start # group_start is the end of the reversed group\n group_start.next = next_group_start # link current reversed group with the next group\n head = next_group_start # move current point to the start of the next group\n\n return dummy.next \n```\n```python3 []\nclass Solution:\n def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n dummy = ListNode()\n prev_group = dummy\n while head:\n j, group_end = 1, head #start of group = end after reverse\n while j < k and head.next:\n head = head.next \n j+=1\n group_start = head #end of group = start after reverse\n next_group = head = head.next #start of next group\n\n if j != k: #don\'t need reverse (not enough nodes)\n break\n #reverse current group without links to prev and next groups\n prev, cur = None, group_end\n while cur != next_group:\n cur.next, cur, prev = prev, cur.next, cur \n\n prev_group.next = group_start\n prev_group = group_end\n group_end.next = next_group\n\n return dummy.next \n```\n![Screenshot 2023-08-03 at 03.09.07.png]()\n# Recursive solution:\n```python3 []\nclass Solution:\n def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n if not head: return\n start, end = head, head\n for _ in range(k):\n if not end: return head\n end = end.next\n \n # reverse diapason [start:end)\n def reverse(start, end):\n prev = None\n while start != end:\n start.next, start, prev = prev, start.next, start\n return prev # return head node of the reversed group\n \n newHead = reverse(start, end)\n start.next = self.reverseKGroup(end, k)\n\n return newHead\n```\n![Screenshot 2023-08-03 at 04.06.16.png]()\n\n
2,457
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
4,618
93
```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nclass Solution:\n def reverseKGroup(self, head: ListNode, k: int) -> ListNode: \n # Check if we need to reverse the group\n curr = head\n for _ in range(k):\n if not curr: return head\n curr = curr.next\n\t\t \n\t\t\t\t\n # Reverse the group (basic way to reverse linked list)\n prev = None\n curr = head\n for _ in range(k):\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n \n\t\t\n # After reverse, we know that `head` is the tail of the group.\n\t\t# And `curr` is the next pointer in original linked list order\n head.next = self.reverseKGroup(curr, k)\n return prev\n ```
2,470
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
175,562
1,168
# Intuition:\nThe Intuition is to use two pointers, `i` and `j`, to iterate through the array. The variable `j` is used to keep track of the current index where a unique element should be placed. The initial value of `j` is 1 since the first element in the array is always unique and doesn\'t need to be changed.\n\n# Explanation:\nThe code starts iterating from `i = 1` because we need to compare each element with its previous element to check for duplicates.\n\nThe main logic is inside the `for` loop:\n1. If the current element `nums[i]` is not equal to the previous element `nums[i - 1]`, it means we have encountered a new unique element.\n2. In that case, we update `nums[j]` with the value of the unique element at `nums[i]`, and then increment `j` by 1 to mark the next position for a new unique element.\n3. By doing this, we effectively overwrite any duplicates in the array and only keep the unique elements.\n\nOnce the loop finishes, the value of `j` represents the length of the resulting array with duplicates removed.\n\nFinally, we return `j` as the desired result.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n int j = 1;\n for(int i = 1; i < nums.size(); i++){\n if(nums[i] != nums[i - 1]){\n nums[j] = nums[i];\n j++;\n }\n }\n return j;\n }\n};\n```\n```Java []\nclass Solution {\n public int removeDuplicates(int[] nums) {\n int j = 1;\n for (int i = 1; i < nums.length; i++) {\n if (nums[i] != nums[i - 1]) {\n nums[j] = nums[i];\n j++;\n }\n }\n return j;\n }\n}\n```\n```Python3 []\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n j = 1\n for i in range(1, len(nums)):\n if nums[i] != nums[i - 1]:\n nums[j] = nums[i]\n j += 1\n return j\n```\n\n![CUTE_CAT.png]()\n\n**If you are a beginner solve these problems which makes concepts clear for future coding:**\n1. [Two Sum]()\n2. [Roman to Integer]()\n3. [Palindrome Number]()\n4. [Maximum Subarray]()\n5. [Remove Element]()\n6. [Contains Duplicate]()\n7. [Add Two Numbers]()\n8. [Majority Element]()\n9. [Remove Duplicates from Sorted Array]()\n10. **Practice them in a row for better understanding and please Upvote the post for more questions.**\n\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**
2,500
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
52,009
575
\n## \u2705 Method 1: sort in place using `[:]`\n```\n\tdef removeDuplicates(self, nums: List[int]) -> int:\n\t\tnums[:] = sorted(set(nums))\n\t\treturn len(nums)\n```\n\n\n**Time Complexity:** `O(n)`\n**Space Complexity:** `O(1)`\n\n\n### \u274C Common Wrong Answers:\n```\n\tnums = sorted(set(nums))\n\treturn len(nums)\n```\n\xA0`nums =`\xA0 doesn\'t replace elements in the original list.\n `nums[:] =`\xA0replaces element in place\n\nIn short, without `[:]`, we\'re creating a new list object, which is against what this problem is asking for:\n"Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory."\n\n-----------------------\n## \u2705 Method 2: Two-pointers\n### \uD83E\uDD14 Initial Intuition:\nUse a `slow` pointer to "lock" the "wanted" element, and use a `fast` pointer to move forward along the list and look for new unique elements in the list.\nOr, in other words, the current `slow` pointer is used to locate the latest unique number for the results, and `fast` is used for iterating and discovery.\n\nHave `fast` advanced in every iteration, but `slow` is only advanced when two pointers are onto two different elements. \n\nThat means, the elements after `nums[slow]` and before `nums[fast]` are numbers we\'ve **seen** before and don\'t need anymore (one copy of these numbers is already saved before the current `slow` (inclusive)). \n\nTherefore, in order to have this newly discovered (unseen) number pointed by the current `fast` to the front of the array for the final answer, we just need to swap this newly discovered number to the location that follows the current `slow` pointer, with one of the **seen** numbers (we don\'t need it for the answer regardlessly), and then advance the `slow` in the same iteration to lock this new number.\n\n```\n\tdef removeDuplicates(self, nums: List[int]) -> int:\n\t\tslow, fast = 0, 1\n\t\twhile fast in range(len(nums)):\n\t\t\tif nums[slow] == nums[fast]:\n\t\t\t\tfast += 1\n\t\t\telse:\n\t\t\t\tnums[slow+1] = nums[fast]\n\t\t\t\tfast += 1\n\t\t\t\tslow += 1\n\n\t\treturn slow + 1\n```\n\n### \u2747\uFE0F Simplified two-pointers with for loops:\n\uD83D\uDCA1 However, observe, `fast` pointer is simply incremented in every iteration regardless of the conditions, that\'s just a typical for loop\'s job. Therefore, we can simplify this "two-pointers" system as follows:\n```\n\tdef removeDuplicates(self, nums: List[int]) -> int:\n\t\tj = 0\n\t\tfor i in range(1, len(nums)):\n\t\t\tif nums[j] != nums[i]:\n\t\t\t\tj += 1\n\t\t\t\tnums[j] = nums[i]\n\t\treturn j + 1\n```\n\n**Time Complexity:** `O(n)`\n**Space Complexity:** `O(1)`\n\n-----------------------\n## Method 3: Using `.pop()`\n```\n\tdef removeDuplicates(self, nums: List[int]) -> int:\n\t\ti = 1\n\t\twhile i < len(nums):\n\t\t\tif nums[i] == nums[i - 1]:\n\t\t\t\tnums.pop(i)\n\t\t\telse:\n\t\t\t\ti += 1\n\t\treturn len(nums)\n```\n-----------------------\n## Method 4: Using `OrderedDict.fromkeys()`\n```\nfrom collections import OrderedDict\nclass Solution(object):\n def removeDuplicates(self, nums):\n nums[:] = OrderedDict.fromkeys(nums)\n return len(nums)\n```\n-------------------\n-----------------------\nAs a total beginner, I am writing these all out to help myself, and hopefully also help anyone out there who is like me at the same time.\n\nPlease upvote\u2B06\uFE0F if you find this helpful or worth-reading for beginners in anyway.\nYour upvote is much more than just supportive to me. \uD83D\uDE33\uD83E\uDD13\uD83E\uDD70\n\nIf you find this is not helpful, needs improvement, or is questionable, would you please leave a quick comment below to point out the problem before you decide to downvote? It will be very helpful for me (maybe also others) to learn as a beginner.\n\nThank you very much either way \uD83E\uDD13.
2,502
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
627
10
\n\nOne option is to use the pop() method to pop any duplicates that are detected, but using pop() is actually very inefficient because if we pop an element near the start of the array, we now have to shift all the other elements back 1 space. So each pop() runs in O(n) time, and in the worst case, we\'d have to pop n-1 elements, so the algorithm would run in O(n<sup>2</sup>) time.\n\nInstead, we\'ll use an O(n) 2-pointer approach. One pointer, `replace`, will keep track of which element we need to overwrite/replace. The other one, loop variable `i`, will traverse the entire array and detect duplicates. Since we know the array is already sorted, we can detect duplicates by comparing each element to the one before it. If they\'re the same, then we\'ve found a duplicate.\n\nIf a duplicate is found, we just keep incrementing `i` while keeping `replace` at the same spot. Basically, we keep searching for the next unique element. Once a unique element is found, we overwrite the element at the `replace`index with the unique one we just found. Then we increment `replace` so that it\'s ready to write at the next slot.\n\nAt the end, we can just return `replace` since it\'s been keeping track of the index of the last unique element written.\n\n# Code\n```\nclass Solution(object):\n def removeDuplicates(self, nums):\n replace = 1\n for i in range(1, len(nums)):\n if nums[i-1] != nums[i]:\n nums[replace] = nums[i]\n replace += 1\n return replace\n```
2,505
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
7,465
43
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to remove duplicates from a sorted integer array nums while keeping track of the number of unique elements. The function should return the count of unique elements and modify the input array in-place to contain only the unique elements at the beginning in the same order.\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. First, we check if the input vector nums is empty. If it is empty, there are no unique elements, so we return 0.\n\n2. We initialize a variable k to 1. This variable will keep track of the count of unique elements in the modified nums array.\n\n3. We iterate through the input vector nums starting from the second element (index 1) using a for loop.\n\n4. Inside the loop, we compare the current element nums[i] with the previous unique element nums[k - 1]. If they are not equal, it means we have encountered a new unique element. In this case, we update the nums[k] position with the current element to keep it in place. We then increment k to indicate that we have found one more unique element.\n\n5. After the loop completes, k contains the count of unique elements, and the first k elements of the nums vector contain the unique elements in the same order they appeared in the input.\n\n6. We return the value of k as the final count of unique elements.\n\n---\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this algorithm is O(n), where n is the number of elements in the input vector nums. This is because we iterate through the input vector once, and each iteration takes constant time.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of this algorithm is O(1) because it modifies the input array in-place without using any additional data structures that depend on the size of the input.\n\n---\n\n# \uD83D\uDCA1"If you have advanced to this point, I kindly request that you consider upvoting this solution to broaden its reach among others."\u2763\uFE0F\uD83D\uDCA1\n\n---\n\n```C++ []\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n if (nums.empty()) {\n return 0;\n }\n\n int k = 1; // Initialize the count of unique elements to 1\n for (int i = 1; i < nums.size(); i++) {\n if (nums[i] != nums[i - 1]) {\n nums[k] = nums[i]; // Overwrite the next unique element\n k++;\n }\n }\n \n return k;\n }\n};\n\n```\n```Java []\npublic class Solution {\n public int removeDuplicates(int[] nums) {\n if (nums.length == 0) {\n return 0;\n }\n\n int k = 1; // Initialize the count of unique elements to 1\n for (int i = 1; i < nums.length; i++) {\n if (nums[i] != nums[k - 1]) {\n nums[k] = nums[i]; // Overwrite the next unique element\n k++;\n }\n }\n \n return k;\n }\n}\n\n```\n```Python []\nclass Solution:\n def removeDuplicates(self, nums):\n if not nums:\n return 0\n \n k = 1 # Initialize the count of unique elements to 1\n for i in range(1, len(nums)):\n if nums[i] != nums[i - 1]:\n nums[k] = nums[i] # Overwrite the next unique element\n k += 1\n \n return k\n\n```\n```Javascript []\nfunction removeDuplicates(nums) {\n if (nums.length === 0) {\n return 0;\n }\n\n let k = 1; // Initialize the count of unique elements to 1\n for (let i = 1; i < nums.length; i++) {\n if (nums[i] !== nums[k - 1]) {\n nums[k] = nums[i]; // Overwrite the next unique element\n k++;\n }\n }\n\n return k;\n}\n\n```\n```C []\nint removeDuplicates(int* nums, int numsSize) {\n if (numsSize == 0) {\n return 0;\n }\n\n int k = 1; // Initialize the count of unique elements to 1\n for (int i = 1; i < numsSize; i++) {\n if (nums[i] != nums[k - 1]) {\n nums[k] = nums[i]; // Overwrite the next unique element\n k++;\n }\n }\n\n return k;\n}\n\n```\n```Ruby []\nclass Solution\n def remove_duplicates(nums)\n return 0 if nums.empty?\n\n k = 1 # Initialize the count of unique elements to 1\n (1...nums.size).each do |i|\n if nums[i] != nums[k - 1]\n nums[k] = nums[i] # Overwrite the next unique element\n k += 1\n end\n end\n\n k\n end\nend\n\n```\n\n# Do Upvote if you like the solution and Explanation please \u2763\uFE0F
2,506
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
33,894
169
# 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 removeDuplicates(self, nums: List[int]) -> int:\n i,j=0,1\n while i<=j and j<len(nums):\n if nums[i]==nums[j]:\n j+=1\n else:\n nums[i+1]=nums[j]\n i+=1\n return i+1\n\n\n \n```\n# Consider upvoting if found helpul\n \n![57jfh9.jpg]()\n
2,507
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
23,353
69
# Intuition:\nThe problem requires us to remove duplicate elements from a sorted array, i.e., we need to keep only one copy of each element in the array. Since the array is sorted, all duplicate elements will be adjacent to each other, so we can easily remove them by shifting the subsequent elements of the array to the left.\n\n# Approach:\nWe can use two pointers i and j, where i points to the last unique element found so far, and j points to the current element being examined. If nums[i] and nums[j] are equal, we just increment j. Otherwise, we increment i and copy nums[j] to nums[i]. At the end, we return i+1, which represents the length of the modified array.\n\n# Complexity:\n- Time complexity: Since we only traverse the array once, the time complexity of the algorithm is O(n).\n- Space complexity: The algorithm uses constant extra space, so the space complexity is O(1).\n\n# C++\n```\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n int i = 0;\n for (int j = 1; j < nums.size(); j++) {\n if (nums[i] != nums[j]) {\n i++;\n nums[i] = nums[j];\n }\n }\n return i + 1;\n }\n};\n```\n# JavaScript\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar removeDuplicates = function(nums) {\n let i = 0;\n for (let j = 1; j < nums.length; j++) {\n if (nums[i] !== nums[j]) {\n i++;\n nums[i] = nums[j];\n }\n }\n return i + 1;\n}\n\n```\n# Java\n```\nclass Solution {\n public int removeDuplicates(int[] nums) {\n int i = 0;\n for (int j = 1; j < nums.length; j++) {\n if (nums[i] != nums[j]) {\n i++;\n nums[i] = nums[j];\n }\n }\n return i + 1;\n }\n}\n\n```\n# Python\n```\nclass Solution(object):\n def removeDuplicates(self, nums):\n i = 0\n for j in range(1, len(nums)):\n if nums[i] != nums[j]:\n i += 1\n nums[i] = nums[j]\n return i + 1\n\n```\n\n**THANK YOU**
2,539
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
53,959
294
Given a sorted array and we need to return the length of the unique elements instead of the entire array. There is no need to delete the duplicate elements also. \n* Since, our first element is already present at index 0 (**it is a unique element**), we quickly run a for loop for the entire array to scan for unique elements.\n* If the current element and the next element are the same, then we just keep on going till we find a different element\n* Once we find a different element, it is inserted at index 1, because, index 0 is taken by the first unique element. \n* Once this is done, the same scanning is done to find out the next unique element and this element is to be inserted at index 2. This process continues until we are done with unique elements.\n* **We use a variable (x = 1) which is incremented to the next index whenever we find a unique element and we insert this element at its corresponding index**.\n```\nx = 1\nfor i in range(len(nums)-1):\n\tif(nums[i]!=nums[i+1]):\n\t\tnums[x] = nums[i+1]\n\t\tx+=1\nreturn(x)\n```
2,581
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
7,943
8
```\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n if len(nums)==1:\n return 1\n x=nums[0]\n i=0\n while i<len(nums)-1:\n if x==nums[1+i]:\n del nums[1+i]\n else:\n x=nums[1+i]\n i+=1\n return i+1\n```
2,599
Remove Element
remove-element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
142,844
1,020
# Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\nThe intuition behind this solution is to iterate through the array and keep track of two pointers: `index` and `i`. The `index` pointer represents the position where the next non-target element should be placed, while the `i` pointer iterates through the array elements. By overwriting the target elements with non-target elements, the solution effectively removes all occurrences of the target value from the array.\r\n# Approach\r\n<!-- Describe your approach to solving the problem. -->\r\n1. Initialize `index` to 0, which represents the current position for the next non-target element.\r\n2. Iterate through each element of the input array using the `i` pointer.\r\n3. For each element `nums[i]`, check if it is equal to the target value.\r\n - If `nums[i]` is not equal to `val`, it means it is a non-target element.\r\n - Set `nums[index]` to `nums[i]` to store the non-target element at the current `index` position.\r\n - Increment `index` by 1 to move to the next position for the next non-target element.\r\n4. Continue this process until all elements in the array have been processed.\r\n5. Finally, return the value of `index`, which represents the length of the modified array.\r\n\r\n# Complexity\r\n- Time complexity:\r\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\r\n$$ O(n) $$\r\n- Space complexity:\r\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\r\n$$ O(1) $$\r\n\r\n# Code\r\n```C++ []\r\nclass Solution {\r\npublic:\r\n int removeElement(vector<int>& nums, int val) {\r\n int index = 0;\r\n for(int i = 0; i< nums.size(); i++){\r\n if(nums[i] != val){\r\n nums[index] = nums[i];\r\n index++;\r\n }\r\n }\r\n return index;\r\n }\r\n};\r\n```\r\n```Java []\r\nclass Solution {\r\n public int removeElement(int[] nums, int val) {\r\n int index = 0;\r\n for (int i = 0; i < nums.length; i++) {\r\n if (nums[i] != val) {\r\n nums[index] = nums[i];\r\n index++;\r\n }\r\n }\r\n return index;\r\n }\r\n}\r\n```\r\n```Python3 []\r\nclass Solution:\r\n def removeElement(self, nums: List[int], val: int) -> int:\r\n index = 0\r\n for i in range(len(nums)):\r\n if nums[i] != val:\r\n nums[index] = nums[i]\r\n index += 1\r\n return index\r\n```\r\n\r\n![CUTE_CAT.png]()\r\n\r\n\r\n**If you are a beginner solve these problems which makes concepts clear for future coding:**\r\n1. [Two Sum]()\r\n2. [Roman to Integer]()\r\n3. [Palindrome Number]()\r\n4. [Maximum Subarray]()\r\n5. [Remove Element]()\r\n6. [Contains Duplicate]()\r\n7. [Add Two Numbers]()\r\n8. [Majority Element]()\r\n9. [Remove Duplicates from Sorted Array]()\r\n10. **Practice them in a row for better understanding and please Upvote for more questions.**\r\n\r\n\r\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**\r\n
2,600
Remove Element
remove-element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
912
12
\n\nOne way to do this is to check every element of `nums`, and if an element is equal to `val`, then we use the pop method to pop it off. This works, but the problem is that the pop method is very inefficient because if we pop an element near the start of the array, all the other elements have to be shifted back one spot. Each shift runs in O(n) time, and in the worst case, we\'d have to do n shifts, so this algorithm ends up running in O(n<sup>2</sup>) time.\n\nInstead, we can use a two pointer approach that overwrites the first `k` elements of the array, where `k` is the number of elements that are not equal to `val`. The index variable `i` keeps track of the next spot to overwrite in the array, and we use `x` to check the value of each element and compare it to `val`.\n\nIf an element is equal to `val`, we just move on and don\'t do anything. Basically, we keep searching until we find an element that is not equal to `val`. Once we do find an element not equal to `val`, we write it to the array at index `i`, then increment `i` so that it\'s ready to write at the next spot.\n\nAt the end, we can just return `i` since it has been incremented exactly once for each element found that is not equal to `val`.\n\n```\nclass Solution(object):\n def removeElement(self, nums, val):\n i = 0\n for x in nums:\n if x != val:\n nums[i] = x\n i += 1\n return i\n```
2,607
Remove Element
remove-element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
29,651
117
# 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 removeElement(self, nums: List[int], val: int) -> int:\n while val in nums:\n nums.remove(val)\n#please upvote me it would encourage me alot\n\n```
2,609
Remove Element
remove-element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
18,135
46
# Intuition:\nThe problem requires removing all occurrences of a given value val from a given integer array nums and returning the new length of the resulting array after the removal.\n\n# Approach:\nThe approach taken here is to keep a counter variable count for keeping track of elements other than val and then loop through all the elements of the array. For each element, if it\'s not equal to val, it is placed at index count of the array, and count is incremented.\n\nFinally, the length of the new array is equal to count. This approach modifies the input array in-place without using any additional space.\n\n# Complexity:\n- Time Complexity: The time complexity of this approach is O(n) since we are traversing the entire array once.\n- Space Complexity: The space complexity of this approach is O(1) since we are not using any additional space.\n\n# C++\n```\nclass Solution {\npublic:\n int removeElement(vector<int>& nums, int val) {\n // Counter for keeping track of elements other than val\n int count = 0;\n // Loop through all the elements of the array\n for (int i = 0; i < nums.size(); i++) {\n // If the element is not val\n if (nums[i] != val) {\n nums[count++] = nums[i];\n }\n }\n return count;\n }\n};\n\n```\n# JAVASCRIPT\n```\nfunction removeElement(nums, val) {\n // Counter for keeping track of elements other than val\n let count = 0;\n // Loop through all the elements of the array\n for (let i = 0; i < nums.length; i++) {\n // If the element is not val\n if (nums[i] !== val) {\n nums[count++] = nums[i];\n }\n }\n return count;\n}\n\n```\n# JAVA\n```\nclass Solution {\n public int removeElement(int[] nums, int val) {\n // Counter for keeping track of elements other than val\n int count = 0;\n // Loop through all the elements of the array\n for (int i = 0; i < nums.length; i++) {\n // If the element is not val\n if (nums[i] != val) {\n nums[count++] = nums[i];\n }\n }\n return count;\n }\n}\n\n```\n# Python\n```\nclass Solution(object):\n def removeElement(self, nums, val):\n # Counter for keeping track of elements other than val\n count = 0\n # Loop through all the elements of the array\n for i in range(len(nums)):\n # If the element is not val\n if nums[i] != val:\n nums[count] = nums[i]\n count += 1\n return count\n\n```\n\n***THANK YOU***
2,634
Remove Element
remove-element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
4,418
8
```\nGiven : val = 2\n1 2 2 2 5 2 5 \ni j\nFirst Start from the far end \n1 2 2 2 5 2 5 \n i j\nwhen nums[i] == val , nums[i] = nums[j]\n1 2 2 2 5 2 5 \n i j \nif(num[j]) is also val then move it left till its not\n1 5 5 2 2 2 5 \n i j \nwhen i==j.. stop\n1 5 5 2 2 2 5 \n i,j\nyou see that i can still be val, \nso we check before returning the answer \n\n\n\n```\n\n\n```\n def removeElement(self, nums: List[int], val: int) -> int:\n\n i,j=0,len(nums)-1;\n if(j==-1): return 0\n while(i<j):\n if(nums[i]==val):\n while(i<j and nums[j]==val): \n j-=1\n nums[i]=nums[j];\n j-=1\n continue;\n i+=1\n return i+1 if nums[i]!=val else i\n\n```
2,643
Remove Element
remove-element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
42
5
# 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 removeElement(self, nums: List[int], val: int) -> int:\n if not nums:\n return 0\n\n left = 0 \n right = len(nums) - 1 \n\n while left <= right:\n if nums[left] == val:\n nums[left], nums[right] = nums[right], nums[left] \n right -= 1 \n else:\n left += 1\n \n return left\n```
2,662
Remove Element
remove-element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
39,506
334
def removeElement(self, nums, val):\n i = 0\n for x in nums:\n if x != val:\n nums[i] = x\n i += 1\n return i
2,674
Remove Element
remove-element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
3,754
8
# Intuition\nSeems like any other pythonic list comprehension problem. Only hurdle is that it has to be in place\n# Approach\nBy using nums[:] you can make it in place\n# Complexity\n- Time complexity:\n\n- Space complexity:\n\n# Code\n```\nclass Solution:\n def removeElement(self, nums: List[int], val: int) -> int:\n\n nums[:] = [num for num in nums if num != val]\n \n return len(nums)\n```
2,676
Remove Element
remove-element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
5,406
23
```\nclass Solution:\n def removeElement(self, nums: List[int], val: int) -> int:\n k=0\n for i in range(len(nums)):\n if nums[i]==val:\n continue\n nums[k]=nums[i]\n k+=1\n return k\n```
2,686
Remove Element
remove-element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
2,340
8
\nSee the code : **\u2B50[]()\u2B50**\n\n**Submissioon detail**\n![image]()\n![image]()\n![image]()\n![image]()\n\n**\uD83E\uDDE1See more LeetCode solution : [Zyrastory - LeetCode Solution]()**
2,699
Divide Two Integers
divide-two-integers
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. Return the quotient after dividing dividend by divisor. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.
Math,Bit Manipulation
Medium
null
20,780
41
1) Define the result\'s sign and operate with positive dividend and divisor.\n2) Calculate the result using the length of range.\n3) Apply the sign.\n4) Apply the 32-bit integer limitations.\n\nNo multiplication, division, or mod used.\n\n\n```\nclass Solution:\n def divide(self, dividend: int, divisor: int) -> int:\n sign = -1 if (dividend >= 0 and divisor < 0) or (dividend < 0 and divisor >= 0) else 1\n dividend = abs(dividend)\n divisor = abs(divisor)\n result = len(range(0, dividend-divisor+1, divisor))\n if sign == -1:\n result = -result\n minus_limit = -(2**31)\n plus_limit = (2**31 - 1)\n result = min(max(result, minus_limit), plus_limit)\n return result\n\n
2,709
Divide Two Integers
divide-two-integers
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. Return the quotient after dividing dividend by divisor. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.
Math,Bit Manipulation
Medium
null
2,199
5
```\nclass Solution:\n def divide(self, dividend: int, divisor: int) -> int:\n n = 0\n md = 1\n if (dividend < 0):\n md = -md\n dividend = abs(dividend)\n if (divisor < 0):\n md = -md\n divisor = abs(divisor)\n nn = 1\n dvd = dividend\n dvr = divisor\n sn = 0\n while (dvd >= dvr):\n nn = 1\n dd = dvr\n while (dvd >= dd):\n sn += nn\n dvd -= dd\n dd += dd\n nn += nn\n\n ans = sn\n\n if (md < 0):\n ans = -ans\n if (ans > 2 ** 31 - 1):\n ans = 2 ** 31 - 1\n if (ans < -2 ** 31):\n ans = -2 ** 31\n return (ans)\n```
2,717
Divide Two Integers
divide-two-integers
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. Return the quotient after dividing dividend by divisor. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.
Math,Bit Manipulation
Medium
null
80,235
263
class Solution:\n # @return an integer\n def divide(self, dividend, divisor):\n positive = (dividend < 0) is (divisor < 0)\n dividend, divisor = abs(dividend), abs(divisor)\n res = 0\n while dividend >= divisor:\n temp, i = divisor, 1\n while dividend >= temp:\n dividend -= temp\n res += i\n i <<= 1\n temp <<= 1\n if not positive:\n res = -res\n return min(max(-2147483648, res), 2147483647)
2,718
Divide Two Integers
divide-two-integers
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. Return the quotient after dividing dividend by divisor. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.
Math,Bit Manipulation
Medium
null
2,314
11
We will follow the **same exact division algorithm we all learn in elementary school** to divide integers, but in binary:\n\n*"We traverse `dividend` from left to right, looking at the first `k` digits, where `k` is the number of digits of `divisor`. If the number formed by those first `k` digits is larger than or equal to `divisor`, then we write `1` in the quotient, subtract and move on to the next digit."*\n\n# Examples\n*53 &div; 3 = 17*\n![image]()\n\n\n*246 &div; 7 = 35*\n![image]()\n\n\n```\nclass Solution:\n def divide(self, dividend: int, divisor: int) -> int:\n if dividend == 0:\n return 0\n\t\t# only case that gives answer outside of [-2 ** 31, 2 ** 31 - 1]\n if dividend == -2 ** 31 and divisor == -1:\n return 2 ** 31 - 1\n\t\t\t\n\t\t# we work with positive numbers only and worry about the sign in the end\n if dividend > 0 and divisor > 0 or dividend < 0 and divisor < 0:\n positiveSign = True\n else:\n positiveSign = False\n dividend, divisor = abs(dividend), abs(divisor)\n\n quotient = 0\n for i in reversed(range(dividend.bit_length() - divisor.bit_length() + 1)):\n if dividend >> i >= divisor:\n dividend -= divisor << i\n quotient |= 1 << i\n \n return quotient if positiveSign else -quotient\n```\n# Notes\n* **Time complexity:** *O(log(`dividend`))*\n* **Space complexity:** *O(1)*\n\nWe don\'t need to worry about `quotient` being smaller than `-2 ** 31` since `abs(quotient) <= abs(dividend) <= 2 ** 31`.\n\nEdit: Updated handling of corner case so that we **only** work with integers in `[-2 ** 31, 2 ** 31 - 1]` at all times.
2,728
Divide Two Integers
divide-two-integers
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. Return the quotient after dividing dividend by divisor. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.
Math,Bit Manipulation
Medium
null
7,099
17
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires us to divide two integers, `dividend` and `divisor`, and return the quotient without using multiplication, division, and mod operator.\n\nWe can solve this problem using bit manipulation and binary search. We can find the largest multiple of the divisor that is less than or equal to the dividend using bit manipulation. Then we can perform division using binary search.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Handle division by zero: If the divisor is 0, return `2**31 - 1`.\n\n- Handle overflow case: If the dividend is `-2**31` and divisor is `-1`, return `2**31 - 1`.\n\n- Get the sign of the result: If both dividend and divisor are negative or positive, the sign of the result will be positive. If either dividend or divisor is negative, the sign of the result will be negative.\n\n- Find the largest multiple of the divisor that is less than or equal to the dividend using bit manipulation. We can do this by left-shifting the divisor and multiple by 1 until the left-shifted divisor is greater than the dividend.\n\n- Perform division using binary search. We can do this by right-shifting the divisor and multiple by 1 until multiple is 0. If the dividend is greater than or equal to the divisor, subtract the divisor from the dividend and add the multiple to the quotient. Repeat until multiple is 0.\n\n- Apply the sign to the quotient and return it.\n\n# Complexity\n- Time complexity: The time complexity of this solution is $$O(log(dividend))$$.\n\nFinding the largest multiple of the divisor that is less than or equal to the dividend takes `log(dividend)` iterations. Performing division using binary search takes `log(dividend) `iterations as well.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: The space complexity of this solution is `O(1)`.\n\nWe only use a constant amount of extra space to store variables.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code Explanation\n\nThe code is an implementation of the binary division algorithm. The algorithm is used to divide two integers (dividend and divisor) and return the quotient (integer division result). Here is how the code works:\n\n- The function accepts two integer parameters, dividend and divisor, and returns an integer (quotient).\n- The function first checks if the divisor is zero. If it is, it returns the maximum 32-bit integer value (2^31 - 1). This is because dividing by zero is not possible, and we need to handle this edge case.\n- The function then checks for an overflow case where the dividend is the minimum 32-bit integer value (-2^31) and the divisor is -1. In this case, the quotient is the maximum 32-bit integer value (2^31 - 1) since dividing the minimum value by -1 would result in an overflow error.\n- The function determines the sign of the result by checking the signs of the dividend and divisor. If both are negative or both are positive, the sign is positive. Otherwise, the sign is negative, and we make both values positive for the next step.\n- The function then finds the largest multiple of the divisor that is less than or equal to the dividend. It does this by left-shifting the divisor and multiple variables (initially set to 1) until the shifted divisor is greater than the dividend. At this point, the last multiple that was less than or equal to the dividend is the largest multiple we need to find. The function keeps track of this multiple value and the divisor value for the next step.\n- The function then performs the division using binary search. It does this by right-shifting the divisor and multiple variables until multiple is zero. At each step, it checks if the dividend is greater than or equal to the divisor. If it is, it subtracts the divisor from the dividend, adds the multiple to the quotient, and continues the loop. Otherwise, it right-shifts the divisor and multiple variables to check for the next value. At the end of this step, the quotient variable contains the integer division result.\n- Finally, the function applies the sign to the result and returns it.\n\n\nOverall, the binary division algorithm is an efficient way to perform integer division using bit manipulation. The code handles edge cases such as division by zero and overflow and returns the correct result with the correct sign.\n\n\n\n\n\n\n```\nclass Solution:\n def divide(self, dividend: int, divisor: int) -> int:\n # Handle division by zero\n if divisor == 0:\n return 2**31 - 1\n \n # Handle overflow case\n if dividend == -2**31 and divisor == -1:\n return 2**31 - 1\n \n # Get the sign of the result\n sign = 1\n if dividend < 0:\n dividend = -dividend\n sign = -sign\n if divisor < 0:\n divisor = -divisor\n sign = -sign\n \n # Find the largest multiple of the divisor that is less than or equal to the dividend\n multiple = 1\n while dividend >= (divisor << 1):\n divisor <<= 1\n multiple <<= 1\n \n # Perform division using binary search\n quotient = 0\n while multiple > 0:\n if dividend >= divisor:\n dividend -= divisor\n quotient += multiple\n divisor >>= 1\n multiple >>= 1\n \n # Apply the sign to the result\n return sign * quotient\n\n```
2,730
Divide Two Integers
divide-two-integers
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. Return the quotient after dividing dividend by divisor. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.
Math,Bit Manipulation
Medium
null
11,738
86
**With [bitwise operators]():**\n```\n def divide(self, dividend: int, divisor: int) -> int:\n is_negative = (dividend < 0) != (divisor < 0)\n divisor, dividend = abs(divisor), abs(dividend)\n\n quotient = 0\n the_sum = divisor\n\n while the_sum <= dividend:\n current_quotient = 1\n while (the_sum << 1) <= dividend:\n the_sum <<= 1\n current_quotient <<= 1 \n dividend -= the_sum\n the_sum = divisor\n quotient += current_quotient\n\n return min(2147483647, max(-quotient if is_negative else quotient, -2147483648))\n```\nRuntime: 24 ms, faster than 99.56% of Python3 online submissions for Divide Two Integers.\nMemory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Divide Two Integers.\n\n**Without bitwise operators:**\n```\n def divide(self, dividend: int, divisor: int) -> int:\n\t\tis_negative = (dividend < 0) != (divisor < 0)\n\t\tdivisor, dividend = abs(divisor), abs(dividend)\n\n\t\tquotient = 0\n\t\tthe_sum = divisor\n\n\t\twhile the_sum <= dividend:\n\t\t\tcurrent_quotient = 1\n\t\t\twhile (the_sum + the_sum) <= dividend:\n\t\t\t\tthe_sum += the_sum\n\t\t\t\tcurrent_quotient += current_quotient\n\t\t\tdividend -= the_sum\n\t\t\tthe_sum = divisor\n\t\t\tquotient += current_quotient\n\n\t\treturn min(2147483647, max(-quotient if is_negative else quotient, -2147483648))\n```\n**How it works**\nFor example, we `divide(5000, 14)`:\n1) After the first inner loop: `the_sum = 3584` which is `14` multiplied `256` times. \nWe can\'t multiply any more \u2014 because after `256` is coming `256 + 256 = 512` and `14 * 512 = 7168` which is larger than our `dividend`, so we exit the inner loop,\nReducing dividend: `dividend = 5000 - 3584 = 1416` \nAnd moving to another cycle of outer loop\n2) After the second inner loop: `the_sum = 896` which is `14` multiplied `64` times. \n3) Third: `the_sum = 448` which is `14` multiplied `32` times. \n4) And so on\n5) Finally we have: `quotient = 256 + 64 + 32 + 4 + 1 = 357`
2,739
Divide Two Integers
divide-two-integers
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. Return the quotient after dividing dividend by divisor. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.
Math,Bit Manipulation
Medium
null
6,331
42
I took the code of [@tusizi]() and made it easier to understand by changing variable names, and adding a detailed explanation for each line. I\'m also not experienced myself and whatever I right here comes from discussion forums and googling. The high level idea is that you substract `dividend` by `divisor` until `dividend` is less than `divisor`. Also, the solution has two `while` loops. The inner `while` loop tries to substract `divisor`, `2*divisor`, `4*divisor` and so on, until `dividend` is less than `divisor` where it starts over the outer `while` loop. \n\n```\nclass Solution:\n# @return an integer\ndef divide(self, dividend, divisor):\n positive = (dividend < 0) is (divisor < 0) # 1\n dividend, divisor = abs(dividend), abs(divisor) # 2\n res = 0 # 3\n while dividend >= divisor: # 4\n curr_divisor, num_divisors = divisor, 1 # 5\n while dividend >= curr_divisor: # 6\n dividend -= curr_divisor # 7\n res += num_divisors # 8\n \n curr_divisor = curr_divisor << 1 # 9\n num_divisors = num_divisors << 1 # 10\n\t\t\t\t\n if not positive: # 11\n res = -res # 12\n\t\t\n return min(max(-2147483648, res), 2147483647) # 13\n```\n\n`#1`: `is` operator is similar to `==` operator except that it compares that whether both the operands refer to the same object or not. check [this](.***.org/difference-operator-python/).\nSo here, if both of `dividend` and `divisor` have similar sign, it returns `True`. Otherwise, `False`. This will be used in line `#11` when we check if the `positive` variable is `True` or `False`. And, if it\'s not `True` (meaning if they don\'t have similar signs, we add a `-` to the output (`#12`). Note that in this example `==` works just fine as `is`. \n\n`#2`: No that we decided on the sign in line `#1`, we can use absolute values of `dividend` and `divisor`. That\'s what\'s being done here. \n\n`#3`: Initiating the output by setting it to zero. \n\n`#4`: So the high level idea is that we substract `divisor` from `dividend` until we can\'t substract anymore. Imagine you want to divide 7 by 2. 7-2 =5, 5-2=3, 3-2 = 1 ! You can\'t substract anymore. Them the `while` loope stops. \n\n`#5`: Now, we enter the main (tricky, challenging, confusing) part of the code. This line is not complicated. It simply initilize some values, meaning `curr_divisor` and `num_divisors\' with `divisor` and `1`, recpectively. This means we assume `curr_divisor = divisor` and `num_divisor = 1`, initially. \n\n`#7` and `#8`: These two lines are updating `dividend` and `res`. When you substract `dividend` by `curr_divisor`, you\'re basically saying if I was going to calculating the quotient of division, I could still cut another piece with the size of `divisor` from `dividend`, and that\'s why you update the `res` variable by num_divisor (`res += num_divisors` means `res = res + num_divisors`). \n\n`#9` and `#10`: `currdivisor = currdivisor << 1` is the same as `currdivisor = currdivisor 2`, and `numdivisors = numdivisors << 1`, is the same as`numdivisors = numdivisors2`. This is called bitwise operation. Check [this](). `<<` sign is left-shifting bitwise operator which shift bits in binary of a number by one to the left. Imaging you have number 4, (`bin(4) = 0b100`)! doing `4 >> 1` make the new binary `1000` (shifted to the left by 1 and added a zero to the rightmost bit) which is the binary for 8. The reason it tries to do the multiplicaion is to fasten the process. From [here](), A naive method here is to repeatedly subtract divisor from dividend, until there is none enough left. Then the count of subtractions will be the answer. Yet this takes linear time and is thus slow. A better method is to subtract divisor in a more efficient way. We can subtract divisor, 2divisor, 4divisor, 8*divisor... as is implemented above. .It will go to the outer loop once it cannot substract anymore of `curr_divisor` from `dividend`, and set the `curr_divisor = divisor` and tries the actual divisor (no 2 multiplications). \n\n`#13`: We are told by problem statement to limit the output to 32-bit integers, meaning the `res` parameter fall in the [-2^31, 2*^31-1] range. Here, the line has two components. First, it compares output (`res`) with -2^31 value and return the max of the two since we don\'t want values less than -2^31. Next, it compares the value from `max(-2147483648, res)` with the maximum allowable value (meaning 2^31). So, if we put `a = max(-2147483648, res)`, then it does `min(a, 2147483647)` and return the min of two since we\'re not allowed to go above 2^31 = 2147483647 number. \n\n=========================================\n\nFinal note: In order to fully understand the code, I suggest to grab a piece of paper and pen (or write on a notepad or something similar in out laptop/pc) and write a simple example and try to pass through the algorithm by hand. Here is an example from [this](). \n\nLet\'s take an example: `50 / 4`\nAt the start,\n`curr_divisor, num_divisors = divisor, 1` # dividend = 50, curr_divisor = 4, num_divisors = 1\n`dividend -= curr_divisor` # dividend = 46, curr_divisor = 4 ,num_divisors = 1\n`res += num_divisors` # res = 1\n`num_divisors <<= 1 ` # dividend = 46, curr_divisor = 4 , num_divisors = 2\n`curr_divisor <<= 1` # dividend = 46, curr_divisor = 8 , num_divisors = 2\n\nSecond iteration:\n`dividend -= curr_divisor` # dividend = 38, curr_divisor = 8 , num_divisors= 2\n`res += num_divisors` # res = 3\n`num_divisors <<= 1` # dividend = 38, curr_divisor = 8 , num_divisors = 3\n`curr_divisor <<= 1` # dividend = 38, curr_divisor = 12 , num_divisors = 3\n\nand so on, when `dividend > curr_divisor`, we start over again with `curr_divisor = 4`, and `num_divisors = 1`\n\n\n===========================================================================\nFinal note 2: Since I believe if I could explain something to others in a simple manner, it would be helpful to me, I try to add more posts like this as I move forward through my leetcode journey. \n\nFinal note 3: There might be some typos in the writing above!!
2,778
Divide Two Integers
divide-two-integers
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. Return the quotient after dividing dividend by divisor. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.
Math,Bit Manipulation
Medium
null
4,794
31
*(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\n*(Note: Some have questioned whether or not bitwise shifts should count as multiplication/division, so I\'ve added an alternate solution explanation taking advantage of the algebraic qualities of logarithms below in the **Alaternate Idea** section.)*\n\nThe naive approach here would be to use a loop to just work down the difference between the dividend (**A**) and the divisor (**B**) through subtraction, but that\'s obviously not a very efficient solution.\n\nInstead, we can use **bit manipulation** to simulate multiplication/division. Since a **bitwise shift** to the left is the equivalent of a multiplication by **2**, if we count how many times we can bitwise shift **B** to the left while still staying under **A**, then we can quickly work out a chunk of the solution. All that\'s left is to start over with the remaining amount of **A** and repeat this process, adding the results to our answer (**ans**) as we go.\n\nOf course, negative numbers will play havoc with our bitwise shifting, so we should first extract the **sign** difference and then use only positive numbers for **A** and **B**.\n\nThere\'s also the stated edge case, which only occurs at one permutation of **A** and **B**, so we can handle that at the outset.\n\n---\n\n#### ***Alternate Idea:***\n\nFor those who consider bitwise shifts to be too close to multiplication/division, we can instead use the rules of **logarithms** to our advantage:\n```c++\n if: exp(log(c) = c // Logarithmic rule #1\n if: log(a / b) = log(a) - log(b) // Logarithmic rule #2\n\nthen: a / b = exp(log(a / b)) // From rule #1\n a / b = exp(log(a) - log(b)) // From rule #2\n\n (if m and n are > 0)\n```\nSince we\'ll have to use the absolute values of **A** and **B**, we\'ll have to define the same edge cases as in the earlier solutions. Finally, we\'ll also have to apply a **floor()** to the result to truncate the decimal before we **return ans**.\n\n---\n\n#### ***Implementation:***\n\nJavascript and Python both handle numbers larger than **32-bit** internally, and Java requires only a small change to the conditions on its loops to avoid an issue.\n\nC++, on the other hand, adheres strictly to the **32-bit** limit, so we have to define a few more edge cases to avoid exceeding these boundaries. That does allow us to simplify the code for both loops, however.\n\n---\n\n#### ***Javascript Code w/ Bit Manipulation:***\n\nThe best result for the code below is **84ms / 39.8MB** (beats 99% / 96%).\n```javascript\nvar divide = function(A, B) {\n if (A === -2147483648 && B === -1) return 2147483647\n let ans = 0, sign = 1\n if (A < 0) A = -A, sign = -sign\n if (B < 0) B = -B, sign = -sign\n if (A === B) return sign\n for (let i = 0, val = B; A >= B; i = 0, val = B) {\n while (val > 0 && val <= A) val = B << ++i\n A -= B << i - 1, ans += 1 << i - 1\n }\n return sign < 0 ? -ans : ans\n};\n```\n\n---\n\n#### ***Javascript Code w/ Logarithms:***\n\nThe best result for the code below is **84ms / 40.1MB** (beats 99% / 63%).\n```javascript\nvar divide = function(A, B) {\n let ans = 0\n if (B === -2147483648) return A === B\n if (A === -2147483648)\n if (B === 1) return -2147483648\n else if (B === -1) return 2147483647\n else A += Math.abs(B), ans++\n ans += Math.floor(Math.exp(Math.log(Math.abs(A)) - Math.log(Math.abs(B))))\n return A > 0 === B > 0 ? ans : -ans\n};\n```\n\n---\n\n#### ***Python Code w/ Bit Manipulation:***\n\nThe best result for the code below is **20ms / 14.0MB** (beats 100% / 95%).\n```python\nclass Solution:\n def divide(self, A: int, B: int) -> int:\n if A == -2147483648 and B == -1: return 2147483647\n ans, sign = 0, 1\n if A < 0: A, sign = -A, -sign\n if B < 0: B, sign = -B, -sign\n if A == B: return sign\n while A >= B:\n b = 0\n while B << b <= A: b += 1\n A -= B << b - 1\n ans += 1 << b - 1\n return -ans if sign < 0 else ans\n```\n\n---\n\n#### ***Python Code w/ Logarithms:***\n\nThe best result for the code below is **28ms / 14.1MB** (beats 92% / 95%).\n```python\nclass Solution:\n def divide(self, A: int, B: int) -> int:\n if A == 0: return 0\n if A == -2147483648 and B == -1: return 2147483647\n ans = math.floor(math.exp(math.log(abs(A)) - math.log(abs(B))))\n return ans if (A > 0) == (B > 0) else -ans\n```\n\n---\n\n#### ***Java Code w/ Bit Manipulation:***\n\nThe best result for the code below is **1ms / 35.8MB** (beats 100% / 97%).\n```java\nclass Solution {\n public int divide(int A, int B) {\n if (A == -2147483648 && B == -1) return 2147483647;\n int ans = 0, sign = A > 0 == B > 0 ? 1 : -1;\n if (A < 0) A = -A;\n if (B < 0) B = -B;\n if (A == B) return sign;\n for (int i = 0, val = B; A - B >= 0; i = 0, val = B) {\n while (val > 0 && A - val >= 0) val = B << ++i;\n A -= B << i - 1;\n ans += 1 << i - 1;\n }\n return sign < 0 ? -ans : ans;\n }\n}\n```\n\n---\n\n#### ***Java Code w/ Logarithms:***\n\nThe best result for the code below is **1ms / 35.9MB** (beats 100% / 84%).\n```java\nclass Solution {\n public int divide(int A, int B) {\n int ans = 0;\n if (B == -2147483648) return A == B ? 1 : 0;\n if (A == -2147483648) {\n if (B == 1) return -2147483648;\n if (B == -1) return 2147483647;\n A += Math.abs(B);\n ans++;\n }\n ans += Math.floor(Math.exp(Math.log(Math.abs(A)) - Math.log(Math.abs(B))));\n return A > 0 == B > 0 ? ans : -ans;\n }\n}\n```\n\n---\n\n#### ***C++ Code w/ Bit Manipulation:***\n\nThe best result for the code below is **0ms / 5.8MB** (beats 100% / 97%).\n```c++\nclass Solution {\npublic:\n int divide(int A, int B) {\n int ans = 0, sign = A > 0 == B > 0 ? 1 : -1;\n if (B == -2147483648) return A == B;\n if (A == -2147483648)\n if (B == 1) return -2147483648;\n else if (B == -1) return 2147483647;\n else A += abs(B), ans++;\n A = abs(A), B = abs(B);\n for (int i = 0; A >= B; i = 0) {\n while (A >> i >= B) i++;\n A -= B << i - 1, ans += 1 << i - 1;\n }\n return sign < 0 ? -ans : ans;\n }\n};\n```\n\n---\n\n#### ***C++ Code w/ Logarithms:***\n\nThe best result for the code below is **0ms / 6.1MB** (beats 100% / 48%).\n```c++\nclass Solution {\npublic:\n int divide(int A, int B) {\n int ans = 0;\n if (B == -2147483648) return A == B;\n if (A == -2147483648)\n if (B == 1) return -2147483648;\n else if (B == -1) return 2147483647;\n else A += abs(B), ans++;\n ans += floor(exp(log(abs(A)) - log(abs(B))));\n return A > 0 == B > 0 ? ans : -ans;\n }\n};\n```
2,780
Divide Two Integers
divide-two-integers
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. Return the quotient after dividing dividend by divisor. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.
Math,Bit Manipulation
Medium
null
527
6
```\nclass Solution:\n def divide(self, dividend: int, divisor: int) -> int:\n is_negative = (dividend < 0) != (divisor < 0)\n dividend, divisor = abs(dividend), abs(divisor)\n sum = divisor\n quo=0\n while sum<=dividend:\n q2=1\n while (sum<<1) <=dividend:\n sum<<=1\n q2<<=1\n dividend -= sum\n sum = divisor\n quo += q2\n return min(2147483647, max(-quo if is_negative else quo, -2147483648)) \n```\n***Pls upvote if you find it helpful.***
2,784
Divide Two Integers
divide-two-integers
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. Return the quotient after dividing dividend by divisor. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.
Math,Bit Manipulation
Medium
null
946
6
```\n\nclass Solution:\n def divide(self, dividend: int, divisor: int):\n sign = 1 if (dividend > 0) == (divisor > 0) else -1\n dividend, divisor = abs(dividend), abs(divisor)\n res = 0\n while dividend >= divisor:\n temp, i = divisor, 1\n while dividend >= temp:\n dividend -= temp\n res += i\n i <<= 1\n temp <<= 1\n\n if sign < 0:\n res = -res\n\n return min(max(-2147483648, res), 2147483647)\n\n```
2,791
Divide Two Integers
divide-two-integers
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. Return the quotient after dividing dividend by divisor. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.
Math,Bit Manipulation
Medium
null
6,964
12
You can refer to this [video solution]() \n\nHere we are doubling the divisor everytime and hence compressing the total number of subtraction operations. \nIf the doubled divisor is greater than the dividend, we reset our divisor to its initial value and try again.\n\nAt the end, we make sure that the output is within the given range and avoid an overflow.\n\n```\nclass Solution:\n def divide(self, dividend: int, divisor: int) -> int:\n a = abs(dividend)\n b=abs(divisor)\n \n negative = (dividend<0 and divisor>=0) or (dividend>=0 and divisor<0)\n \n output = 0\n \n while a>=b:\n counter = 1\n decrement = b\n \n while a>=decrement:\n a-=decrement\n \n output+=counter\n counter+=counter\n decrement+=decrement\n \n output = output if not negative else -output\n \n return min(max(-2147483648, output), 2147483647)\n
2,798
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
7,609
51
Method: `Hash Table`\n\nFirst we can create a `dict` to store the occurrence times for each word in `words`.\n\nFor example,\nIf `s = "barfoofoobarthefoobarman"` and `words = ["bar","foo","the"]`, \nthe dict will be `word_count = {\'bar\': 1, \'foo\': 1, \'the\': 1}`,\n\nSince all the strings stored in `words` have the same length, the size of **sliding window** will be the word length of a single string. In the example above, the **sliding window** will be `3`\n\n![image]()\n```\nbar -> foo -> foo -> bar -> the -> foo -> bar -> man\nignore b -> arf -> oof -> oob -> art -> hef -> oob -> arm -> ignore an\nignore ba -> rfo -> ofo -> oba -> rth -> efo -> oba -> rma -> ignore n\n```\nThen, we can scan `s` in these 3 ways one by one\n\nLet the word in **sliding window** be `word`.\nAlso, we will create a `queue` to store the scan history.\n```\n1) word_count.get(word, 0) >= 0 \n -> word_count[word] -= 1 as it uses one of the string in words\n\t-> queue.append(word)\n\t\n2) word_count.get(word, 0) == 0 \n -> while queue.pop()\n\t\t-> queue.pop() == word\n\t\t\t-> queue.append(queue.pop()) # Only the beginning word is dropped, the remaining words are still in use\n\t\t\t-> break\n\t\t-> queue.pop() != word\n\t\t\t# Since the beginning word is dropped, the count of beginning word should be added 1.\n\t\t\t-> word_dict[last_element] += 1\n\t\t\t\t-> word_dict[last_element] exceeds its original value, reset the whole word_dict\n\t\t\t-> continue\n```\nCode:\n```\nfrom collections import deque, defaultdict\n\nclass Solution:\n def findSubstring(self, s: str, words: List[str]) -> List[int]:\n word_len = len(words[0])\n ori_word_dict = defaultdict(int)\n\t\t\n for word in words:\n ori_word_dict[word] += 1\n \n all_word_len = len(words) * word_len\n result = []\n for i in range(word_len):\n queue = deque()\n word_dict = ori_word_dict.copy()\n for j in range(i, len(s) - word_len + 1, word_len):\n word = s[j:j + word_len]\n if word_dict.get(word, 0) != 0:\n word_dict[word] -= 1\n queue.append(word)\n if sum(word_dict.values()) == 0:\n result.append(j - all_word_len + word_len)\n last_element = queue.popleft()\n word_dict[last_element] = word_dict.get(last_element, 0) + 1\n else:\n while len(queue):\n last_element = queue.popleft()\n if last_element == word:\n queue.append(word)\n break\n else:\n word_dict[last_element] = word_dict.get(last_element, 0) + 1\n if word_dict[last_element] > ori_word_dict[last_element]:\n word_dict = ori_word_dict.copy()\n\n return result\n```\n\nLet `n` be the length of a word in `words`\nand `m` be the total number of words in `words`\n\n**Time complexity**: `O(n * m)`\n**Space complexity**: `O(n + m)`\n<br/>
2,814
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
6,615
28
```C++ []\nclass Solution {\npublic:\n\tstruct matcher {\n\t\tstruct info { int mtindex, count; };\n\t\tunordered_map<string_view, info>dict;\n\t\tint different_word_count;\n\n\t\tvector<int>slot;\n\t\tint maching_slot_count;\n\n\t\tmatcher(const vector<string>& words) {\n\t\t\tint mtind = 0;\n\t\t\tfor (auto& word : words) {\n\t\t\t\tauto find = dict.find(word);\n\t\t\t\tif (find != dict.end()) {\n\t\t\t\t\t++find->second.count;\n\t\t\t\t}\n\t\t\t\telse { dict[word] = { mtind++,1 }; }\n\t\t\t}\n\t\t\tdifferent_word_count = mtind;\n\t\t\tslot = vector<int>(different_word_count, 0);\n\t\t\tmaching_slot_count = 0;\n\t\t}\n\n\t\tvoid reset() {\n\t\t\tfor (auto& i : slot) { i = 0; }\n\t\t\tmaching_slot_count = 0;\n\t\t}\n\t\tbool match() {\n\t\t\treturn maching_slot_count == different_word_count;\n\t\t}\n\t\tvoid push(string_view sv) {\n\t\t\tauto find = dict.find(sv);\n\t\t\tif (find == dict.end())return;\n\t\t\tif (++slot[find->second.mtindex] == find->second.count) {\n\t\t\t\t++maching_slot_count;\n\t\t\t}\n\t\t}\n\t\tvoid pop(string_view sv) {\n\t\t\tauto find = dict.find(sv);\n\t\t\tif (find == dict.end())return;\n\t\t\tif (--slot[find->second.mtindex] == find->second.count - 1) {\n\t\t\t\t--maching_slot_count;\n\t\t\t}\n\t\t}\n\t};\n\tvector<int> findSubstring(string s, const vector<string>& words) {\n\t\tint word_count = words.size();\n\t\tint word_len = words[0].size();\n\n\t\tmatcher matcher(words);\n\n\t\tconst char* str = s.c_str();\n\t\tint len = s.size();\n\t\tvector<int> ret;\n\n\t\tfor (int off = 0; off < word_len; off++) {\n\t\t\tconst char* beg = str + off, * end = str + len;\n\t\t\tif (beg + word_len * word_count <= end) {\n\t\t\t\tmatcher.reset();\n\t\t\t\tfor (int i = 0; i < word_count; i++) {\n\t\t\t\t\tstring_view sv(beg + i * word_len, word_len);\n\t\t\t\t\tmatcher.push(sv);\n\t\t\t\t}\n\t\t\t\tif (matcher.match()) {\n\t\t\t\t\tret.push_back(beg - str);\n\t\t\t\t}\n\t\t\t\tconst char* pos = beg + word_len * word_count;\n\t\t\t\twhile (pos + word_len <= end) {\n\t\t\t\t\tstring_view del(beg, word_len);\n\t\t\t\t\tstring_view add(pos, word_len);\n\t\t\t\t\tbeg += word_len;\n\t\t\t\t\tpos += word_len;\n\t\t\t\t\tmatcher.pop(del);\n\t\t\t\t\tmatcher.push(add);\n\t\t\t\t\tif (matcher.match()) {\n\t\t\t\t\t\tret.push_back(beg - str);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}\n};\n```\n\n```Python3 []\nclass Solution:\n def findSubstring(self, s: str, words: List[str]) -> List[int]:\n n_word = len(words)\n n_char = len(words[0])\n word2freq = {}\n for word in words:\n if word in word2freq:\n word2freq[word] += 1\n else:\n word2freq[word] = 1\n\n all_start_ind = []\n for start_ind in range(n_char):\n curr_map = {}\n curr_total = 0\n excessive = False\n for i in range(start_ind, len(s), n_char):\n word = s[i:i+n_char]\n if word in word2freq: # a valid word for permutation \n curr_total += 1\n if word in curr_map: # found valid word\n curr_map[word] += 1\n if curr_map[word] > word2freq[word]: \n excessive = word\n else:\n curr_map[word] = 1\n\n earliest_ind = i - (curr_total-1)*n_char\n while excessive:\n earliest_word = s[earliest_ind: earliest_ind+n_char]\n curr_map[earliest_word] -= 1\n curr_total -= 1\n if earliest_word == excessive:\n excessive = False\n break\n earliest_ind += n_char\n if curr_total == n_word:\n earliest_ind = i - (n_word-1)*n_char\n\n all_start_ind.append(earliest_ind)\n\n earliest_word = s[earliest_ind: earliest_ind+n_char]\n curr_total -= 1\n curr_map[earliest_word] -= 1\n else:\n curr_total = 0\n curr_map = {}\n return all_start_ind\n \n def check_map_equal(self, curr_map, ref_map) -> bool:\n for word, freq in curr_map.items():\n if word not in ref_map or freq != ref_map[word]:\n return False\n return True\n```\n\n```Java []\nclass Solution {\n public List<Integer> findSubstring(String s, String[] words) {\n int wordLength = words[0].length();\n int totalWordsLength = wordLength * words.length;\n Map<String, Integer> hash = new HashMap<>();\n List<Integer> ans = new ArrayList<>();\n char[] s2 = s.toCharArray();\n for (String value : words) {\n hash.putIfAbsent(value, hash.size());\n }\n int[] count = new int[hash.size()];\n for (String word : words) {\n count[hash.get(word)]++;\n }\n for (int i = 0; i < wordLength; i++) {\n for (int j = i; j <= s.length() - totalWordsLength; j += wordLength) {\n int[] localCount = new int[hash.size()];\n for (int k = j + totalWordsLength - wordLength; k >= j; k -= wordLength) {\n String str = new String(s2, k, wordLength); // [ k, k+wordLength )\n Integer key = hash.get(str);\n if (!(key != null && count[key] >= ++localCount[key])) {\n j = k;\n break;\n }\n if (j == k) {\n ans.add(j);\n }\n }\n }\n }\n return ans;\n }\n}\n```\n
2,817
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
3,274
31
![image]()\n\n```\nclass Solution:\n def findSubstring(self, s: str, words: List[str]) -> List[int]:\n wlen = len(words[0])\n wslen = len(words) * len(words[0])\n res = []\n \n for pos in range(wlen):\n i = pos\n d = Counter(words)\n \n for j in range(i, len(s) + 1 - wlen, wlen):\n word = s[j: j + wlen]\n d[word] -= 1\n \n while d[word] < 0:\n d[s[i: i + wlen]] += 1\n i += wlen\n if i + wslen == j + wlen:\n res. append(i)\n \n return res\n```\n**Please UPVOTE if you LIKE**\n![image]()\n
2,820
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
880
9
**Please UPVOTE if you LIKE!!**\n***Watch this video for the better explanation of the code.*\nAlso you can SUBSCRIBE \uD83E\uDC83 this channel for the daily leetcode challange solution.**\n\n\n \u2B05\u2B05 **Telegram link** to discuss leetcode daily questions and other dsa problems\n\n\n**C++**\n```\nclass Solution {\npublic:\n vector<int> findSubstring(string s, vector<string>& words) {\n int wordsquan= words.size();\n int wordsleng= words[0].size();\n int target= wordsquan * wordsleng;\n unordered_map<string, int> unmap;\n \n for(int j=0; j< wordsquan; j++)\n {\n unmap[words[j]]++; \n }\n vector<int > ans;\n if(s.size()<target)\n {\n return ans;\n }\n for(int i=0; i<=s.size()-target; i++)\n {\n unordered_map<string, int> unmap2;\n unmap2= unmap; \n int k;\n for( k=0; k< wordsquan; k++)\n {\n string s1= s.substr(i+k*wordsleng, wordsleng);\n if(unmap2.count(s1)==0)\n break;\n else if(unmap2[s1]!=0)\n unmap2[s1]--;\n else\n break; \n }\n \n if(k==wordsquan)\n {\n ans.push_back(i);\n }\n \n \n }\n return ans;\n }\n};\n```\n**JAVA**(Copied)\n```\nclass Solution \n{\n public List<Integer> findSubstring(String s, String[] words) \n {\n if(words[0].length()*words.length>s.length())\n return new ArrayList<>();\n \n Map<String,Integer> word_frq=new HashMap<>();\n List<Integer> ans=new ArrayList<>();\n \n // Map store the frequency of every word in words[]\n \n for(String str:words)\n word_frq.put(str,word_frq.getOrDefault(str,0)+1);\n \n int wordlen=words[0].length(); \n \n String[] str=new String[s.length()];\n \n for(int i=0;i<wordlen;i++)\n {\n Map<String,Integer> frq=new HashMap<>(); // count frequency of words inside the window\n \n int begin=i,size=0; // size is the no. of window and begin is the starting index of window\n \n // s.length()-wordlen -> based on observation\n \n for(int j=i;j<=s.length()-wordlen;j+=wordlen)\n {\n str[j]=s.substring(j,j+wordlen); // window\n if(word_frq.containsKey(str[j]))\n {\n begin= begin==-1? j:begin; // begin=-1 means new window need to be started\n frq.put(str[j],frq.getOrDefault(str[j],0)+1); \n size++; \n \n if(size==words.length) // substring may be possible\n {\n if(frq.equals(word_frq))\n ans.add(begin);\n \n // sliding the window \n \n frq.put(str[begin],frq.get(str[begin])-1); \n begin+=wordlen; // new starting index\n size--;\n }\n }\n else // reset window\n {\n begin=-1;\n size=0;\n frq.clear();\n }\n }\n }\n return ans;\n }\n}\n```\n**PYTHON**((Copied)\n```\n res = []\n WordLen = [len(s) for s in words]\n WordIni = [ s[0] for s in words]\n TotWordLen = sum(WordLen)\n LongestWordLen = max(WordLen)\n \n d = {}\n for i in range(len(words)):\n if words[i] not in d:\n d[words[i]] = [i]\n else:\n d[words[i]].append(i) \n \n \n def isCCT(string):\n \n copy_d = copy.deepcopy(d)\n temp = \'\'\n #print(\'isCCT:\',string,copy_d)\n \n for c in string:\n temp += c\n if temp in copy_d:\n \n if len(copy_d[temp]) > 1:\n copy_d[temp].pop()\n else:\n del copy_d[temp]\n temp = \'\'\n elif len(temp) >= LongestWordLen:\n #print(\'isCCT:\',string, temp, \'zero patience\')\n return False\n \n #print(\'isCCT:\',string, temp) \n if temp == \'\' and len(copy_d) == 0:\n return True\n else:\n return False\n \n \n for i in range(len(s)):\n if s[i] in WordIni:\n if (i + TotWordLen - 1) <= len(s): \n testSubStr = s[i:i + TotWordLen]\n #print(i,testSubStr)\n if isCCT(testSubStr) == True:\n res.append(i)\n \n return res\n```**Please Don\'t forget to UPVOTE if you LIKE!!**
2,836
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
4,584
6
\n# Approach\n\nThe solution iterates through possible starting points in the given string and checks if the substring starting from each point forms a concatenated substring. It maintains a dictionary to track the occurrences of words encountered and compares it with the expected occurrences. By updating the counts while scanning the string, it identifies valid concatenated substrings and records their starting indices. The solution effectively ensures that all the words in any permutation of the input words array are present in the substring, returning the starting indices of all such valid substrings.\n\n# Code\n```\nclass Solution:\n def findSubstring(self, s: str, words: List[str]) -> List[int]:\n wlen= len(words[0])\n slen= wlen*len(words)\n track=dict()\n \n occ = collections.Counter(words)\n\n def test():\n for key, val in track.items():\n if val !=occ[key]:\n return False\n return True\n res=[]\n #first look\n\n for k in range(wlen):\n for i in words:\n track.update({i : 0})\n for i in range(k,slen+k,wlen):\n w=s[i:i+wlen]\n if w in words:\n track.update({w: track[w]+1})\n if test():\n res.append(k)\n #complete\n for i in range(wlen+k, len(s)-slen+1,wlen):\n \n nw=s[i+slen-wlen:i+slen]\n pw=s[i-wlen:i]\n if nw in words:\n track.update({nw: track[nw]+1})\n if pw in words:\n track.update({pw: track[pw]-1})\n if test():\n res.append(i)\n return res\n\n \n```
2,841
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
2,886
16
![image]()\n\n```\nfrom collections import Counter, defaultdict\n\n\nclass Solution:\n\t"""\n\tTime: O(n*k), n = length of s, k = length of each word\n\tMemory: O(m*k), m = length of words, k = length of each word\n\t"""\n\n\tdef findSubstring(self, s: str, words: List[str]) -> List[int]:\n\t\tlength = len(words[0])\n\t\tword_count = Counter(words)\n\t\tindexes = []\n\n\t\tfor i in range(length):\n\t\t\tstart = i\n\t\t\twindow = defaultdict(int)\n\t\t\twords_used = 0\n\n\t\t\tfor j in range(i, len(s) - length + 1, length):\n\t\t\t\tword = s[j:j + length]\n\n\t\t\t\tif word not in word_count:\n\t\t\t\t\tstart = j + length\n\t\t\t\t\twindow = defaultdict(int)\n\t\t\t\t\twords_used = 0\n\t\t\t\t\tcontinue\n\n\t\t\t\twords_used += 1\n\t\t\t\twindow[word] += 1\n\n\t\t\t\twhile window[word] > word_count[word]:\n\t\t\t\t\twindow[s[start:start + length]] -= 1\n\t\t\t\t\tstart += length\n\t\t\t\t\twords_used -= 1\n\n\t\t\t\tif words_used == len(words):\n\t\t\t\t\tindexes.append(start)\n\n\t\treturn indexes\n```\n\nIf you like this solution remember to **upvote it** to let me know.\n\n
2,854
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
3,250
16
**Please UPVOTE if you LIKE!!**\n***Watch this video for the better explanation of the code.*\nAlso you can SUBSCRIBE \uD83E\uDC83 this channel for the daily leetcode challange solution.**\n\n\n\n**C++**\n```\nclass Solution {\npublic:\n vector<int> findSubstring(string s, vector<string>& words) {\n int wordsquan= words.size();\n int wordsleng= words[0].size();\n int target= wordsquan * wordsleng;\n unordered_map<string, int> unmap;\n \n for(int j=0; j< wordsquan; j++)\n {\n unmap[words[j]]++; \n }\n vector<int > ans;\n if(s.size()<target)\n {\n return ans;\n }\n for(int i=0; i<=s.size()-target; i++)\n {\n unordered_map<string, int> unmap2;\n unmap2= unmap; \n int k;\n for( k=0; k< wordsquan; k++)\n {\n string s1= s.substr(i+k*wordsleng, wordsleng);\n if(unmap2.count(s1)==0)\n break;\n else if(unmap2[s1]!=0)\n unmap2[s1]--;\n else\n break; \n }\n \n if(k==wordsquan)\n {\n ans.push_back(i);\n }\n \n \n }\n return ans;\n }\n};\n```\n**JAVA**(Copied)\n```\nclass Solution \n{\n public List<Integer> findSubstring(String s, String[] words) \n {\n if(words[0].length()*words.length>s.length())\n return new ArrayList<>();\n \n Map<String,Integer> word_frq=new HashMap<>();\n List<Integer> ans=new ArrayList<>();\n \n // Map store the frequency of every word in words[]\n \n for(String str:words)\n word_frq.put(str,word_frq.getOrDefault(str,0)+1);\n \n int wordlen=words[0].length(); \n \n String[] str=new String[s.length()];\n \n for(int i=0;i<wordlen;i++)\n {\n Map<String,Integer> frq=new HashMap<>(); // count frequency of words inside the window\n \n int begin=i,size=0; // size is the no. of window and begin is the starting index of window\n \n // s.length()-wordlen -> based on observation\n \n for(int j=i;j<=s.length()-wordlen;j+=wordlen)\n {\n str[j]=s.substring(j,j+wordlen); // window\n if(word_frq.containsKey(str[j]))\n {\n begin= begin==-1? j:begin; // begin=-1 means new window need to be started\n frq.put(str[j],frq.getOrDefault(str[j],0)+1); \n size++; \n \n if(size==words.length) // substring may be possible\n {\n if(frq.equals(word_frq))\n ans.add(begin);\n \n // sliding the window \n \n frq.put(str[begin],frq.get(str[begin])-1); \n begin+=wordlen; // new starting index\n size--;\n }\n }\n else // reset window\n {\n begin=-1;\n size=0;\n frq.clear();\n }\n }\n }\n return ans;\n }\n}\n```\n**PYTHON**((Copied)\n```\n res = []\n WordLen = [len(s) for s in words]\n WordIni = [ s[0] for s in words]\n TotWordLen = sum(WordLen)\n LongestWordLen = max(WordLen)\n \n d = {}\n for i in range(len(words)):\n if words[i] not in d:\n d[words[i]] = [i]\n else:\n d[words[i]].append(i) \n \n \n def isCCT(string):\n \n copy_d = copy.deepcopy(d)\n temp = \'\'\n #print(\'isCCT:\',string,copy_d)\n \n for c in string:\n temp += c\n if temp in copy_d:\n \n if len(copy_d[temp]) > 1:\n copy_d[temp].pop()\n else:\n del copy_d[temp]\n temp = \'\'\n elif len(temp) >= LongestWordLen:\n #print(\'isCCT:\',string, temp, \'zero patience\')\n return False\n \n #print(\'isCCT:\',string, temp) \n if temp == \'\' and len(copy_d) == 0:\n return True\n else:\n return False\n \n \n for i in range(len(s)):\n if s[i] in WordIni:\n if (i + TotWordLen - 1) <= len(s): \n testSubStr = s[i:i + TotWordLen]\n #print(i,testSubStr)\n if isCCT(testSubStr) == True:\n res.append(i)\n \n return res\n```**Please Don\'t forget to UPVOTE if you LIKE!!**
2,856
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
729
9
**Please UPVOTE if you LIKE!!**\n***Watch this video for the better explanation of the code.*\nAlso you can SUBSCRIBE \uD83E\uDC83 this channel for the daily leetcode challange solution.**\n\n\n \u2B05\u2B05 **Telegram link** to discuss leetcode daily questions and other dsa problems\n\n\n**C++**\n```\nclass Solution {\npublic:\n vector<int> findSubstring(string s, vector<string>& words) {\n int wordsquan= words.size();\n int wordsleng= words[0].size();\n int target= wordsquan * wordsleng;\n unordered_map<string, int> unmap;\n \n for(int j=0; j< wordsquan; j++)\n {\n unmap[words[j]]++; \n }\n vector<int > ans;\n if(s.size()<target)\n {\n return ans;\n }\n for(int i=0; i<=s.size()-target; i++)\n {\n unordered_map<string, int> unmap2;\n unmap2= unmap; \n int k;\n for( k=0; k< wordsquan; k++)\n {\n string s1= s.substr(i+k*wordsleng, wordsleng);\n if(unmap2.count(s1)==0)\n break;\n else if(unmap2[s1]!=0)\n unmap2[s1]--;\n else\n break; \n }\n \n if(k==wordsquan)\n {\n ans.push_back(i);\n }\n \n \n }\n return ans;\n }\n};\n```\n**JAVA**(Copied)\n```\nclass Solution \n{\n public List<Integer> findSubstring(String s, String[] words) \n {\n if(words[0].length()*words.length>s.length())\n return new ArrayList<>();\n \n Map<String,Integer> word_frq=new HashMap<>();\n List<Integer> ans=new ArrayList<>();\n \n // Map store the frequency of every word in words[]\n \n for(String str:words)\n word_frq.put(str,word_frq.getOrDefault(str,0)+1);\n \n int wordlen=words[0].length(); \n \n String[] str=new String[s.length()];\n \n for(int i=0;i<wordlen;i++)\n {\n Map<String,Integer> frq=new HashMap<>(); // count frequency of words inside the window\n \n int begin=i,size=0; // size is the no. of window and begin is the starting index of window\n \n // s.length()-wordlen -> based on observation\n \n for(int j=i;j<=s.length()-wordlen;j+=wordlen)\n {\n str[j]=s.substring(j,j+wordlen); // window\n if(word_frq.containsKey(str[j]))\n {\n begin= begin==-1? j:begin; // begin=-1 means new window need to be started\n frq.put(str[j],frq.getOrDefault(str[j],0)+1); \n size++; \n \n if(size==words.length) // substring may be possible\n {\n if(frq.equals(word_frq))\n ans.add(begin);\n \n // sliding the window \n \n frq.put(str[begin],frq.get(str[begin])-1); \n begin+=wordlen; // new starting index\n size--;\n }\n }\n else // reset window\n {\n begin=-1;\n size=0;\n frq.clear();\n }\n }\n }\n return ans;\n }\n}\n```\n**PYTHON**((Copied)\n```\n res = []\n WordLen = [len(s) for s in words]\n WordIni = [ s[0] for s in words]\n TotWordLen = sum(WordLen)\n LongestWordLen = max(WordLen)\n \n d = {}\n for i in range(len(words)):\n if words[i] not in d:\n d[words[i]] = [i]\n else:\n d[words[i]].append(i) \n \n \n def isCCT(string):\n \n copy_d = copy.deepcopy(d)\n temp = \'\'\n #print(\'isCCT:\',string,copy_d)\n \n for c in string:\n temp += c\n if temp in copy_d:\n \n if len(copy_d[temp]) > 1:\n copy_d[temp].pop()\n else:\n del copy_d[temp]\n temp = \'\'\n elif len(temp) >= LongestWordLen:\n #print(\'isCCT:\',string, temp, \'zero patience\')\n return False\n \n #print(\'isCCT:\',string, temp) \n if temp == \'\' and len(copy_d) == 0:\n return True\n else:\n return False\n \n \n for i in range(len(s)):\n if s[i] in WordIni:\n if (i + TotWordLen - 1) <= len(s): \n testSubStr = s[i:i + TotWordLen]\n #print(i,testSubStr)\n if isCCT(testSubStr) == True:\n res.append(i)\n \n return res\n```**Please Don\'t forget to UPVOTE if you LIKE!!**
2,873
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
434
6
```\nclass Solution:\n def findSubstring(self, s: str, words: List[str]) -> List[int]:\n word_len = len(words[0])\n counter = collections.Counter(words)\n window_size = len(words) * word_len\n ans = []\n for i in range(len(s) - window_size + 1):\n temp = s[i:i+window_size]\n temp = [temp[j:j+word_len] for j in range(0, window_size, word_len)]\n if collections.Counter(temp) == counter:\n ans.append(i)\n return ans\n```
2,875
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
1,462
6
[]()\n[]()\n# DO UPVOTE IF YOU FIND IT SUITABLE AND HELPFUL AND FOR ANY DOUBTS COMMENT.\n# DO LIKE AS EACH VOTE COUNTS\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. --> Refer and take the refernce from the find all anagrams and permutations in a string question of leetcode 438.\n\n# Approach\n<!-- Describe your approach to solving the problem. --> Sliding window + hashtable for each word in words list and then inside nested loop use substrcount each time new and compare for equivalence\\.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->The first for-loop iterates over all words in the input list words and takes O(N) time where N is the number of words in the list.\nThe second for-loop iterates over all substrings of length len(words)*len(words[0]) in the input string s. The number of substrings will be O(M) where M is the length of the input string. For each substring, the code creates a new dictionary substrcount and iterates over all words of length len(words[0]) in the substring. This takes O(len(substr)/len(words[0])) time for each substring. Therefore, the overall time complexity of the second for-loop is O(M * len(substr)/len(words[0])) = O(M*N), where N and M are defined as before.\nThe dictionary operations (insertion, lookup) in the code take O(1) time.\nThus, the overall time complexity of the code is O(M*N), where N is the number of words in the input list and M is the length of the input string.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->The code uses two dictionaries, wordcount and substrcount, to store word frequencies. The maximum size of each dictionary is N (the number of words in the input list).\nThe code stores the input string s, which takes O(M) space.\nThe code stores the result list result, which can take up to O(M/N) space in the worst case (when all substrings are valid).\nThus, the overall space complexity of the code is O(M + N).\n\nIn summary, the time complexity of the given code is O(M*N) and the space complexity is O(M + N), where N is the number of words in the input list and M is the length of the input string.\n\n\n\n\n# Code\n```\nclass Solution:\n def findSubstring(self, s: str, words: List[str]) -> List[int]:\n wordcount={}\n for word in words:\n wordcount[word]=1+wordcount.get(word,0)\n result=[]\n substringlength=len(words)*len(words[0])\n for i in range(len(s)-substringlength+1):\n substr=s[i:i+substringlength]\n substrcount={}\n for j in range(0,len(substr),len(words[0])):\n word=substr[j:j+len(words[0])]\n substrcount[word]=1+substrcount.get(word,0)\n if substrcount==wordcount:\n result.append(i)\n return result\n\n# m=\'\'.join(words)\n# pcount=dict()\n# scount=dict()\n# if len(m)>len(s):\n# print([])\n# for i in range(len(m)):\n# pcount[m[i]]=1+pcount.get(m[i],0)\n# scount[s[i]]=1+scount.get(s[i],0)\n# # print(pcount)\n# # print(scount)\n# res=[0]if pcount==scount else []\n# l=0\n# for i in range(len(m),len(s),1):\n# scount[s[i]]=1+scount.get(s[i],0)\n# scount[s[l]]-=1 \n# if scount[s[l]]==0:\n# del scount[s[l]]\n# l+=1 \n# if scount==pcount:\n# res.append(l)\n# #@print(res)\n# return res\n \n```
2,879
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
7,208
97
```\n def nextPermutation(self, nums):\n for i in range(len(nums)-1, 0, -1):\n # find the index of the last peak\n if nums[i - 1] < nums[i]:\n nums[i:] = sorted(nums[i:])\n \n # get the index before the last peak\n j = i - 1\n \n # swap the pre-last peak index with the value just large than it\n for k in range(i, len(nums)):\n if nums[j] < nums[k]:\n nums[k], nums[j] = nums[j], nums[k]\n return nums\n return nums.reverse()\n```\n\n**Please upvote me if you think this is useful! Much appreciated!**\n\nImagine this as a wave or signal, what we want to do is to move the last peak one-bit forward with equal or smaller peak\n\nConsider the following example [1, 2, 3, 5, 2, 3, 7, 5, 4, 3, 0]\n![image]()\n\nThe last peak is the red dot (index = 6), the index before the last peak (aka the pre-last peak index) is the green dot (index = 5)\n![image]()\n\nThen sort the region after the pre-peak index (green dot), the sorted region is shown in yellow dots\n![image]()\n\nThen find the point where its value is just above the pre-peak index (green dot)\nIn this example, it is the pink dot with index = 8\n![image]()\n\nSwap the green dot and the pink dot\n![image]()\n\n**Done!** Output the final list\nIn this case, it is [1,2,3,5,2,4,0,3,3,5,7]
2,949
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
51,911
365
\n def nextPermutation(self, nums):\n i = j = len(nums)-1\n while i > 0 and nums[i-1] >= nums[i]:\n i -= 1\n if i == 0: # nums are in descending order\n nums.reverse()\n return \n k = i - 1 # find the last "ascending" position\n while nums[j] <= nums[k]:\n j -= 1\n nums[k], nums[j] = nums[j], nums[k] \n l, r = k+1, len(nums)-1 # reverse the second part\n while l < r:\n nums[l], nums[r] = nums[r], nums[l]\n l +=1 ; r -= 1
2,973
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
1,281
5
# Code\n```\nclass Solution(object):\n # To Reverse the Part of a List/Array\n def reverseLst(self,lst,left,right):\n while left < right:\n lst[left],lst[right] = lst[right],lst[left]\n left += 1\n right -= 1\n return lst\n\n def nextPermutation(self, nums):\n numsLen = len(nums)\n\n # Reaching the element which is Greater than the next and near to the right, and the element\'s idx is eleIdx\n eleIdx = numsLen - 1\n while 0 < eleIdx and nums[eleIdx-1] >= nums[eleIdx]:\n eleIdx -= 1\n\n # if the eleIdx is 0 that mean the Whole lst is reversely sorted in this case just return the sorted array but don\'t sort Just reverse it to get the sorted lst\n if eleIdx == 0:\n return self.reverseLst(nums,0,numsLen -1)\n\n # Reversing the right sub array from the eleIdx to end -> indirectly Sorting\n nums = self.reverseLst(nums,eleIdx,numsLen -1)\n\n # mainEle is the element that is neaded to swap with the next minum element after the mainEle\'s idx\n mainEleIdx = eleIdx -1\n\n # finding the right position for the mainElement and swapping it to the right position\n while eleIdx < numsLen and nums[mainEleIdx] >= nums[eleIdx]:\n eleIdx += 1\n\n nums[mainEleIdx],nums[eleIdx] = nums[eleIdx],nums[mainEleIdx]\n return nums\n```\nYou Can also Look At My SDE Prep Repo [*`\uD83E\uDDE2 GitHub`*]()
2,974
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
10,755
88
```\nclass Solution:\n def nextPermutation(self, nums: List[int]) -> None:\n """\n Do not return anything, modify nums in-place instead.\n """\n # To find next permutations, we\'ll start from the end\n i = j = len(nums)-1\n # First we\'ll find the first non-increasing element starting from the end\n while i > 0 and nums[i-1] >= nums[i]:\n i -= 1\n # After completion of the first loop, there will be two cases\n # 1. Our i becomes zero (This will happen if the given array is sorted decreasingly). In this case, we\'ll simply reverse the sequence and will return \n if i == 0:\n nums.reverse()\n return \n # 2. If it\'s not zero then we\'ll find the first number grater then nums[i-1] starting from end\n while nums[j] <= nums[i-1]:\n j -= 1\n # Now out pointer is pointing at two different positions\n # i. first non-assending number from end\n # j. first number greater than nums[i-1]\n \n # We\'ll swap these two numbers\n nums[i-1], nums[j] = nums[j], nums[i-1]\n \n # We\'ll reverse a sequence strating from i to end\n nums[i:]= nums[len(nums)-1:i-1:-1]\n # We don\'t need to return anything as we\'ve modified nums in-place\n \'\'\'\n Dhruval\n \'\'\'\n```\n\nTake an example from this site and try to re-run above code manually. This will better help to understand the code\n\n\nRelated Link: \n\n
2,986
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
7,030
67
# Approach\n- Here the approach is nothing but we are using a stack and when we encounter an opening brace then we push the index of it into the stack and whenever we touch a closing brace then we see the top of the stack if it\'s size is one then it means the closing braces have dominated the opening brace. We then edit the top value of the stack to the index of the closing brace.\n>- This method is clearly depicted in the picture as shown below.\n\n![pic1.png]()\n\n>- here answer is given as the line `ans = max(ans , index - stk.top())` only when the size of stack is not 1 and there is a closing brace encountered.\n\n---\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int longestValidParentheses(string s) {\n stack<int>stk;\n stk.push(-1);\n int ans = 0;\n for(int i = 0 ; i < s.size(); i++)\n {\n if(s[i] == \'(\')\n stk.push(i);\n else\n {\n if(stk.size() == 1)\n stk.top() = i;\n else\n {\n stk.pop();\n ans = max(ans , i - stk.top());\n }\n }\n }\n return ans;\n }\n};\n```\n```java []\nclass Solution {\n public int longestValidParentheses(String s) {\n int leftCount = 0;\n int rightCount = 0;\n int maxLength = 0;\n \n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) == \'(\') {\n leftCount++;\n } else {\n rightCount++;\n }\n \n if (leftCount == rightCount) {\n maxLength = Math.max(maxLength, 2 * rightCount);\n } else if (rightCount > leftCount) {\n leftCount = rightCount = 0;\n }\n }\n \n leftCount = rightCount = 0;\n \n for (int i = s.length() - 1; i >= 0; i--) {\n if (s.charAt(i) == \'(\') {\n leftCount++;\n } else {\n rightCount++;\n }\n \n if (leftCount == rightCount) {\n maxLength = Math.max(maxLength, 2 * leftCount);\n } else if (leftCount > rightCount) {\n leftCount = rightCount = 0;\n }\n }\n \n return maxLength;\n }\n}\n```\n```python []\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n stack=[]\n l=[\'0\']*len(s)\n for ind,i in enumerate(s):\n if i==\'(\':\n stack.append(ind)\n else:\n if stack:\n l[stack.pop()]=\'1\'\n l[ind]=\'1\'\n return max(len(i) for i in \'\'.join(l).split(\'0\'))\n```\n\n---\n\n\n\n# Complexity\n>- Time complexity:Here the complexity would be $$O(n)$$ as we are using only a single loop with a stack only so this runs in a linear complexity.\n\n>- Space complexity:Here the space complexity would be $O(n)$ as we are using just a stack that too store the elements in the worst case it goes to that complexity.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n\n\n**IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.**\n\n![UPVOTE.jpg]()\n
3,001
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
8,594
61
The time complexity for both the approaches is `O(len(s)`.\n\n 1. ##### **Space - O(len(s))**\n\nThis approach solves the problem in similar way as using `Stack`. The stack is used to track indices of `(`. So whenever we hit a `)`, we pop the pair from stack and update the length of valid substring.\n\n```\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n max_length = 0\n stck=[-1] # initialize with a start index\n for i in range(len(s)):\n if s[i] == \'(\':\n stck.append(i)\n else:\n stck.pop()\n if not stck: # if popped -1, add a new start index\n stck.append(i)\n else:\n max_length=max(max_length, i-stck[-1]) # update the length of the valid substring\n return max_length\n```\n\n2. ##### **Space - O(1)**\nThe valid parantheses problem can also be solved using a counter variable. Below implementation modifies this approach a bit and uses two counters:`left` and `right` for `(` and `)` respectively. \n\nThe pseudo code for this approach:\n1. Increment `left` on hitting `(`.\n2. Increment `right` on hitting `)`.\n3. If `left=right`, then calculate the current substring length and update the `max_length`\n4. If `right>left`, then it means it\'s an invalid substring. So reset both `left` and `right` to `0`.\n\nPerform the above algorithm once on original `s` and then on the reversed `s`.\n\n```\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n max_length = 0\n \n l,r=0,0 \n # traverse the string from left to right\n for i in range(len(s)):\n if s[i] == \'(\':\n l+=1\n else:\n r+=1 \n if l == r:# valid balanced parantheses substring \n max_length=max(max_length, l*2)\n elif r>l: # invalid case as \')\' is more\n l=r=0\n \n l,r=0,0 \n # traverse the string from right to left\n for i in range(len(s)-1,-1,-1):\n if s[i] == \'(\':\n l+=1\n else:\n r+=1 \n if l == r:# valid balanced parantheses substring \n max_length=max(max_length, l*2)\n elif l>r: # invalid case as \'(\' is more\n l=r=0\n return max_length\n```\n\n---\n\n***Please upvote if you find it useful***
3,027
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
1,657
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n\n# If you find this helpful,Please Upvote \n```\npublic class Solution {\n public int LongestValidParentheses(string s) {\n Stack<int> index =new Stack<int>();\n for(int i=0;i < s.Length;i++){\n if (s[i] == \'(\'){\n index.Push(i);\n }\n else{\n if(index.Any() && s[index.Peek()] == \'(\'){\n index.Pop();\n }\n else{\n index.Push(i);\n }\n }\n }\n if(!index.Any()){\n return s.Length;\n }\n int length = s.Length, unwanted = 0;\n int result = 0;\n while(index.Any()){\n unwanted = index.Peek();\n index.Pop();\n result = Math.Max(result,length - unwanted - 1);\n length = unwanted;\n }\n result = Math.Max(result,length);\n return result;\n }\n}\n```\n# Python Solution \n\n def ValidParantheses(s):\n length=len(s)\n dp=[0]*length\n count=0\n maxLen=0\n pos=0\n for par in s:\n if par == \'(\':\n count += 1\n elif par == \')\':\n if count>0:\n count-=1\n #immediate parentheses like ()()\n dp[pos]=dp[pos-1]+2\n #outer parentheses (out of nested parentheses or non immmediate valid parentheses)\n if dp[pos] <= pos:\n dp[pos] = dp[pos]+dp[pos-dp[pos]]\n \n maxLen=max(maxLen,dp[pos])\n pos += 1\n return maxLen\n\n# Upvote \uD83E\uDD1E
3,032
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
1,585
11
***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***Q32. Longest Valid Parentheses***\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **Python Code** :\n```\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n l,stack=0,[-1]\n for i in range(len(s)):\n if s[i]==\'(\':\n stack.append(i)\n else:\n stack.pop()\n if not stack:\n stack.append(i)\n else:\n l=max(l,i-stack[-1])\n return l;\n```\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\n\u2705 **Java Code** :\n```\nclass Solution {\n public int longestValidParentheses(String s) {\n Stack<Integer> stack = new Stack();\n stack.push(-1);\n int maxLen = 0;\n for(int i = 0; i < s.length(); i++)\n {\n if(s.charAt(i) == \'(\')\n stack.push(i);\n else if(s.charAt(i) == \')\')\n { \n stack.pop();\n if(stack.empty())\n stack.push(i);\n else\n maxLen = Math.max(maxLen, i - stack.peek()); \n }\n }\n return maxLen;\n }\n}\n```\n\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **C++ Code** :\n```\nclass Solution {\npublic:\n int longestValidParentheses(string s) {\n int n = s.length(),len =0,maxlen =0;\n stack<int> st;\n st.push(-1);\n for(int i =0;i<n;i++)\n {\n if(s[i] == \'(\')\n st.push(i);\n if(s[i] == \')\')\n {\n st.pop();\n if(st.empty())\n st.push(i);\n len = i - st.top();\n maxlen = max(maxlen,len);\n }\n }\n return maxlen;\n }\n};\n```\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\nIf you like the solution, please upvote \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F\n
3,034
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
2,168
7
# Using Stack:\n```\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n stack=[]\n stack.append(-1)\n ans=0\n for i in range(len(s)):\n if s[i]==\'(\':\n stack.append(i)\n else:\n stack.pop()\n if len(stack)==0:\n stack.append(i)\n ans=max(ans,i-stack[-1])\n return ans\n```\n# without Space complexity:\n```\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n open,close,ans=0,0,0\n for i in s:\n if i=="(":\n open+=1\n else:\n close+=1\n if close==open:\n ans=max(ans,close+open)\n elif close>open:\n open=close=0\n open=close=0\n for i in range(len(s)-1,-1,-1):\n if "("==s[i]:\n open+=1\n else:\n close+=1\n if close==open:\n ans=max(ans,close+open)\n elif open>close:\n open=close=0\n return ans\n```
3,082
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
606
5
**Brute Force O(n) Space:**\n```\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n st=[-1]\n m=0\n for i in range(len(s)):\n if s[i]==\'(\':\n st.append(i)\n else:\n st.pop()\n if not st: #if -1 is popped\n st.append(i)\n else:\n m=max(m,i-st[-1])\n return m\n```\n**Optimized Solution O(1) Space:**\n```\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n l=r=m=0\n for i in range(len(s)):\n if s[i]==\'(\':\n l+=1\n else:\n r+=1\n if l==r: #for balanced parantheses\n m=max(m,l+r)\n elif r>l: #invalid case\n l=r=0\n l=r=0\n# We are traversing right to left for the test case where opening brackets are more than closing brackets. eg: s = "(()"\n for i in range(len(s)-1,-1,-1):\n if s[i]==\'(\':\n l+=1\n else:\n r+=1\n if l==r: #for balanced parantheses\n m=max(m,l+r)\n elif l>r: #invalid case\n l=r=0 \n return m\n```\n**An upvote will be encouraging**
3,088
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
48,470
262
# Problem Understanding\n\nThe task is to search for a target integer in a sorted array that has been rotated at an unknown pivot. \n\nFor instance, the array $$[0,1,2,4,5,6,7]$$ could be rotated at the 4th position to give $$[4,5,6,7,0,1,2]$$. The challenge is to find the position of the target integer in this rotated array. \n\n![example.png]()\n\n- The top section shows the `nums` array with a red rectangle highlighting the current "mid" value being considered in each step.\n- The bottom section displays a table that presents the steps of the binary search. Each row corresponds to a step, detailing:\n - The step number.\n - The indices of the low (L), mid (M), and high (R) pointers.\n - The values at the low (L), mid (M), and high (R) positions.\n\n# Live Coding & Explenation\n\n\n# Approach\n\nGiven the properties of the array, it\'s tempting to perform a linear search. However, that would result in a time complexity of $$O(n)$$. Instead, we can use the properties of the array to our advantage and apply a binary search to find the target with time complexity of $$ O(\\log n) $$ only.\n\n## Treating the Rotated Array\n\nAlthough the array is rotated, it retains some properties of sorted arrays that we can leverage. Specifically, one half of the array (either the left or the right) will always be sorted. This means we can still apply binary search by determining which half of our array is sorted and whether the target lies within it.\n\n## Binary Search\n\nBinary search is an efficient algorithm for finding a target value within a sorted list. It works by repeatedly dividing the search interval in half. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.\n\n## Initialization\n\nWe start with two pointers:\n\n- $$ \\text{left} $$ - This represents the beginning of the array. We initialize it to 0, the index of the first element.\n- $$ \\text{right} $$ - This represents the end of the array. It\'s set to $$ n - 1 $$, the index of the last element, where $$ n $$ is the length of the array.\n\n## Iterative Binary Search\n\nWe perform the binary search within a while loop until $$ \\text{left} $$ exceeds $$ \\text{right} $$. In each iteration, we calculate the midpoint between $$ \\text{left} $$ and $$ \\text{right} $$.\n\n### Deciding the Sorted Half:\n\nAt any point during the search in the rotated array, one half (either the left or the right) will always be sorted. Determining which half is sorted is crucial for our modified binary search. \n\n- **If left half $$[low...mid]$$ is sorted**: We know this if the element at $$ \\text{low} $$ is less than or equal to the element at $$ \\text{mid} $$. In a normally sorted array, if the start is less than or equal to the midpoint, it means all elements till the midpoint are in the correct increasing order.\n\n - **If the target lies within this sorted left half**: We know this if the target is greater than or equal to the element at $$ \\text{low} $$ and less than the element at $$ \\text{mid} $$. If this is the case, we then move our search to this half, meaning, we update $$ \\text{high} $$ to $$ \\text{mid} - 1 $$.\n\n - **Otherwise**: The target must be in the right half. So, we update $$ \\text{low} $$ to $$ \\text{mid} + 1 $$.\n\n- **If right half $$[mid...high]$$ is sorted**: This is the else part. If the left half isn\'t sorted, the right half must be!\n\n - **If the target lies within this sorted right half**: We know this if the target is greater than the element at $$ \\text{mid} $$ and less than or equal to the element at $$ \\text{high} $$. If so, we move our search to this half by updating $$ \\text{low} $$ to $$ \\text{mid} + 1 $$.\n\n - **Otherwise**: The target must be in the left half. So, we update $$ \\text{high} $$ to $$ \\text{mid} - 1 $$.\n\n### Rationale:\n\nThe beauty of this approach lies in its ability to determine with certainty which half of the array to look in, even though the array is rotated. By checking which half of the array is sorted and then using the sorted property to determine if the target lies in that half, we can effectively eliminate half of the array from consideration at each step, maintaining the $$ O(\\log n) $$ time complexity of the binary search.\n\n## Complexity\n\n**Time Complexity**: The time complexity is $$ O(\\log n) $$ since we\'re performing a binary search over the elements of the array.\n\n**Space Complexity**: The space complexity is $$ O(1) $$ because we only use a constant amount of space to store our variables ($$ \\text{left} $$, $$\\text{right} $$, $$ \\text{mid} $$), regardless of the size of the input array.\n\n# Performance\n\n![33-per.png]()\n\n\n# Code\n\n``` Python []\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n left, right = 0, len(nums) - 1\n\n while left <= right:\n mid = (left + right) // 2\n\n if nums[mid] == target:\n return mid\n\n # Check if left half is sorted\n if nums[left] <= nums[mid]:\n if nums[left] <= target < nums[mid]:\n right = mid - 1\n else:\n left = mid + 1\n # Otherwise, right half is sorted\n else:\n if nums[mid] < target <= nums[right]:\n left = mid + 1\n else:\n right = mid - 1\n\n return -1\n```\n``` C++ []\nclass Solution {\npublic:\n int search(std::vector<int>& nums, int target) {\n int low = 0, high = nums.size() - 1;\n\n while (low <= high) {\n int mid = (low + high) / 2;\n\n if (nums[mid] == target) {\n return mid;\n }\n\n if (nums[low] <= nums[mid]) {\n if (nums[low] <= target && target < nums[mid]) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n } else {\n if (nums[mid] < target && target <= nums[high]) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n }\n\n return -1;\n }\n};\n```\n``` Go []\nfunc search(nums []int, target int) int {\n low, high := 0, len(nums) - 1\n\n for low <= high {\n mid := (low + high) / 2\n\n if nums[mid] == target {\n return mid\n }\n\n if nums[low] <= nums[mid] {\n if nums[low] <= target && target < nums[mid] {\n high = mid - 1\n } else {\n low = mid + 1\n }\n } else {\n if nums[mid] < target && target <= nums[high] {\n low = mid + 1\n } else {\n high = mid - 1\n }\n }\n }\n\n return -1\n}\n```\n``` Rust []\nimpl Solution {\n pub fn search(nums: Vec<i32>, target: i32) -> i32 {\n let mut low = 0;\n let mut high = nums.len() as i32 - 1;\n\n while low <= high {\n let mid = (low + high) / 2;\n\n if nums[mid as usize] == target {\n return mid;\n }\n\n if nums[low as usize] <= nums[mid as usize] {\n if nums[low as usize] <= target && target < nums[mid as usize] {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n } else {\n if nums[mid as usize] < target && target <= nums[high as usize] {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n }\n\n -1\n }\n}\n```\n``` Java []\nclass Solution {\n public int search(int[] nums, int target) {\n int low = 0, high = nums.length - 1;\n\n while (low <= high) {\n int mid = (low + high) / 2;\n\n if (nums[mid] == target) {\n return mid;\n }\n\n if (nums[low] <= nums[mid]) {\n if (nums[low] <= target && target < nums[mid]) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n } else {\n if (nums[mid] < target && target <= nums[high]) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n }\n\n return -1;\n }\n}\n```\n``` JavaScript []\n/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number}\n */\nvar search = function(nums, target) {\n let low = 0, high = nums.length - 1;\n\n while (low <= high) {\n let mid = Math.floor((low + high) / 2);\n\n if (nums[mid] === target) {\n return mid;\n }\n\n if (nums[low] <= nums[mid]) {\n if (nums[low] <= target && target < nums[mid]) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n } else {\n if (nums[mid] < target && target <= nums[high]) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n }\n\n return -1;\n};\n```\n``` C# []\npublic class Solution {\n public int Search(int[] nums, int target) {\n int low = 0, high = nums.Length - 1;\n\n while (low <= high) {\n int mid = (low + high) / 2;\n\n if (nums[mid] == target) {\n return mid;\n }\n\n if (nums[low] <= nums[mid]) {\n if (nums[low] <= target && target < nums[mid]) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n } else {\n if (nums[mid] < target && target <= nums[high]) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n }\n\n return -1;\n }\n}\n```\n\nI hope this explanation provides clarity on the "Search in Rotated Sorted Array" problem. If you have any more questions, feel free to ask! If you found this helpful, consider giving it a thumbs up. Happy coding! \uD83D\uDC69\u200D\uD83D\uDCBB\uD83D\uDE80\uD83D\uDC68\u200D\uD83D\uDCBB
3,100
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
1,466
6
<iframe width="560" height="315" src="" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>\n\n```\nclass Solution {\n public int search(int[] A, int B) {\n int l = 0;\n int r = A.length-1;\n int m;\n while(l<=r){\n m = (l+r)/2;\n if(A[m] == B) return m;\n if(A[m]>=A[0]){\n if(B>=A[0] && B<=A[m]) r = m-1;\n else l = m+1;\n }else{\n if(B>=A[m] && B<=A[A.length-1]) l = m+1;\n else r = m-1;\n }\n\n }\n return -1;\n }\n}\n```\n\n```\nclass Solution {\npublic:\n int search(vector<int>& A, int B) {\n int l = 0;\n int r = A.size() - 1;\n int m;\n while (l <= r) {\n m = (l + r) / 2;\n if (A[m] == B) return m;\n if (A[m] >= A[0]) {\n if (B >= A[0] && B <= A[m]) r = m - 1;\n else l = m + 1;\n } else {\n if (B >= A[m] && B <= A[A.size() - 1]) l = m + 1;\n else r = m - 1;\n }\n }\n return -1;\n }\n};\n```\n\n```\nclass Solution:\n def search(self, A: List[int], B: int) -> int:\n l = 0\n r = len(A) - 1\n while l <= r:\n m = (l + r) // 2\n if A[m] == B:\n return m\n if A[m] >= A[0]:\n if B >= A[0] and B <= A[m]:\n r = m - 1\n else:\n l = m + 1\n else:\n if B >= A[m] and B <= A[-1]:\n l = m + 1\n else:\n r = m - 1\n return -1\n\n```
3,116
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
32,004
90
# Intuition:\nThe given problem asks us to find the index of the target element in the given rotated sorted array.\n\n# Approach:\n- The solution provided in the code implements two approaches, Brute force and Binary search.\n\n - The Brute force approach: \n 1. Iterates through the array and checks if the current element is equal to the target. If it is, then it returns the index of that element, otherwise, it returns -1. This approach has a time complexity of O(n).\n\n - The Binary search approach is based on the fact that a rotated sorted array can be divided into two sorted arrays.\n 1. The approach starts with finding the mid element and compares it with the target element. \n 2. If they are equal, it returns the mid index. If the left half of the array is sorted, then it checks if the target lies between the start and the mid, and updates the end pointer accordingly. \n 3. Otherwise, it checks if the target lies between mid and end, and updates the start pointer accordingly. \n 4. If the right half of the array is sorted, then it checks if the target lies between mid and end, and updates the start pointer accordingly. \n 5. Otherwise, it checks if the target lies between start and mid, and updates the end pointer accordingly. \n 6. This process continues until the target element is found, or the start pointer becomes greater than the end pointer, in which case it returns -1. \n 7. This approach has a time complexity of O(log n).\n\n# Complexity:\n\n- Time Complexity:\n 1. The time complexity of the Brute force approach is O(n), where n is the size of the input array.\n 2. The time complexity of the Binary search approach is O(log n), where n is the size of the input array.\n\n- Space Complexity:\nThe space complexity of both approaches is O(1) as we are not using any extra space to store any intermediate results.\n\n---\n\n\n# Code: C++\n## Brute Force:\n```\nclass Solution {\npublic:\n int search(vector<int>& nums, int target) {\n for(int i=0;i<nums.size();i++){\n if(target==nums[i]){\n return i;\n }\n }\n return -1;\n }\n};\n```\n## Binary Search:\n```\nclass Solution {\npublic:\n int search(vector<int>& nums, int target) {\n int start=0,end=nums.size()-1;\n int mid= (start+end)/2;\n while(start<=end){\n mid=(start+end)/2;\n if(target==nums[mid]){\n return mid;\n }\n if(nums[start]<=nums[mid]){\n if(nums[start]<=target && nums[mid]>=target){\n end=mid-1;\n }\n else{\n start=mid+1;\n }\n }\n else{\n if(nums[end]>=target && nums[mid]<=target){\n start=mid+1;\n }\n else{\n end=mid-1;\n }\n }\n }\n return -1;\n }\n};\n\n```\n\n---\n\n# Code: Java\n## Binary Search:\n```\nclass Solution {\n public int search(int[] nums, int target) {\n int start = 0, end = nums.length - 1;\n int mid = (start + end) / 2;\n while (start <= end) {\n mid = (start + end) / 2;\n if (target == nums[mid]) {\n return mid;\n }\n if (nums[start] <= nums[mid]) {\n if (nums[start] <= target && nums[mid] >= target) {\n end = mid - 1;\n } else {\n start = mid + 1;\n }\n } else {\n if (nums[end] >= target && nums[mid] <= target) {\n start = mid + 1;\n } else {\n end = mid - 1;\n }\n }\n }\n return -1;\n }\n}\n\n```\n\n---\n\n# Code: Python\n## Binary Search:\n```\nclass Solution:\n def search(self, nums, target):\n start, end = 0, len(nums) - 1\n mid = (start + end) / 2\n while start <= end:\n mid = (start + end) / 2\n if target == nums[mid]:\n return mid\n if nums[start] <= nums[mid]:\n if nums[start] <= target and nums[mid] >= target:\n end = mid - 1\n else:\n start = mid + 1\n else:\n if nums[end] >= target and nums[mid] <= target:\n start = mid + 1\n else:\n end = mid - 1\n return -1\n\n```\n\n---\n\n# Code: JavaScript\n## Binary Search:\n```\nvar search = function(nums, target) {\n let start = 0, end = nums.length - 1;\n let mid = Math.floor((start + end) / 2);\n while (start <= end) {\n mid = Math.floor((start + end) / 2);\n if (target === nums[mid]) {\n return mid;\n }\n if (nums[start] <= nums[mid]) {\n if (nums[start] <= target && nums[mid] >= target) {\n end = mid - 1;\n } else {\n start = mid + 1;\n }\n } else {\n if (nums[end] >= target && nums[mid] <= target) {\n start = mid + 1;\n } else {\n end = mid - 1;\n }\n }\n }\n return -1;\n}\n\n```\n> # ***Thanks For Voting***\n
3,139
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
5,007
34
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nArray is sorted and rotated if we are able to find in which part target is present and also whether it is sorted or not then we can search easily by binary search.\n\nFor detailed explanation you can refer to my youtube channel (Hindi Language)\n\n or link in my profile.Here,you can find any solution in playlists monthwise from june 2023 with detailed explanation.i upload daily leetcode solution video with short and precise explanation (5-10) minutes.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. Initialize two pointers `i` and `j` to represent the current search interval, where `i` is the left boundary and `j` is the right boundary.\n\n2. Enter a loop that continues as long as `i` is less than or equal to `j`.\n\n3. Calculate the middle index `mid` as `i + (j - i) / 2`.\n\n4. Check if the element at index `mid` is equal to the target. If it is, return `mid` as the index where the target is found.\n\n5. Check if the left part of the interval (from `i` to `mid`) is sorted:\n\n a. If `nums[mid] >= nums[i]`, then the left part is sorted.\n\n b. Check if the target is within the range of values in the left sorted part (`nums[i]` to `nums[mid]`). If yes, update `j = mid - 1` to search in the left part; otherwise, update `i = mid + 1` to search in the right part.\n\n6. Check if the right part of the interval (from `mid` to `j`) is sorted:\n\n a. If `nums[mid] <= nums[j]`, then the right part is sorted.\n\n b. Check if the target is within the range of values in the right sorted part (`nums[mid]` to `nums[j]`). If yes, update `i = mid + 1` to search in the right part; otherwise, update `j = mid - 1` to search in the left part.\n\n7. If none of the conditions above is satisfied, return `-1` to indicate that the target element is not found in the array.\n\n8. After the loop ends (when `i > j`), return `-1` to indicate that the target element is not found in the rotated sorted array.\n\n# Complexity\n- Time complexity:O(log n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` C++ []\nclass Solution {\npublic:\n int search(vector<int>& nums, int target) {\n int i=0;\n int j=nums.size()-1;\n while(i<=j){\n int mid=i+(j-i)/2;\n if(nums[mid]==target){\n return mid;\n }\n else if(nums[mid]>=nums[i]){\n if(target>=nums[i]&& target<nums[mid]){\n j=mid-1;\n }\n else\n i=mid+1;\n }\n else if(nums[mid]<=nums[j]){\n if(target>nums[mid]&&target<=nums[j])\n i=mid+1;\n else\n j=mid-1;\n }\n }\n return -1;\n }\n};\n```\n```java []\nclass Solution {\n public int search(int[] nums, int target) {\n int i = 0;\n int j = nums.length - 1;\n while (i <= j) {\n int mid = i + (j - i) / 2;\n if (nums[mid] == target) {\n return mid;\n } else if (nums[mid] >= nums[i]) {\n if (target >= nums[i] && target < nums[mid]) {\n j = mid - 1;\n } else {\n i = mid + 1;\n }\n } else if (nums[mid] <= nums[j]) {\n if (target > nums[mid] && target <= nums[j]) {\n i = mid + 1;\n } else {\n j = mid - 1;\n }\n }\n }\n return -1;\n }\n}\n\n```\n```python []\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n i = 0\n j = len(nums) - 1\n while i <= j:\n mid = i + (j - i) // 2\n if nums[mid] == target:\n return mid\n elif nums[mid] >= nums[i]:\n if target >= nums[i] and target < nums[mid]:\n j = mid - 1\n else:\n i = mid + 1\n elif nums[mid] <= nums[j]:\n if target > nums[mid] and target <= nums[j]:\n i = mid + 1\n else:\n j = mid - 1\n return -1\n\n```\n\n
3,141
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
769
5
Here\'s the intuition:\n\n1. If we can determine`k`, the so-called *unknown pivot index*, the solution becomes easier. The key is that `nums[k]` is the first element in `nums` that is strictly less than `nums[0]`, so we can find it in *O*(log*N*) time with a boolean binary search.\n\n1. We now have the two subrrays, `nums[:k]` and `nums[k:]`, and we easily deduce in which subarray `target` must lie (if it indeed does lie in`nums`) by comparing `target` to `nums[0]`.\n\n1. We perform a numerical binary search on the appropriate subarray, return the index if we find`target`, otherwise we return`-1`.\n\n\n```\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n\n k = bisect_left(nums, True, key = lambda x: x < nums[0]) # <-- 1\n \n if target >= nums[0]: # <-- 2\n \n left = bisect_left(nums, target, hi = k-1) # \n return left if nums[left] == target else -1 #\n # <-- 3\n rght = bisect_left(nums, target, lo = k) #\n return rght if rght < len(nums # (this line to avoid index out of range)\n ) and nums[rght] == target else -1 #\n```\n[](http://)\n\nI could be wrong, but I think that time complexity is *O*(log*N*) and space complexity is *O*(1), in which *N* ~ `len(nums)`.
3,172
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
2,268
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem is solved by using binary search several times.\nFirstly, it is suggested to find the location for the peak which can be done by binary search.\nSecondly, using binary search to find location for the target which is possible before the peak or after the peak.\n\nBe careful for the boundary cases when n=1 and n=2.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo find the location for the peak, it needs to build a binary searching function for this special purpose. Once the location of the peak is sure, then use the built-in C++ lower_bound to find the target.\n\nThe python solution uses bisect_left.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n $$O(\\log n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n $$O(1)$$\n# Code\n```\nclass Solution {\npublic:\n int n;\n vector<int> x;\n int findK() {\n if (n==1) return 0;\n if (n==2) return (x[0]<x[1])?1:0;\n int l=0, r=n, m;\n while(l<r){\n m=(r+l)/2;\n if (m==n-1 || x[m]>x[m+1]) return m;\n if (x[m]>x[l]) l=m;\n else r=m; \n }\n return m;\n }\n int search(vector<int>& nums, int target) {\n x=nums;\n n=nums.size();\n int k=findK();\n // cout<<"k="<<k<<endl;\n auto it=x.begin();\n if (target>=x[0] || k==n-1){\n int i=lower_bound(it,it+k+1,target)-it;\n if (i == k+1 || x[i] != target) return -1;\n return i;\n } \n else{\n int i=lower_bound(it+k+1,it+n,target)-it;\n if (i == n || x[i] != target) return -1;\n return i;\n }\n }\n};\n```\n# Python solution\n```\nclass Solution:\n def search(self, x: List[int], target: int) -> int:\n n = len(x)\n \n def findK():\n if n == 1:\n return 0\n if n==2:\n if x[0]<x[1]: return 1\n else: return 0\n l=0\n r=n\n while l < r:\n m = (r + l) // 2\n if m==n-1 or x[m]>x[m+1]: return m\n if x[m]>x[l]: l=m\n else: r=m\n return m\n \n k=findK()\n \n if target >= x[0]:\n i = bisect_left(x, target, hi=k)\n if i<n and x[i] == target:\n return i\n return -1\n else:\n i = bisect_left(x, target, lo=k+1)\n if i<n and x[i] == target:\n return i\n return -1\n```\n# findK() uses bisect_right()\n```\ndef findK():\n if n == 1:\n return 0\n return bisect_right(x, False, key=lambda y: y < x[0])\n```
3,197
Find First and Last Position of Element in Sorted Array
find-first-and-last-position-of-element-in-sorted-array
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
12,455
88
# \uD83D\uDE80 Hi, I\'m [Mohammed Raziullah Ansari](), and I\'m excited to share 4 ways to solve this question with detailed explanation of each approach:\n\n# Problem Explaination: \nConsider a long list of numbers that are listed from smallest to largest, in that order. We refer to this list as an array. Additionally, we are looking for a particular number on this list.\n\nwe now need to know not only if that number is in the list but also when and where it first and last appears.\n\n**Here\'s an example:**\n\nArray: [1, 2, 2, 4, 4, 4, 7, 9, 10]\n\nNumber we are looking for: 4\n\nWe want to find:\n\nThe first position where the number 4 appears, which is the index 3 in this case.\nThe last position where the number 4 appears, which is the index 5 in this case.\n\n# \uD83D\uDD0D Methods To Solve This Problem:\nI\'ll be covering four different methods to solve this problem:\n1. Linear Search (Brute Force)\n2. Binary Search (Two Binary Searches)\n3. Modified Binary Search (Optimized)\n4. Two-Pointer Approach\n\n# 1. Linear Search (Brute Force): \n\n- Initialize two variables, first and last, to -1.\n- Iterate through the sorted array from left to right.\n- When you encounter the target element for the first time, set first to the current index.\n- Continue iterating to find the last occurrence of the target element and update last whenever you encounter it.\n- Return first and last\n# Complexity\n- \u23F1\uFE0F Time Complexity: O(n) - In the worst case, you may have to traverse the entire array.\n\n- \uD83D\uDE80 Space Complexity: O(1) - Constant extra space is used.\n\n# Code\n```Python []\nclass Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n first, last = -1, -1\n for i in range(len(nums)):\n if nums[i] == target:\n if first == -1:\n first = i\n last = i\n return [first, last]\n\n```\n```Java []\nclass Solution {\n public int[] searchRange(int[] nums, int target) {\n int first = -1, last = -1;\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] == target) {\n if (first == -1) {\n first = i;\n }\n last = i;\n }\n }\n return new int[]{first, last};\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> searchRange(vector<int>& nums, int target) {\n int first = -1, last = -1;\n for (int i = 0; i < nums.size(); ++i) {\n if (nums[i] == target) {\n if (first == -1) {\n first = i;\n }\n last = i;\n }\n }\n return {first, last};\n }\n};\n\n```\n```C []\nint* searchRange(int* nums, int numsSize, int target, int* returnSize) {\n int first = -1, last = -1;\n for (int i = 0; i < numsSize; i++) {\n if (nums[i] == target) {\n if (first == -1) {\n first = i;\n }\n last = i;\n }\n }\n\n int* result = (int*)malloc(2 * sizeof(int));\n result[0] = first;\n result[1] = last;\n *returnSize = 2;\n return result;\n}\n\n```\n# 2. Binary Search (Two Binary Searches):\n- Perform a binary search to find the first occurrence of the target element.\n- Perform another binary search to find the last occurrence of the target element.\n- Return the results from the two binary searches.\n# Complexity\n- \u23F1\uFE0F Time Complexity: O(n) - Two binary searches are performed.\n\n- \uD83D\uDE80 Space Complexity: O(1) - Constant extra space is used.\n\n# Code\n```Python []\nclass Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n def findFirst(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = left + (right - left) // 2\n if nums[mid] == target:\n if mid == 0 or nums[mid - 1] != target:\n return mid\n else:\n right = mid - 1\n elif nums[mid] < target:\n left = mid + 1\n else:\n right = mid - 1\n return -1\n \n def findLast(nums, target):\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = left + (right - left) // 2\n if nums[mid] == target:\n if mid == len(nums) - 1 or nums[mid + 1] != target:\n return mid\n else:\n left = mid + 1\n elif nums[mid] < target:\n left = mid + 1\n else:\n right = mid - 1\n return -1\n \n first = findFirst(nums, target)\n last = findLast(nums, target)\n return [first, last]\n\n```\n```Java []\nclass Solution {\n public int[] searchRange(int[] nums, int target) {\n int first = findFirst(nums, target);\n int last = findLast(nums, target);\n return new int[]{first, last};\n }\n\n private int findFirst(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n int first = -1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) {\n if (mid == 0 || nums[mid - 1] != target) {\n first = mid;\n break;\n } else {\n right = mid - 1;\n }\n } else if (nums[mid] < target) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n return first;\n }\n\n private int findLast(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n int last = -1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) {\n if (mid == nums.length - 1 || nums[mid + 1] != target) {\n last = mid;\n break;\n } else {\n left = mid + 1;\n }\n } else if (nums[mid] < target) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n return last;\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> searchRange(vector<int>& nums, int target) {\n int first = findFirst(nums, target);\n int last = findLast(nums, target);\n return {first, last};\n }\n\nprivate:\n int findFirst(vector<int>& nums, int target) {\n int left = 0, right = nums.size() - 1;\n int first = -1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) {\n if (mid == 0 || nums[mid - 1] != target) {\n first = mid;\n break;\n }\n else {\n right = mid - 1;\n }\n }\n else if (nums[mid] < target) {\n left = mid + 1;\n }\n else {\n right = mid - 1;\n }\n }\n return first;\n }\n\n int findLast(vector<int>& nums, int target) {\n int left = 0, right = nums.size() - 1;\n int last = -1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) {\n if (mid == nums.size() - 1 || nums[mid + 1] != target) {\n last = mid;\n break;\n }\n else {\n left = mid + 1;\n }\n }\n else if (nums[mid] < target) {\n left = mid + 1;\n }\n else {\n right = mid - 1;\n }\n }\n return last;\n }\n};\n\n```\n```C []\nint* searchRange(int* nums, int numsSize, int target, int* returnSize) {\n int first = findFirst(nums, numsSize, target);\n int last = findLast(nums, numsSize, target);\n\n int* result = (int*)malloc(2 * sizeof(int));\n result[0] = first;\n result[1] = last;\n *returnSize = 2;\n return result;\n}\n\nint findFirst(int* nums, int numsSize, int target) {\n int left = 0, right = numsSize - 1;\n int first = -1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) {\n if (mid == 0 || nums[mid - 1] != target) {\n first = mid;\n break;\n } else {\n right = mid - 1;\n }\n } else if (nums[mid] < target) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n return first;\n}\n\nint findLast(int* nums, int numsSize, int target) {\n int left = 0, right = numsSize - 1;\n int last = -1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) {\n if (mid == numsSize - 1 || nums[mid + 1] != target) {\n last = mid;\n break;\n } else {\n left = mid + 1;\n }\n } else if (nums[mid] < target) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n return last;\n}\n\n```\n# 3. Modified Binary Search (Optimized):\n - Initialize two variables, first and last, to -1.\n- Perform a binary search to find the target element.\n- When you find the target element, update first to the current index and continue searching for the first occurrence in the left subarray.\n- Similarly, update last to the current index and continue searching for the last occurrence in the right subarray.\n- Continue until the binary search terminates.\n- Return first and last.\n# Complexity\n- \u23F1\uFE0F Time Complexity: O(n) - One binary search with constant additional work.\n\n- \uD83D\uDE80 Space Complexity: O(1) - Constant extra space is used.\n\n# Code\n```Python []\nclass Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n def findFirst(nums, target):\n left, right = 0, len(nums) - 1\n first = -1\n while left <= right:\n mid = left + (right - left) // 2\n if nums[mid] == target:\n first = mid\n right = mid - 1\n elif nums[mid] < target:\n left = mid + 1\n else:\n right = mid - 1\n return first\n \n def findLast(nums, target):\n left, right = 0, len(nums) - 1\n last = -1\n while left <= right:\n mid = left + (right - left) // 2\n if nums[mid] == target:\n last = mid\n left = mid + 1\n elif nums[mid] < target:\n left = mid + 1\n else:\n right = mid - 1\n return last\n \n first = findFirst(nums, target)\n last = findLast(nums, target)\n return [first, last]\n\n```\n```Java []\nclass Solution {\n public int[] searchRange(int[] nums, int target) {\n int first = findFirst(nums, target);\n int last = findLast(nums, target);\n return new int[]{first, last};\n }\n\n private int findFirst(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n int first = -1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) {\n first = mid;\n right = mid - 1;\n } else if (nums[mid] < target) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n return first;\n }\n\n private int findLast(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n int last = -1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) {\n last = mid;\n left = mid + 1;\n } else if (nums[mid] < target) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n return last;\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> searchRange(vector<int>& nums, int target) {\n int first = findFirst(nums, target);\n int last = findLast(nums, target);\n return {first, last};\n }\n\nprivate:\n int findFirst(vector<int>& nums, int target) {\n int left = 0, right = nums.size() - 1;\n int first = -1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) {\n first = mid;\n right = mid - 1;\n }\n else if (nums[mid] < target) {\n left = mid + 1;\n }\n else {\n right = mid - 1;\n }\n }\n return first;\n }\n\n int findLast(vector<int>& nums, int target) {\n int left = 0, right = nums.size() - 1;\n int last = -1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) {\n last = mid;\n left = mid + 1;\n }\n else if (nums[mid] < target) {\n left = mid + 1;\n }\n else {\n right = mid - 1;\n }\n }\n return last;\n }\n};\n\n```\n```C []\nint* searchRange(int* nums, int numsSize, int target, int* returnSize) {\n int first = findFirst(nums, numsSize, target);\n int last = findLast(nums, numsSize, target);\n\n int* result = (int*)malloc(2 * sizeof(int));\n result[0] = first;\n result[1] = last;\n *returnSize = 2;\n return result;\n}\n\nint findFirst(int* nums, int numsSize, int target) {\n int left = 0, right = numsSize - 1;\n int first = -1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) {\n first = mid;\n right = mid - 1;\n } else if (nums[mid] < target) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n return first;\n}\n\nint findLast(int* nums, int numsSize, int target) {\n int left = 0, right = numsSize - 1;\n int last = -1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) {\n last = mid;\n left = mid + 1;\n } else if (nums[mid] < target) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n return last;\n}\n\n```\n# 4. Two-Pointer Approach:\n - Initialize two pointers, left and right, to the beginning and end of the array, respectively.\n- Initialize two variables, first and last, to -1.\n- Use a while loop with the condition left <= right.\n- Calculate the middle index as (left + right) / 2.\n- If the middle element is equal to the target, update first and last accordingly and adjust the pointers.\n- If the middle element is less than the target, update left.\n- If the middle element is greater than the target, update right.\n- Continue the loop until left is less than or equal to right.\n- Return first and last.\n# Complexity\n- \u23F1\uFE0F Time Complexity: O(n) - One pass through the array using two pointers.\n\n- \uD83D\uDE80 Space Complexity: O(1) - Constant extra space is used.\n\n# Code\n```Python []\nclass Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n left, right = 0, len(nums) - 1\n first, last = -1, -1\n \n while left <= right:\n mid = left + (right - left) // 2\n if nums[mid] == target:\n first = mid\n last = mid\n while first > 0 and nums[first - 1] == target:\n first -= 1\n while last < len(nums) - 1 and nums[last + 1] == target:\n last += 1\n return [first, last]\n elif nums[mid] < target:\n left = mid + 1\n else:\n right = mid - 1\n \n return [first, last]\n\n```\n```Java []\nclass Solution {\n public int[] searchRange(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n int first = -1, last = -1;\n\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) {\n first = mid;\n last = mid;\n while (first > 0 && nums[first - 1] == target) {\n first--;\n }\n while (last < nums.length - 1 && nums[last + 1] == target) {\n last++;\n }\n break;\n } else if (nums[mid] < target) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n\n return new int[]{first, last};\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> searchRange(vector<int>& nums, int target) {\n int left = 0, right = nums.size() - 1;\n int first = -1, last = -1;\n \n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) {\n first = mid;\n last = mid;\n while (first > 0 && nums[first - 1] == target) {\n first--;\n }\n while (last < nums.size() - 1 && nums[last + 1] == target) {\n last++;\n }\n break;\n }\n else if (nums[mid] < target) {\n left = mid + 1;\n }\n else {\n right = mid - 1;\n }\n }\n \n return {first, last};\n }\n};\n\n```\n```C []\nint* searchRange(int* nums, int numsSize, int target, int* returnSize) {\n int left = 0, right = numsSize - 1;\n int first = -1, last = -1;\n\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] == target) {\n first = mid;\n last = mid;\n while (first > 0 && nums[first - 1] == target) {\n first--;\n }\n while (last < numsSize - 1 && nums[last + 1] == target) {\n last++;\n }\n break;\n } else if (nums[mid] < target) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n\n int* result = (int*)malloc(2 * sizeof(int));\n result[0] = first;\n result[1] = last;\n *returnSize = 2;\n return result;\n}\n\n```\n# \uD83C\uDFC6Conclusion: \nThe most effective methods are Methods 3 and 4, which have constant space complexity and an O(n) time complexity. \n\n\n# \uD83D\uDCA1 I invite you to check out my profile for detailed explanations and code for each method. Happy coding and learning! \uD83D\uDCDA
3,203
Find First and Last Position of Element in Sorted Array
find-first-and-last-position-of-element-in-sorted-array
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
3,720
49
Welcome to my post! This post starts with "How we think about a solution". In other words, that is my thought process to solve the question. This post explains how I get to my solution instead of just posting solution codes or out of blue algorithms. I hope it is helpful for someone.\n\n# Intuition\nUsing Binary Search twice for left most value and right most value\n\n---\n\n# Solution Video\n\n\n\n\u25A0 Timeline of the video\n`0:00` Read the question of Find First and Last Position of Element in Sorted Array\n`1:16` Demonstrate solution with an example\n`6:59` Coding\n`9:56` Time Complexity and Space Complexity\n`10:14` Step by step algorithm\n\nI created the video last year. I write my thought process in the post to support the video. You can understand the question visually with the video and behind the scene with the post.\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,637\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\nWe have a constraint of time complexity $$O(log n)$$ and a description says "Given an array of integers `nums` sorted in non-decreasing order", so we can feel this question is solved by `binary search`.\n\nBut a challenging point of this question is that we might multiple targes in the input array, becuase we have to find the starting and ending position of a given target value.\n\n\n---\n\n\u2B50\uFE0F Points\n\nWe might have multiple targets in the input array.\n\n---\n\nThe start position and end position can be rephrased as the leftmost index and the rightmost index.\n\nSo, for the most part, we use typical binary search, but when we find a target, we need to do these.\n\n---\n\n\u2B50\uFE0F Points\n\nEvery time we find one of targets, `keep current index` and execute one of these\n\n- If we try to find left most index, move `right pointer` to `middle pointer - 1`.\n- If we try to find right most index, move `left pointer` to `middle pointer + 1`.\n\n\nBecause we need to find a target again between `left and middle pointer` or `right and middle pointer`. If we don\'t find the new target in the new range, don\'t worry. The current index you have right now is the most left index or right index.\n\n---\n\n- How we can find the most left index and right index at the same time?\n\nI think it\'s hard to find the most left index and right index at the same time, so simply we execute binary search twice for the most left index and right index, so that we can focus on one of them.\n\nLet\'s see a real algorithm!\n\n\n### Algorithm Overview:\n\n1. Define a class `Solution`.\n2. Implement a method `searchRange` that takes a sorted list of integers `nums` and a target integer `target`. This method finds the range of the target value in the input list.\n\n### Detailed Explanation:\n1. Define a class named `Solution`.\n2. Implement a method `searchRange` within the `Solution` class that takes three parameters: `nums` (a sorted list of integers), `target` (an integer to search for), and `is_searching_left` (a boolean indicating whether to search for the leftmost or rightmost occurrence of the target).\n\n a. Define a helper method `binary_search` that takes `nums`, `target`, and `is_searching_left` as arguments. This method performs binary search to find the target value and returns the index of either the leftmost or rightmost occurrence of the target value based on the `is_searching_left` parameter.\n\n b. Initialize `left` to 0, `right` to the length of `nums` minus 1, and `idx` to -1.\n\n c. Perform a binary search within the `nums` array using a while loop until `left` is less than or equal to `right`.\n\n d. Calculate the midpoint as `(left + right) // 2`.\n\n e. Compare the target value with the element at the midpoint of the array (`nums[mid]`):\n - If `nums[mid]` is greater than the target, update `right` to `mid - 1`.\n - If `nums[mid]` is less than the target, update `left` to `mid + 1`.\n - If `nums[mid]` is equal to the target, update `idx` to `mid` and adjust `left` or `right` accordingly based on `is_searching_left`.\n\n f. Return the index `idx`.\n\n3. Call `binary_search` twice within the `searchRange` method: once to find the leftmost occurrence of the target (`left = binary_search(nums, target, True)`) and once to find the rightmost occurrence of the target (`right = binary_search(nums, target, False)`).\n\n4. Return a list containing the leftmost and rightmost indices of the target: `[left, right]`.\n\nThis algorithm uses binary search to efficiently find the leftmost and rightmost occurrences of the target in the sorted array.\n\n# Complexity\n- Time complexity: $$O(log n)$$\nThe time complexity of the binary search algorithm is $$O(log n)$$ where n is the length of the input array nums. The searchRange method calls binary_search twice, so the overall time complexity remains $$O(log n)$$.\n\n- Space complexity: $$O(1)$$\nThe space complexity is $$O(1)$$ because the algorithm uses a constant amount of extra space, regardless of the size of the input array. There are no data structures or recursive calls that consume additional space proportional to the input size.\n\n```python []\nclass Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n \n def binary_search(nums, target, is_searching_left):\n left = 0\n right = len(nums) - 1\n idx = -1\n \n while left <= right:\n mid = (left + right) // 2\n \n if nums[mid] > target:\n right = mid - 1\n elif nums[mid] < target:\n left = mid + 1\n else:\n idx = mid\n if is_searching_left:\n right = mid - 1\n else:\n left = mid + 1\n \n return idx\n \n left = binary_search(nums, target, True)\n right = binary_search(nums, target, False)\n \n return [left, right]\n \n```\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number[]}\n */\nvar searchRange = function(nums, target) {\n const binarySearch = (nums, target, isSearchingLeft) => {\n let left = 0;\n let right = nums.length - 1;\n let idx = -1;\n \n while (left <= right) {\n const mid = Math.floor((left + right) / 2);\n \n if (nums[mid] > target) {\n right = mid - 1;\n } else if (nums[mid] < target) {\n left = mid + 1;\n } else {\n idx = mid;\n if (isSearchingLeft) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n }\n \n return idx;\n };\n \n const left = binarySearch(nums, target, true);\n const right = binarySearch(nums, target, false);\n \n return [left, right]; \n};\n```\n```java []\nclass Solution {\n public int[] searchRange(int[] nums, int target) {\n int[] result = {-1, -1};\n int left = binarySearch(nums, target, true);\n int right = binarySearch(nums, target, false);\n result[0] = left;\n result[1] = right;\n return result; \n }\n\n private int binarySearch(int[] nums, int target, boolean isSearchingLeft) {\n int left = 0;\n int right = nums.length - 1;\n int idx = -1;\n\n while (left <= right) {\n int mid = left + (right - left) / 2;\n \n if (nums[mid] > target) {\n right = mid - 1;\n } else if (nums[mid] < target) {\n left = mid + 1;\n } else {\n idx = mid;\n if (isSearchingLeft) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n }\n\n return idx;\n }\n\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> searchRange(vector<int>& nums, int target) {\n vector<int> result = {-1, -1};\n int left = binarySearch(nums, target, true);\n int right = binarySearch(nums, target, false);\n result[0] = left;\n result[1] = right;\n return result; \n }\n\n int binarySearch(vector<int>& nums, int target, bool isSearchingLeft) {\n int left = 0;\n int right = nums.size() - 1;\n int idx = -1;\n \n while (left <= right) {\n int mid = left + (right - left) / 2;\n \n if (nums[mid] > target) {\n right = mid - 1;\n } else if (nums[mid] < target) {\n left = mid + 1;\n } else {\n idx = mid;\n if (isSearchingLeft) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n }\n \n return idx;\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- My next post for daily conding challenge\n\n\n\n\u2B50\uFE0F Next daily challenge video\n\n\n\n- My previous post for daily coding challenge\n\n\n\n\u2B50\uFE0F Yesterday\'s daily challenge video\n\n
3,242
Find First and Last Position of Element in Sorted Array
find-first-and-last-position-of-element-in-sorted-array
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
1,903
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWe use a two-pointer approach, where low starts at the beginning of the array, and high starts at the end of the array.\nWe compare the elements at low and high with the target value.\nIf the element at low is less than the target, we increment low.\nIf the element at high is greater than the target, we decrement high.\nIf we find two elements equal to the target, we return their indices in the array as the result.\nIf we do not find any such pair, we return [-1, -1] to indicate that the target value is not present in the array.\n\n\n# Complexity\n- Time complexity:\no(n)\n- Space complexity:\no(1)\n\n# Code\n```\n\n\n```\n```c++ []\nclass Solution {\npublic:\n vector<int> searchRange(vector<int>& nums, int target) {\n vector<int> v;\n int low = 0, high = nums.size() - 1;\n while (low <= high) {\n if (nums[low] < target)\n low = low + 1;\n else if (nums[high] > target)\n high = high - 1;\n else if (nums[low] == target && nums[high] == target) {\n v.push_back(low);\n v.push_back(high);\n return {low, high};\n }\n }\n return {-1, -1};\n }\n};\n\n```\n```python []\nclass Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n low, high = 0, len(nums) - 1\n while low <= high:\n if nums[low] < target:\n low += 1\n elif nums[high] > target:\n high -= 1\n elif nums[low] == target and nums[high] == target:\n return [low, high]\n return [-1, -1]\n\n```\n```java []\nclass Solution {\n public int[] searchRange(int[] nums, int target) {\n int[] result = new int[2];\n int low = 0, high = nums.length - 1;\n while (low <= high) {\n if (nums[low] < target) {\n low++;\n } else if (nums[high] > target) {\n high--;\n } else if (nums[low] == target && nums[high] == target) {\n result[0] = low;\n result[1] = high;\n return result;\n }\n }\n result[0] = -1;\n result[1] = -1;\n return result;\n }\n}\n```\n
3,266
Find First and Last Position of Element in Sorted Array
find-first-and-last-position-of-element-in-sorted-array
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
972
15
# 1st Method :- Brute force\nThe brute force approach involves iterating through the entire array and checking each element to see if it matches the target element. Here are the steps:\n\n1. Initialize two variables, `first` and `last`, to -1. These variables will be used to store the `first` and last occurrence of the target element.\n2. Iterate through the array using a for loop and check each element:\n - a. If the current element matches the target element and `first` is still -1, set `first` to the current index.\n - b. If the current element matches the target element, update `last` to the current index.\n3. After the loop, return the values of `first` and `last`.\n## Code\n``` Java []\nclass Solution {\n public int[] searchRange(int[] nums, int target) {\n int first = -1; // Initialize first occurrence to -1\n int last = -1; // Initialize last occurrence to -1\n \n // Iterate through the array\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] == target) {\n if (first == -1) {\n first = i; // Found the first occurrence\n }\n last = i; // Update last occurrence\n }\n }\n \n // Return the result as an array\n return new int[]{first, last};\n }\n}\n\n```\n``` C++ []\nclass Solution {\npublic:\n vector<int> searchRange(vector<int>& nums, int target) {\n int first = -1; // Initialize first occurrence to -1\n int last = -1; // Initialize last occurrence to -1\n \n // Iterate through the array\n for (int i = 0; i < nums.size(); i++) {\n if (nums[i] == target) {\n if (first == -1) {\n first = i; // Found the first occurrence\n }\n last = i; // Update last occurrence\n }\n }\n \n // Return the result as a vector\n return {first, last};\n }\n};\n\n```\n``` Python []\nclass Solution:\n def searchRange(self, nums, target):\n first = -1 # Initialize first occurrence to -1\n last = -1 # Initialize last occurrence to -1\n \n # Iterate through the array\n for i in range(len(nums)):\n if nums[i] == target:\n if first == -1:\n first = i # Found the first occurrence\n last = i # Update last occurrence\n \n # Return the result as a list\n return [first, last]\n```\n\n``` JavaScript []\nvar searchRange = function(nums, target) {\n let first = -1; // Initialize first occurrence to -1\n let last = -1; // Initialize last occurrence to -1\n \n // Iterate through the array\n for (let i = 0; i < nums.length; i++) {\n if (nums[i] === target) {\n if (first === -1) {\n first = i; // Found the first occurrence\n }\n last = i; // Update last occurrence\n }\n }\n \n // Return the result as an array\n return [first, last];\n};\n```\n``` C# []\npublic int[] SearchRange(int[] nums, int target) {\n int first = -1; // Initialize first occurrence to -1\n int last = -1; // Initialize last occurrence to -1\n \n // Iterate through the array\n for (int i = 0; i < nums.Length; i++) {\n if (nums[i] == target) {\n if (first == -1) {\n first = i; // Found the first occurrence\n }\n last = i; // Update last occurrence\n }\n }\n \n // Return the result as an array\n return new int[]{first, last};\n}\n```\n``` PHP []\nclass Solution {\n function searchRange($nums, $target) {\n $first = -1; // Initialize first occurrence to -1\n $last = -1; // Initialize last occurrence to -1\n \n $n = count($nums); // Get the length of the array\n \n // Iterate through the array\n for ($i = 0; $i < $n; $i++) {\n if ($nums[$i] == $target) {\n if ($first == -1) {\n $first = $i; // Found the first occurrence\n }\n $last = $i; // Update last occurrence\n }\n }\n \n // Return the result as an array\n return [$first, $last];\n }\n}\n```\n\n\n# Complexity\n#### Time complexity: O(n);\n- The code consists of a single loop that iterates through the entire array of length `n` where `n` is the length of the nums array.\n- Within the loop, it performs constant time operations like comparisons and assignments.\n\nTherefore, the overall time complexity of the code is O(n) because it iterates through the array once.\n#### Space complexity: O(1);\n- The code uses a constant amount of extra space for variables `first` and `last`, which do not depend on the input size.\n- It creates a result array of size 2 to store the `first` and `last` occurrences, which is also constant space.\n\nHence, the space complexity of the code is O(1), indicating that it uses a constant amount of additional space regardless of the input size.\n\n![upvote.png]()\n### plz UpVote\n\n# 2nd Method :- Efficient Method\nNow, let\'s optimize the solution using a more efficient approach. We\'ll use a binary search to find the first and last occurrences of the target element. Here are the steps:\n\n1. Initialize two variables, `first` and `last`, to -1. These variables will be used to store the first and last occurrence of the target element.\n2. Perform a binary search to find the first occurrence:\n - a. Initialize `left` to 0 and `right` to the last index of the array.\n - b. While `left <= right`, calculate the middle index `mid`.\n - c. If `nums[mid]` is equal to the target, update `first` to `mid` and set `right` to `mid - 1` to search in the left half.\n - d. If `nums[mid]` is less than the target, set `left` to `mid + 1`.\n - e. If `nums[mid]` is greater than the target, set `right` to `mid - 1`.\n3. Perform another binary search to find the last occurrence:\n - a. Initialize `left` to 0 and `right` to the last index of the array.\n - b. While `left <= right`, calculate the middle index `mid`.\n - c. If `nums[mid]` is equal to the target, update `last` to `mid` and set `left` to `mid + 1` to search in the right half.\n - d. If `nums[mid]` is less than the target, set `left` to `mid + 1`.\n - e. If `nums[mid]` is greater than the target, set `right` to `mid - 1`.\n4. After both binary searches, return the values of `first` and `last`.\n\n## Code\n``` Java []\nclass Solution {\n public int[] searchRange(int[] nums, int target) {\n int first = findFirst(nums, target); // Find the first occurrence of the target.\n int last = findLast(nums, target); // Find the last occurrence of the target.\n return new int[]{first, last}; // Return the result as an array.\n }\n \n // Helper function to find the first occurrence of the target.\n private int findFirst(int[] nums, int target) {\n int left = 0; // Initialize the left pointer to the beginning of the array.\n int right = nums.length - 1; // Initialize the right pointer to the end of the array.\n int first = -1; // Initialize the variable to store the first occurrence.\n\n while (left <= right) {\n int mid = left + (right - left) / 2; // Calculate the middle index.\n\n if (nums[mid] == target) {\n first = mid; // Update first occurrence.\n right = mid - 1; // Move the right pointer to the left to search in the left half.\n } else if (nums[mid] < target) {\n left = mid + 1; // If mid element is less than target, move the left pointer to the right.\n } else {\n right = mid - 1; // If mid element is greater than target, move the right pointer to the left.\n }\n }\n \n return first; // Return the index of the first occurrence.\n }\n \n // Helper function to find the last occurrence of the target.\n private int findLast(int[] nums, int target) {\n int left = 0; // Initialize the left pointer to the beginning of the array.\n int right = nums.length - 1; // Initialize the right pointer to the end of the array.\n int last = -1; // Initialize the variable to store the last occurrence.\n\n while (left <= right) {\n int mid = left + (right - left) / 2; // Calculate the middle index.\n\n if (nums[mid] == target) {\n last = mid; // Update last occurrence.\n left = mid + 1; // Move the left pointer to the right to search in the right half.\n } else if (nums[mid] < target) {\n left = mid + 1; // If mid element is less than target, move the left pointer to the right.\n } else {\n right = mid - 1; // If mid element is greater than target, move the right pointer to the left.\n }\n }\n \n return last; // Return the index of the last occurrence.\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n vector<int> searchRange(vector<int>& nums, int target) {\n int first = findFirst(nums, target); // Find the first occurrence of the target.\n int last = findLast(nums, target); // Find the last occurrence of the target.\n return {first, last}; // Return the result as a vector.\n }\n \n // Helper function to find the first occurrence of the target.\n int findFirst(vector<int>& nums, int target) {\n int left = 0; // Initialize the left pointer to the beginning of the array.\n int right = nums.size() - 1; // Initialize the right pointer to the end of the array.\n int first = -1; // Initialize the variable to store the first occurrence.\n\n while (left <= right) {\n int mid = left + (right - left) / 2; // Calculate the middle index.\n\n if (nums[mid] == target) {\n first = mid; // Update first occurrence.\n right = mid - 1; // Move the right pointer to the left to search in the left half.\n } else if (nums[mid] < target) {\n left = mid + 1; // If mid element is less than target, move the left pointer to the right.\n } else {\n right = mid - 1; // If mid element is greater than target, move the right pointer to the left.\n }\n }\n \n return first; // Return the index of the first occurrence.\n }\n \n // Helper function to find the last occurrence of the target.\n int findLast(vector<int>& nums, int target) {\n int left = 0; // Initialize the left pointer to the beginning of the array.\n int right = nums.size() - 1; // Initialize the right pointer to the end of the array.\n int last = -1; // Initialize the variable to store the last occurrence.\n\n while (left <= right) {\n int mid = left + (right - left) / 2; // Calculate the middle index.\n\n if (nums[mid] == target) {\n last = mid; // Update last occurrence.\n left = mid + 1; // Move the left pointer to the right to search in the right half.\n } else if (nums[mid] < target) {\n left = mid + 1; // If mid element is less than target, move the left pointer to the right.\n } else {\n right = mid - 1; // If mid element is greater than target, move the right pointer to the left.\n }\n }\n \n return last; // Return the index of the last occurrence.\n }\n};\n\n```\n``` Python []\nclass Solution:\n def searchRange(self, nums, target):\n # Helper function to find the first occurrence of the target.\n def findFirst(nums, target):\n left, right = 0, len(nums) - 1\n first = -1\n\n while left <= right:\n mid = left + (right - left) // 2 # Calculate the middle index.\n\n if nums[mid] == target:\n first = mid # Update first occurrence.\n right = mid - 1 # Move the right pointer to the left to search in the left half.\n elif nums[mid] < target:\n left = mid + 1 # If mid element is less than target, move the left pointer to the right.\n else:\n right = mid - 1 # If mid element is greater than target, move the right pointer to the left.\n\n return first\n\n # Helper function to find the last occurrence of the target.\n def findLast(nums, target):\n left, right = 0, len(nums) - 1\n last = -1\n\n while left <= right:\n mid = left + (right - left) // 2 # Calculate the middle index.\n\n if nums[mid] == target:\n last = mid # Update last occurrence.\n left = mid + 1 # Move the left pointer to the right to search in the right half.\n elif nums[mid] < target:\n left = mid + 1 # If mid element is less than target, move the left pointer to the right.\n else:\n right = mid - 1 # If mid element is greater than target, move the right pointer to the left.\n\n return last\n\n # Find the first and last occurrences of the target using the helper functions.\n first = findFirst(nums, target)\n last = findLast(nums, target)\n\n return [first, last] # Return the result as a list.\n\n```\n``` JavaScript []\nvar searchRange = function(nums, target) {\n let first = findFirst(nums, target); // Find the first occurrence of the target.\n let last = findLast(nums, target); // Find the last occurrence of the target.\n return [first, last]; // Return the result as an array.\n};\n\n// Helper function to find the first occurrence of the target.\nfunction findFirst(nums, target) {\n let left = 0; // Initialize the left pointer to the beginning of the array.\n let right = nums.length - 1; // Initialize the right pointer to the end of the array.\n let first = -1; // Initialize the variable to store the first occurrence.\n\n while (left <= right) {\n let mid = left + Math.floor((right - left) / 2); // Calculate the middle index.\n\n if (nums[mid] === target) {\n first = mid; // Update first occurrence.\n right = mid - 1; // Move the right pointer to the left to search in the left half.\n } else if (nums[mid] < target) {\n left = mid + 1; // If mid element is less than target, move the left pointer to the right.\n } else {\n right = mid - 1; // If mid element is greater than target, move the right pointer to the left.\n }\n }\n \n return first; // Return the index of the first occurrence.\n}\n\n// Helper function to find the last occurrence of the target.\nfunction findLast(nums, target) {\n let left = 0; // Initialize the left pointer to the beginning of the array.\n let right = nums.length - 1; // Initialize the right pointer to the end of the array.\n let last = -1; // Initialize the variable to store the last occurrence.\n\n while (left <= right) {\n let mid = left + Math.floor((right - left) / 2); // Calculate the middle index.\n\n if (nums[mid] === target) {\n last = mid; // Update last occurrence.\n left = mid + 1; // Move the left pointer to the right to search in the right half.\n } else if (nums[mid] < target) {\n left = mid + 1; // If mid element is less than target, move the left pointer to the right.\n } else {\n right = mid - 1; // If mid element is greater than target, move the right pointer to the left.\n }\n }\n \n return last; // Return the index of the last occurrence.\n}\n\n```\n``` C# []\npublic int[] SearchRange(int[] nums, int target) {\n int first = FindFirst(nums, target); // Find the first occurrence of the target.\n int last = FindLast(nums, target); // Find the last occurrence of the target.\n return new int[]{first, last}; // Return the result as an array.\n}\n\n// Helper function to find the first occurrence of the target.\nprivate int FindFirst(int[] nums, int target) {\n int left = 0; // Initialize the left pointer to the beginning of the array.\n int right = nums.Length - 1; // Initialize the right pointer to the end of the array.\n int first = -1; // Initialize the variable to store the first occurrence.\n\n while (left <= right) {\n int mid = left + (right - left) / 2; // Calculate the middle index.\n\n if (nums[mid] == target) {\n first = mid; // Update first occurrence.\n right = mid - 1; // Move the right pointer to the left to search in the left half.\n } else if (nums[mid] < target) {\n left = mid + 1; // If mid element is less than target, move the left pointer to the right.\n } else {\n right = mid - 1; // If mid element is greater than target, move the right pointer to the left.\n }\n }\n \n return first; // Return the index of the first occurrence.\n}\n\n// Helper function to find the last occurrence of the target.\nprivate int FindLast(int[] nums, int target) {\n int left = 0; // Initialize the left pointer to the beginning of the array.\n int right = nums.Length - 1; // Initialize the right pointer to the end of the array.\n int last = -1; // Initialize the variable to store the last occurrence.\n\n while (left <= right) {\n int mid = left + (right - left) / 2; // Calculate the middle index.\n\n if (nums[mid] == target) {\n last = mid; // Update last occurrence.\n left = mid + 1; // Move the left pointer to the right to search in the right half.\n } else if (nums[mid] < target) {\n left = mid + 1; // If mid element is less than target, move the left pointer to the right.\n } else {\n right = mid - 1; // If mid element is greater than target, move the right pointer to the left.\n }\n }\n \n return last; // Return the index of the last occurrence.\n}\n\n```\n``` PHP []\nclass Solution {\n function searchRange($nums, $target) {\n $first = $this->findFirst($nums, $target); // Find the first occurrence of the target.\n $last = $this->findLast($nums, $target); // Find the last occurrence of the target.\n return [$first, $last]; // Return the result as an array.\n }\n \n // Helper function to find the first occurrence of the target.\n private function findFirst($nums, $target) {\n $left = 0; // Initialize the left pointer to the beginning of the array.\n $right = count($nums) - 1; // Initialize the right pointer to the end of the array.\n $first = -1; // Initialize the variable to store the first occurrence.\n\n while ($left <= $right) {\n $mid = $left + floor(($right - $left) / 2); // Calculate the middle index.\n\n if ($nums[$mid] == $target) {\n $first = $mid; // Update first occurrence.\n $right = $mid - 1; // Move the right pointer to the left to search in the left half.\n } elseif ($nums[$mid] < $target) {\n $left = $mid + 1; // If mid element is less than target, move the left pointer to the right.\n } else {\n $right = $mid - 1; // If mid element is greater than target, move the right pointer to the left.\n }\n }\n \n return $first; // Return the index of the first occurrence.\n }\n \n // Helper function to find the last occurrence of the target.\n private function findLast($nums, $target) {\n $left = 0; // Initialize the left pointer to the beginning of the array.\n $right = count($nums) - 1; // Initialize the right pointer to the end of the array.\n $last = -1; // Initialize the variable to store the last occurrence.\n\n while ($left <= $right) {\n $mid = $left + floor(($right - $left) / 2); // Calculate the middle index.\n\n if ($nums[$mid] == $target) {\n $last = $mid; // Update last occurrence.\n $left = $mid + 1; // Move the left pointer to the right to search in the right half.\n } elseif ($nums[$mid] < $target) {\n $left = $mid + 1; // If mid element is less than target, move the left pointer to the right.\n } else {\n $right = $mid - 1; // If mid element is greater than target, move the right pointer to the left.\n }\n }\n \n return $last; // Return the index of the last occurrence.\n }\n}\n```\n\n# Complexity\n#### Time complexity: O(log n);\n- The code consists of two binary search functions, findFirst and findLast.\n- Each binary search operates on a sorted array of length n.\n- Binary search has a time complexity of O(log n).\nSince we are performing two separate binary searches, the overall time complexity of the searchRange function is O(log n) for each binary search, resulting in a total time complexity of O(log n) for the entire algorithm.\n\n#### Space complexity: O(1);\n- The space complexity of the code is primarily determined by the space used for variables and function call stack during recursion.\n- The primary variables used are `left`, `right`, `first`, `last`, and `mid`. These variables have a constant space requirement, so they do not contribute significantly to space complexity.\n- There is no significant use of data structures that would consume additional space proportional to the input size.\n\nTherefore, the space complexity of the given code is O(1), which means it uses a constant amount of extra space regardless of the input size.
3,272
Find First and Last Position of Element in Sorted Array
find-first-and-last-position-of-element-in-sorted-array
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
1,004
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this question is to perform two binary searches separately to find the leftmost and rightmost occurrences of the target value.\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Implement two binary search functions, one to find the leftmost occurrence and another to find the rightmost occurrence.\n2. Use the binary search to locate the target value in the array.\n3. When the target is found, update the search range for the leftmost occurrence accordingly.\n4. Continue searching for the leftmost occurrence until the left and right pointers converge, and return the leftmost index.\n5. Repeat the binary search for the rightmost occurrence by adjusting the search range accordingly.\n6. Continue searching for the rightmost occurrence until the left and right pointers converge, and return the rightmost index.\n7. If the target value is not found during the binary search, return [-1, -1].\n8. Combine the results from the leftmost and rightmost binary searches and return them as the final result.\n\n---\n\n## Do Upvote if you like the solution and explanation please\n\n---\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this approach is O(log n), where n is the number of elements in the input array. Each binary search operation reduces the search space by half in each step, resulting in logarithmic time complexity.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1) because it only uses a constant amount of extra space to store the left, right, and mid pointers and the result vector. The space usage does not depend on the size of the input array.\n\n---\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> searchRange(vector<int>& nums, int target) {\n vector<int> result = {-1, -1};\n int left = binarySearch(nums, target, true);\n if (left == -1) {\n return result;\n }\n int right = binarySearch(nums, target, false);\n result[0] = left;\n result[1] = right;\n return result;\n }\n \n int binarySearch(vector<int>& nums, int target, bool findLeft) {\n int left = 0, right = nums.size() - 1;\n int index = -1;\n \n while (left <= right) {\n int mid = left + (right - left) / 2;\n \n if (nums[mid] == target) {\n index = mid;\n \n if (findLeft) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n } else if (nums[mid] < target) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n \n return index;\n }\n};\n\n```
3,273
Find First and Last Position of Element in Sorted Array
find-first-and-last-position-of-element-in-sorted-array
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
1,546
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse C++ lower_bound & upper_bound to solve this question. Python version uses bisect.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n2nd approach is self made binarch search. Use it twice and solve this question. The self made `binary_search` function is similar to C++ lower_bound. \n\nOn the 2nd applying of `binary_search` function, the parameters `nums, target+1` are input. And at final, it needs a check for `nums[j]==target`!\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n\\log n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code\n```Python []\nclass Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n n=len(nums)\n if n==0: return [-1, -1]\n i=bisect.bisect_left(nums, target)\n if i==n or nums[i]>target: return [-1, -1]\n j=bisect.bisect_right(nums, target)\n return [i, j-1]\n \n```\n```C++ []\n\nclass Solution {\npublic:\n vector<int> searchRange(vector<int>& nums, int target) {\n int n=nums.size();\n if (n==0) return {-1, -1};\n int i=lower_bound(nums.begin(), nums.end(), target)-nums.begin();\n if (i==n || nums[i]>target) return {-1, -1};\n int j=upper_bound(nums.begin(), nums.end(), target)-nums.begin();\n // cout<<i<<","<<j-1<<endl;\n return {i, j-1};\n }\n};\n```\n# Code using custom binary search\n```\nclass Solution {\npublic:\n int n;\n int binary_search(vector<int>& nums, int target){\n int l=0, r=n-1, m;\n while(l<r){\n m=(r+l)/2;\n if (nums[m]<target) l=m+1;\n else r=m;\n }\n return l;\n }\n vector<int> searchRange(vector<int>& nums, int target) {\n n=nums.size();\n if (n==0) return {-1, -1};\n int i=binary_search(nums, target);\n if (nums[i]!=target) return {-1, -1};\n int j=binary_search(nums, target+1);\n if (nums[j]==target) return {i, j}; // j might be n-1. Need this check\n return {i, j-1};\n }\n};\n\n```
3,274
Find First and Last Position of Element in Sorted Array
find-first-and-last-position-of-element-in-sorted-array
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
1,340
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this question is to count the number of occurrences of the target value in the sorted array and then calculate the starting and ending positions based on the count.\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize a count variable to keep track of the number of occurrences of the target value and set it to 0.\n2. Iterate through the array from left to right.\n3. When you encounter the target value, increment the count.\n4. If the count becomes greater than 0, this means you\'ve found at least one occurrence of the target value. Set the starting position to the index of the first occurrence.\n5. Calculate the ending position as the starting position plus the count minus one since all occurrences are adjacent in a sorted array.\n6. Return the starting and ending positions as the result.\n\n---\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this approach is O(n), where n is the number of elements in the input array. In the worst case, you may need to traverse the entire array to count the occurrences and find the starting and ending positions.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1) because it only uses a constant amount of extra space to store the count and the result vector, regardless of the size of the input array.\n\n---\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> searchRange(vector<int>& nums, int target) {\n vector<int> result = {-1, -1};\n int count = 0;\n \n for (int i = 0; i < nums.size(); ++i) {\n if (nums[i] == target) {\n if (count == 0) {\n result[0] = i;\n }\n count++;\n }\n }\n \n if (count > 0) {\n result[1] = result[0] + count - 1;\n }\n \n return result;\n }\n};\n\n```
3,293
Find First and Last Position of Element in Sorted Array
find-first-and-last-position-of-element-in-sorted-array
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
18,343
222
```python\nclass Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n \n def search(x):\n lo, hi = 0, len(nums) \n while lo < hi:\n mid = (lo + hi) // 2\n if nums[mid] < x:\n lo = mid+1\n else:\n hi = mid \n return lo\n \n lo = search(target)\n hi = search(target+1)-1\n \n if lo <= hi:\n return [lo, hi]\n \n return [-1, -1]\n```
3,298
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Easy
null
396
7
\n\nIf we simply iterated over the entire array to find the target, the algorithm would run in O(n) time. We can improve this by using binary search instead to find the element, which runs in O(log n) time (see the video for a review of binary search).\n\nNow, why does binary search run in O(log n) time? Well, with each iteration, we eliminate around half of the array. So now the question is: how many iterations does it take to converge on a single element? In other words, how many times do we need to divide `n` by 2 until we reach 1?\n\nIf <b>k</b> is the number of times we need to divide `n` by 2 to reach 1, then the equation is:\n\nn / 2<sup>k</sup> = 1\n\nn = 2<sup>k</sup> &nbsp;&nbsp;(multiply both sides by 2<sup>k</sup>)\n\nlog<sub>2</sub>n = k &nbsp;&nbsp;(definition of logarithms)\n\nSo we know that it takes log<sub>2</sub>n steps in the worst case to find the element. But in Big O notation, we drop the base, so this ends up running in O(log n) time.\n\nIf the target was not in the array, then we need to figure out what index the target <i>would</i> be at if it were inserted in sorted order. For a detailed visualization, please see the video (it\'s difficult to describe here) but basically, at the end of the loop, the left pointer will have passed the right pointer (so l > r) and the target needs to be inserted between them. Inserting at index `r` actually ends up inserting the target at 1 spot behind the correct spot, so inserting at index `l` is the correct answer.\n\n# Code\n```\nclass Solution(object):\n def searchInsert(self, nums, target):\n l = 0\n r = len(nums) - 1\n while l <= r:\n mid = (l + r) // 2\n if nums[mid] < target:\n l = mid + 1\n elif nums[mid] > target:\n r = mid - 1\n else:\n return mid\n return l\n \n```
3,301
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Easy
null
2,368
13
# Intuition\nSince the array is sorted and we need to achieve O(log n) runtime complexity, we can use binary search. Binary search is an efficient algorithm for finding a target element in a sorted array.\n\n# Approach\n**Initialize Pointers:**\n- Initialize two pointers, low and high, to represent the range of elements in the array where the target may exist. Initially, set low = 0 and high = nums.length - 1.\n\n**Binary Search:**\n- Perform a binary search within the range [low, high].\n- At each step, calculate the middle index as mid = (low + high) / 2.\n- Compare the element at the middle index (nums[mid]) with the target.\n\n**Adjust Pointers:**\n- If nums[mid] is equal to the target, return mid as the index where the target is found.\n- If nums[mid] is less than the target, adjust low to mid + 1.\n- If nums[mid] is greater than the target, adjust high to mid - 1.\n\n**Handle Insertion Position:**\n- If the loop exits without finding the target, return the current value of low as the index where the target would be inserted.\n\n# Complexity\n- **Time complexity:**\nThe time complexity of the provided solution is O(log n). This is because, in each iteration of the binary search, the search space is divided in half. The logarithmic time complexity arises from the fact that the algorithm repeatedly eliminates half of the remaining elements until the target is found or the search space is empty.\n\n- **Space complexity:**\nThe space complexity is O(1). The algorithm uses a constant amount of extra space regardless of the size of the input array. It only uses a few variables (low, high, mid) to perform the search, and the space required for these variables is independent of the input size. Therefore, the space complexity is constant.\n\n```c++ []\nclass Solution {\npublic:\n int searchInsert(vector<int>& nums, int target) {\n int low = 0;\n int high = nums.size() - 1;\n\n while (low <= high) {\n int mid = low + (high - low) / 2;\n\n if (nums[mid] == target) {\n return mid; // Target found\n } else if (nums[mid] < target) {\n low = mid + 1; // Adjust low pointer\n } else {\n high = mid - 1; // Adjust high pointer\n }\n }\n return low; // Return the index for insertion position\n }\n};\n}\n```\n```java []\nclass Solution {\n public int searchInsert(int[] nums, int target) {\n int low = 0;\n int high = nums.length - 1;\n\n while (low <= high) {\n int mid = low + (high - low) / 2;\n\n if (nums[mid] == target) {\n return mid; // Target found\n } else if (nums[mid] < target) {\n low = mid + 1; // Adjust low pointer\n } else {\n high = mid - 1; // Adjust high pointer\n }\n }\n return low; // Return the index for insertion position\n }\n}\n```\n```python []\nclass Solution:\n def search_insert(nums, target):\n low, high = 0, len(nums) - 1\n\n while low <= high:\n mid = (low + high) // 2\n\n if nums[mid] == target:\n return mid # Target found\n elif nums[mid] < target:\n low = mid + 1 # Adjust low pointer\n else:\n high = mid - 1 # Adjust high pointer\n\n return low # Return the index for insertion position\n\n```\n```javascript []\nclass Solution {\n searchInsert(nums, target) {\n let low = 0;\n let high = nums.length - 1;\n\n while (low <= high) {\n let mid = Math.floor((low + high) / 2);\n\n if (nums[mid] === target) {\n return mid; // Target found\n } else if (nums[mid] < target) {\n low = mid + 1; // Adjust low pointer\n } else {\n high = mid - 1; // Adjust high pointer\n }\n }\n\n return low; // Return the index for insertion position\n }\n}\n```\n![upvote.png]()\n\n
3,317
Valid Sudoku
valid-sudoku
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Note:
Array,Hash Table,Matrix
Medium
null
34,143
196
\n1)It initializes an empty list called "res", which will be used to store all the valid elements in the board.\n\n2)It loops through each cell in the board using two nested "for" loops.\nFor each cell, it retrieves the value of the element in that cell and stores it in a variable called "element".\n\n3)If the element is not a dot (\'.\'), which means it\'s a valid number, the method adds three tuples to the "res" list:\n\n- The first tuple contains the row index (i) and the element itself.\n- The second tuple contains the element itself and the column index (j).\n- The third tuple contains the floor division of the row index by 3 (i // 3), the floor division of the column index by 3 (j // 3), and the element itself. This tuple represents the 3x3 sub-grid that the current cell belongs to.\n\n4)After processing all the cells, the method checks if the length of "res" is equal to the length of the set of "res".\n\n```\nclass Solution(object):\n def isValidSudoku(self, board):\n res = []\n for i in range(9):\n for j in range(9):\n element = board[i][j]\n if element != \'.\':\n res += [(i, element), (element, j), (i // 3, j // 3, element)]\n return len(res) == len(set(res))\n\n```
3,404
Valid Sudoku
valid-sudoku
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Note:
Array,Hash Table,Matrix
Medium
null
74,429
824
Apparently not the shortest solution but I think it's easy to follow the logic.\n\n \n def isValidSudoku(self, board):\n return (self.is_row_valid(board) and\n self.is_col_valid(board) and\n self.is_square_valid(board))\n \n def is_row_valid(self, board):\n for row in board:\n if not self.is_unit_valid(row):\n return False\n return True\n \n def is_col_valid(self, board):\n for col in zip(*board):\n if not self.is_unit_valid(col):\n return False\n return True\n \n def is_square_valid(self, board):\n for i in (0, 3, 6):\n for j in (0, 3, 6):\n square = [board[x][y] for x in range(i, i + 3) for y in range(j, j + 3)]\n if not self.is_unit_valid(square):\n return False\n return True\n \n def is_unit_valid(self, unit):\n unit = [i for i in unit if i != '.']\n return len(set(unit)) == len(unit)
3,414
Valid Sudoku
valid-sudoku
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Note:
Array,Hash Table,Matrix
Medium
null
10,094
104
Hello!\n\nTo solve this problem we have to check if each value in sudoku does not repeat in its:\n1. column\n2. row\n3. square\n\nTo do this efficiently we will use **sets** to store elements in columns, rows and squares. This is easy to define column and row (by single index), but squares are defined using two indexes. We will use **//** (floor division) operator to know in which square we are right now.\n\nIndexes range from **0** to **8**. \n0 // 3 = 0\n1 // 3 = 0\n2 // 3 = 0\n3 // 3 = 1\n4 // 3 = 1\n5 // 3 = 1\n6 // 3 = 2\n7 // 3 = 2\n8 // 3 = 2\n\nWe got 3 different values for each range (0-2: **0**, 3-5: **1**, 6-8: **2**), so we can use it to know in which square are currently are (by getting square **x** and **y** coordinate, we need 9 squares with indexes (0, 0), (0, 1), (0, 2), (1,0), ..., (2, 2)).\n\nIn code we do nothing if we meet **.** symbol, but if we have **digit** in cell, then we check if it is in cell\'s row, column or square. \nIf **yes**, then it means that the value is repeated, so sudoku is not valid one, so we return **False**.\n\nAfter checking, we add this value to its row, column and square.\nIf number occurs 2 times in given row, cell or square, then the 2nd occurence is going to trigger **False** return (because in first occurence we add the value to the **sets**).\n\nCode:\n```\nclass Solution:\n def isValidSudoku(self, board: List[List[str]]) -> bool:\n rows = [set() for x in range(9)]\n columns = [set() for x in range(9)]\n squares = [[set() for x in range(3)] for y in range(3)]\n \n for x in range(9):\n for y in range(9):\n cell_value = board[x][y]\n if cell_value == ".":\n continue\n if cell_value in rows[x] or cell_value in columns[y] or cell_value in squares[x//3][y//3]:\n return False\n\n rows[x].add(cell_value)\n columns[y].add(cell_value)\n squares[x//3][y//3].add(cell_value)\n \n return True\n```\n\nPlease upvote if it was helpful :))
3,415
Valid Sudoku
valid-sudoku
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Note:
Array,Hash Table,Matrix
Medium
null
1,593
15
# Intuition\n*A simple straight-forward solution!*\n\n# Approach\nThis code block is an implementation of the solution to `isValidSudoku`. Let\'s break down the code step by step:\n\n1. The code starts by importing the `collections` module, which is used to create defaultdicts (Why? Will explain!).\n \n2. Within the `isValidSudoku` method, three defaultdicts are created: `rows`, `columns`, and `sub_boxes`. These defaultdicts will store sets of numbers that are present in each row, column, and sub-box of the Sudoku board, respectively.\n\n3. The code then uses two nested loops to iterate through each cell in the 9x9 Sudoku board.\n\n4. For each cell, it checks the value of the number in the cell (`num`):\n\n - If the cell contains a period (`.`), which represents an empty cell, it skips the current iteration using `continue`.\n\n - If the cell contains a number, it checks three conditions to determine if the number violates the rules of Sudoku:\n\n - It checks if the number is already present in the set of numbers in the same row (`rows[row]`).\n \n - It checks if the number is already present in the set of numbers in the same column (`columns[col]`).\n \n - It checks if the number is already present in the set of numbers in the corresponding sub-box (`sub_boxes[(row//3, col//3)]`).\n\n - If any of these conditions are met, it means the Sudoku rules are violated, and the function immediately returns `False`, indicating that the Sudoku board is not valid.\n\n5. If none of the conditions are met, meaning the number can be safely placed in the current cell without violating any rules, the code updates the sets in `rows`, `columns`, and `sub_boxes` to include the new number.\n\n6. After iterating through the entire board, if no violations were found, the function returns `True`, indicating that the Sudoku board is valid.\n\n\n# Complexity\n- Time complexity:\n O(1) , ***Actually O(81) since constant\'s are O(1)***\n\n- Space complexity:\n O(1), ***Confusing? It\'s simple. The total space incurred will be three times the size of the Sudoku board, and it\'s constant in length! It might get smaller but will never exceed 3(9+1 x 9+1).***\n\n# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def isValidSudoku(self, board: List[List[str]]) -> bool:\n # Create dictionaries to keep track of numbers in rows, columns, and sub-boxes\n rows = collections.defaultdict(set)\n columns = collections.defaultdict(set)\n sub_boxes = collections.defaultdict(set)\n\n # Iterate through each cell in the 9x9 Sudoku board\n for row in range(9):\n for col in range(9):\n num = board[row][col]\n\n # Skip empty cells represented by "."\n if num == ".":\n continue\n\n # Check if the current number violates Sudoku rules\n if (num in rows[row] or \n num in columns[col] or \n num in sub_boxes[(row // 3, col // 3)]):\n return False\n\n # Update sets to keep track of encountered numbers\n rows[row].add(num)\n columns[col].add(num)\n sub_boxes[(row // 3, col // 3)].add(num)\n\n # If all cells satisfy Sudoku rules, the board is valid\n return True\n\n```\n\n***Extra note:***\n\n*Why we used **defaultdict?**.*\n-- *It is to simplify the process of initializing and accessing values in a dictionary, especially when dealing with keys that might not exist yet. It provides a convenient way to handle default values for keys that are not present in the dictionary.*\n\n\n- `num in sub_boxes[(row // 3, col // 3)]`:\n\n*This line checks whether the number `num` is already present in the set that corresponds to the specific ***3x3*** sub-box where the current cell is located.*\n\n*Imagine you\'re playing a game on a ***9x9*** Sudoku board. To make sure you\'re not violating the rules, you want to know if the number you\'re considering ***(let\'s say "5")*** is already in the little ***3x3*** box that your current cell is part of. You\'d look at that ***3x3*** box, see if the number ***"5"*** is already there, and if it is, you\'d know you can\'t place another ***"5"*** there. This line of code is doing that exact check for you, but programmatically.*\n\n```\n 0 1 2\n - - - | - - - | - - -\n0 - - - | - - - | - - - // sub_boxes key\'s as a tuple (x,y)\n - - - | - - - | - - -\n -----------------------\n - - - | - - - | - - -\n1 - - - | - - - | - - -\n - - - | - - - | - - -\n -----------------------\n - - - | - - - | - - -\n2 - - - | - - - | - - -\n - - - | - - - | - - -\n```\n\n- `sub_boxes[(row // 3, col // 3)].add(num)`:\n\n*This line adds the current number `num` to the set that corresponds to the ***3x3*** sub-box where the current cell is located.*\n\n*Continuing from the previous analogy, let\'s say you found that the number **"5"** isn\'t in the ***3x3*** box yet, so you want to add it there. You take your pen and add the ***"5"*** to the list of numbers you\'ve placed in that box. This line of code does the same thing in code. It adds the current number `num` to the set that represents the numbers placed in that specific ***3x3*** sub-box.*\n\n***In both cases, these lines help ensure that you\'re following the rules of Sudoku by keeping track of the numbers in rows, columns, and sub-boxes, making sure no number repeats within the same row, column, or sub-box.***\n\n***END***\n\n\n*It took a lot of time and effort to write this documentation, but I will be really happy if it becomes useful to someone!* \n\n\n\n
3,433
Valid Sudoku
valid-sudoku
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Note:
Array,Hash Table,Matrix
Medium
null
51,132
312
**Idea**\n\nJust go through all you see (like "7 in row 3") and check for duplicates.\n\n**Solution 1**\n\nUsing `Counter`. One logical line, seven physical lines.\n\n def isValidSudoku(self, board):\n return 1 == max(collections.Counter(\n x\n for i, row in enumerate(board)\n for j, c in enumerate(row)\n if c != '.'\n for x in ((c, i), (j, c), (i/3, j/3, c))\n ).values() + [1])\n\nThe ` + [1]` is only for the empty board, where `max` would get an empty list and complain. It's not necessary to get it accepted here, as the empty board isn't among the test cases, but it's good to have.\n\n**Solution 2**\n\nUsing `len(set)`.\n\n def isValidSudoku(self, board):\n seen = sum(([(c, i), (j, c), (i/3, j/3, c)]\n for i, row in enumerate(board)\n for j, c in enumerate(row)\n if c != '.'), [])\n return len(seen) == len(set(seen))\n\n**Solution 3**\n\nUsing `any`.\n\n def isValidSudoku(self, board):\n seen = set()\n return not any(x in seen or seen.add(x)\n for i, row in enumerate(board)\n for j, c in enumerate(row)\n if c != '.'\n for x in ((c, i), (j, c), (i/3, j/3, c)))\n\n**Solution 4**\n\nIterating a different way.\n\n def isValidSudoku(self, board):\n seen = sum(([(c, i), (j, c), (i/3, j/3, c)]\n for i in range(9) for j in range(9)\n for c in [board[i][j]] if c != '.'), [])\n return len(seen) == len(set(seen))
3,463
Valid Sudoku
valid-sudoku
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Note:
Array,Hash Table,Matrix
Medium
null
6,175
23
To solve this problem we have to check if each value in sudoku does not repeat in its:\n\n1. Row\n1. Column\n1. Block\n\n# Complexity\n- Time complexity: $$O(n*n)$$ \n where n is fiexed here.\n so, Time Complexity will be O(81) ==> O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n * n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def isValidSudoku(self, board: List[List[str]]) -> bool:\n rows = [set() for _ in range(9)]\n cols = [set() for _ in range(9)]\n block = [[set() for _ in range(3)] for _ in range(3)]\n\n for i in range(9):\n for j in range(9):\n curr = board[i][j]\n if curr == \'.\':\n continue\n if (curr in rows[i]) or (curr in cols[j]) or (curr in block[i // 3][j // 3]):\n return False\n rows[i].add(curr)\n cols[j].add(curr)\n block[i // 3][j // 3].add(curr)\n return True\n\n```
3,476
Valid Sudoku
valid-sudoku
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Note:
Array,Hash Table,Matrix
Medium
null
8,969
78
Just store the indexs of the numbers in a dictionary in `(x, y)` format. Then for every number check for same row, same col and same box condition.\nThis will require a single traversal. The same box condition can be checked using `pos[0]//3 == x//3 and pos[1]//3 == y//3` since `i//3` and `j//3` give the box position.\n\n```\nclass Solution:\n def isValidSudoku(self, board: List[List[str]]) -> bool:\n boardMap = collections.defaultdict(list)\n for x in range(9):\n for y in range(9):\n char = board[x][y]\n if char != \'.\': \n if char in boardMap:\n for pos in boardMap[char]:\n if (pos[0]== x) or (pos[1] == y) or (pos[0]//3 == x//3 and pos[1]//3 == y//3):\n return False\n boardMap[char].append((x,y))\n \n return True\n```
3,499
Sudoku Solver
sudoku-solver
Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: The '.' character indicates empty cells.
Array,Backtracking,Matrix
Hard
null
340
6
# 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```\nfrom typing import List\n\nclass Solution:\n def solveSudoku(self, board: List[List[str]]) -> None:\n """\n Solves the Sudoku puzzle in-place.\n\n Parameters:\n board (List[List[str]]): 9x9 Sudoku board represented as a list of lists.\n """\n n = 9\n\n def isValid(row, col, num):\n for i in range(n):\n if board[i][col] == num or board[row][i] == num or board[3 * (row // 3) + i // 3][3 * (col // 3) + i % 3] == num:\n return False\n return True\n\n def solve(row, col):\n if row == n:\n return True\n if col == n:\n return solve(row + 1, 0)\n\n if board[row][col] == ".":\n for num in map(str, range(1, 10)):\n if isValid(row, col, num):\n board[row][col] = num\n if solve(row, col + 1):\n return True\n else:\n board[row][col] = "."\n return False\n else:\n return solve(row, col + 1)\n\n solve(0, 0)\n##Upvote me If it helps please\n\n```
3,503
Sudoku Solver
sudoku-solver
Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: The '.' character indicates empty cells.
Array,Backtracking,Matrix
Hard
null
8,662
73
```\nclass Solution:\n def solveSudoku(self, board: List[List[str]]) -> None:\n n = 9\n \n \n def isValid(row, col, ch):\n row, col = int(row), int(col)\n \n for i in range(9):\n \n if board[i][col] == ch:\n return False\n if board[row][i] == ch:\n return False\n \n if board[3*(row//3) + i//3][3*(col//3) + i%3] == ch:\n return False\n \n return True\n \n def solve(row, col):\n if row == n:\n return True\n if col == n:\n return solve(row+1, 0)\n \n if board[row][col] == ".":\n for i in range(1, 10):\n if isValid(row, col, str(i)):\n board[row][col] = str(i)\n \n if solve(row, col + 1):\n return True\n else:\n board[row][col] = "."\n return False\n else:\n return solve(row, col + 1)\n \n \n \n solve(0, 0)\n\t\t\n\t\t#do upvote if it helps.
3,526
Sudoku Solver
sudoku-solver
Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: The '.' character indicates empty cells.
Array,Backtracking,Matrix
Hard
null
1,048
8
# Backtracking\n```\nclass Solution:\n def solveSudoku(self, grid: List[List[str]]) -> None:\n return self.solve(grid)\n def solve(self,grid):\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j]==".":\n for c in range(1,len(grid)+1):\n c=str(c)\n if self.isvalid(i,j,c,grid):\n grid[i][j]=c\n if self.solve(grid)==True:\n return True\n else:\n grid[i][j]="."\n return False\n return True\n def isvalid(self,row,col,c,grid):\n for i in range(len(grid)):\n if grid[row][i]==c:\n return False\n if grid[i][col]==c:\n return False\n if grid[(3*(row//3)+i//3)][3*(col//3)+i%3]==c:\n return False\n return True\n```\n# please upvote me it would encourage me alot\n
3,546
Sudoku Solver
sudoku-solver
Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: The '.' character indicates empty cells.
Array,Backtracking,Matrix
Hard
null
1,449
6
```C++ []\nclass Solution {\npublic:\n bool isValid(vector<vector<char>> &board, int row, int col, char c) {\n for (int i = 0; i < 9; i++) {\n if (board[i][col] == c)\n return false;\n if (board[row][i] == c)\n return false;\n if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c)\n return false;\n }\n return true;\n }\n\n bool solve(vector<vector<char>> &board) {\n for (int i = 0; i < board.size(); i++) {\n for (int j = 0; j < board[0].size(); j++) {\n if (board[i][j] == \'.\') {\n for (char c = \'1\'; c <= \'9\'; c++) {\n if (isValid(board, i, j, c)) {\n board[i][j] = c;\n if (solve(board))\n return true;\n else\n board[i][j] = \'.\';\n }\n }\n return false;\n }\n }\n }\n return true;\n }\n \n void solveSudoku(vector<vector<char>> &board) {\n solve(board);\n }\n};\n\n```\n```JAVA []\nclass Solution {\n\n public boolean isValid(char[][] board, int row, int col, char c) {\n for (int i = 0; i < 9; i++) {\n if (board[i][col] == c) return false;\n if (board[row][i] == c) return false;\n if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) return false;\n }\n return true;\n }\n\n public boolean solve(char[][] board) {\n for (int i = 0; i < 9; i++) {\n for (int j = 0; j < 9; j++) {\n if (board[i][j] == \'.\') {\n for (char c = \'1\'; c <= \'9\'; c++) {\n if (isValid(board, i, j, c)) {\n board[i][j] = c;\n if (solve(board)) return true;\n else board[i][j] = \'.\';\n }\n }\n return false;\n }\n }\n }\n return true;\n }\n\n public void solveSudoku(char[][] board) {\n solve(board);\n }\n}\n\n```\n```Python []\nclass Solution:\n def solveSudoku(self, board: List[List[str]]) -> None:\n def isValid(board, row, col, c):\n for i in range(9):\n if board[i][col] == c:\n return False\n if board[row][i] == c:\n return False\n row_index = 3 * (row // 3) + i // 3\n col_index = 3 * (col // 3) + i % 3\n if board[row_index][col_index] == c:\n return False\n return True\n\n def solve(board):\n for row in range(9):\n for col in range(9):\n if board[row][col] == ".":\n for c in range(1, 10):\n if isValid(board, row, col, chr(c + ord("0"))):\n board[row][col] = chr(c + ord("0"))\n if solve(board):\n return True\n else:\n board[row][col] = "."\n return False\n return True\n\n solve(board)\n\n\n\n```\n
3,555
Sudoku Solver
sudoku-solver
Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: The '.' character indicates empty cells.
Array,Backtracking,Matrix
Hard
null
6,406
68
```\nclass Solution:\n def solveSudoku(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n """\n assert(self.backtrack(board, 0, 0))\n return\n \n def backtrack(self, board: List[List[str]], r: int, c: int) -> bool:\n # Go to next empty space\n while board[r][c] != \'.\':\n c += 1\n if c == 9: c, r = 0, r+1\n if r == 9: return True\n # Try all options, backtracking if not work\n for k in range(1, 10):\n if self.isValidSudokuMove(board, r, c, str(k)):\n board[r][c] = str(k)\n if self.backtrack(board, r, c):\n return True\n board[r][c] = \'.\'\n return False\n \n def isValidSudokuMove(self, board: List[List[str]], r: int, c: int, cand: int) -> bool:\n # Check row\n if any(board[r][j] == cand for j in range(9)): return False\n # Check col\n if any(board[i][c] == cand for i in range(9)): return False\n # Check block\n br, bc = 3*(r//3), 3*(c//3)\n if any(board[i][j] == cand for i in range(br, br+3) for j in range(bc, bc+3)): return False\n return True\n```
3,586
Sudoku Solver
sudoku-solver
Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: The '.' character indicates empty cells.
Array,Backtracking,Matrix
Hard
null
2,376
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe easiest Method is just trial and error. We do this by finding and empty cell and checking which numbers are available for this cell. Then we input these numbers one by one and traverse deeper continuing this approach recursively until we meet one of the following two cases:\n\n1) The grid does not contain empty cells anymore. This means we found a valid solution.\n2) We have an empty cell, but there are no available numbers any more.\n\nIn case of 2) we need to backtrack through the recursion and undo the changes we made to the grid.\n\nWe could make this a little fast by starting from position whith the least available numbers.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn my approach I tried to keep it readable by splitting the work into small and independent functions.\n\nThey are named in a readable manner, so I think one can see the purpose of each of the functions.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime complexity is O(N*M) but I\'m not entirely sure about this one, so I stand corrected.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space is taken by the recursion stack which is O(N*M) in the worst case.\n\n# Code\n```Python\nclass Solution:\n\n # make a set of possible characters\n possible = set(str(nr) for nr in range(1,10))\n\n def solveSudoku(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n """\n \n # save the board\n self.board = board\n self.dfs()\n \n def dfs(self):\n\n # find the next empty cell\n rx, cx, complete = self.findEmpty()\n\n # check whether there are empty cells\n if complete:\n return True\n \n # get the available numbers\n available = self.getPossible(rx, cx)\n\n # check whether we have available numbers\n if not available:\n return False\n \n # go through available numbers and try them\n for number in available:\n\n # set the number\n self.board[rx][cx] = number\n\n # check whether it works\n if self.dfs():\n return True\n \n # reset the number\n self.board[rx][cx] = "."\n \n return False\n\n def findEmpty(self):\n # find the next free position and if all are filled we can return True\n for rx in range(len(self.board)):\n for cx in range(len(self.board[0])):\n if self.board[rx][cx] == \'.\':\n return rx, cx, False\n return -1, -1, True\n\n def getPossible(self, rx, cx):\n return self.possible - self.getBox(rx, cx) - self.getRow(rx, cx) - self.getCol(rx, cx)\n\n def getRow(self, rx, cx):\n return set(self.board[rx])\n\n def getCol(self, rx, cx):\n return set([row[cx] for row in self.board])\n\n def getBox(self, rx, cx):\n result = set()\n for rx in range(rx // 3 * 3, rx // 3 * 3 + 3):\n result.update(self.board[rx][cx // 3 * 3:cx // 3 * 3 + 3])\n return result\n \n```
3,589
Sudoku Solver
sudoku-solver
Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: The '.' character indicates empty cells.
Array,Backtracking,Matrix
Hard
null
3,985
33
## IDEA:\n*The simple idea here is to fill a position and take the updated board as the new board and check if this new board has a possible solution.\nIf there is no valid solution for our new board we revert back to our previous state of the board and try by filling the next possible solution.*\n\nChecking if a value is valid in the respective empty slot:\nBefore intialising a value to our empty spot we need to check if that value is valid at that spot. For that we should check three cases:\n1) If value is already present in the row\n2) If value is already presnt in the column\n3) If value is already presnt in the smaller(3*3)box .(This is a bit tricky)\n\n****\nFeel free to ask and get your answer within 24hrs if you have any doubts. \uD83E\uDD16\n**Upvote** if you got any help !! \uD83E\uDD1E\n****\n\n\'\'\'\n\n\tfrom collections import defaultdict,deque\n\tclass Solution:\n\t\tdef solveSudoku(self, board: List[List[str]]) -> None:\n \n rows,cols,block,seen = defaultdict(set),defaultdict(set),defaultdict(set),deque([])\n for i in range(9):\n for j in range(9):\n if board[i][j]!=".":\n rows[i].add(board[i][j])\n cols[j].add(board[i][j])\n block[(i//3,j//3)].add(board[i][j])\n else:\n seen.append((i,j))\n \n def dfs():\n if not seen:\n return True\n \n r,c = seen[0]\n t = (r//3,c//3)\n for n in {\'1\',\'2\',\'3\',\'4\',\'5\',\'6\',\'7\',\'8\',\'9\'}:\n if n not in rows[r] and n not in cols[c] and n not in block[t]:\n board[r][c]=n\n rows[r].add(n)\n cols[c].add(n)\n block[t].add(n)\n seen.popleft()\n if dfs():\n return True\n else:\n board[r][c]="."\n rows[r].discard(n)\n cols[c].discard(n)\n block[t].discard(n)\n seen.appendleft((r,c))\n return False\n \n dfs()\n\n### Thanks \uD83E\uDD17
3,595
Sudoku Solver
sudoku-solver
Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: The '.' character indicates empty cells.
Array,Backtracking,Matrix
Hard
null
3,791
8
(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\nThe best result for the code below is ***0ms / 38.2MB*** (beats 92.04% / 24.00%).\n* *** Java ***\n\n```\n\nclass Solution {\n private static final char EMPTY_ENTRY = \'.\';\n\n/*\n Driver function to kick off the recursion\n*/\npublic static boolean solveSudoku(char[][] board){\n return solveSudokuCell(0, 0, board);\n}\n\n/*\n This function chooses a placement for the cell at (row, col)\n and continues solving based on the rules we define.\n \n Our strategy:\n We will start at row 0.\n We will solve every column in that row.\n When we reach the last column we move to the next row.\n If this is past the last row (row == board.length) we are done.\n The whole board has been solved.\n*/\nprivate static boolean solveSudokuCell(int row, int col, char[][] board) {\n\n /*\n Have we finished placements in all columns for\n the row we are working on?\n */\n if (col == board[row].length){\n\n /*\n Yes. Reset to col 0 and advance the row by 1.\n We will work on the next row.\n */\n col = 0;\n row++;\n\n /*\n Have we completed placements in all rows? If so then we are done.\n If not, drop through to the logic below and keep solving things.\n */\n if (row == board.length){\n return true; // Entire board has been filled without conflict.\n }\n\n }\n\n // Skip non-empty entries. They already have a value in them.\n if (board[row][col] != EMPTY_ENTRY) {\n return solveSudokuCell(row, col + 1, board);\n }\n\n /*\n Try all values 1 through 9 in the cell at (row, col).\n Recurse on the placement if it doesn\'t break the constraints of Sudoku.\n */\n for (int value = 1; value <= board.length; value++) {\n\n char charToPlace = (char) (value + \'0\'); // convert int value to char\n\n /*\n Apply constraints. We will only add the value to the cell if\n adding it won\'t cause us to break sudoku rules.\n */\n if (canPlaceValue(board, row, col, charToPlace)) {\n board[row][col] = charToPlace;\n if (solveSudokuCell(row, col + 1, board)) { // recurse with our VALID placement\n return true;\n }\n }\n\n }\n\n /*\n Undo assignment to this cell. No values worked in it meaning that\n previous states put us in a position we cannot solve from. Hence,\n we backtrack by returning "false" to our caller.\n */\n board[row][col] = EMPTY_ENTRY;\n return false; // No valid placement was found, this path is faulty, return false\n}\n\n/*\n Will the placement at (row, col) break the Sudoku properties?\n*/\nprivate static boolean canPlaceValue(char[][] board, int row, int col, char charToPlace) {\n\n // Check column constraint. For each row, we do a check on column "col".\n for (char[] element : board) {\n if (charToPlace == element[col]){\n return false;\n }\n }\n\n // Check row constraint. For each column in row "row", we do a check.\n for (int i = 0; i < board.length; i++) {\n if (charToPlace == board[row][i]) {\n return false;\n }\n }\n\n /*\n Check region constraints.\n \n In a 9 x 9 board, we will have 9 sub-boxes (3 rows of 3 sub-boxes).\n \n The "I" tells us that we are in the Ith sub-box row. (there are 3 sub-box rows)\n The "J" tells us that we are in the Jth sub-box column. (there are 3 sub-box columns)\n \n I tried to think of better variable names for like 20 minutes but couldn\'t so just left\n I and J.\n \n Integer properties will truncate the decimal place so we just know the sub-box number we are in.\n Each coordinate we touch will be found by an offset from topLeftOfSubBoxRow and topLeftOfSubBoxCol.\n */\n int regionSize = (int) Math.sqrt(board.length); // gives us the size of a sub-box\n\n int I = row / regionSize;\n int J = col / regionSize;\n\n /*\n This multiplication takes us to the EXACT top left of the sub-box. We keep the (row, col)\n of these values because it is important. It lets us traverse the sub-box with our double for loop.\n */\n int topLeftOfSubBoxRow = regionSize * I; // the row of the top left of the block\n int topLeftOfSubBoxCol = regionSize * J; // the column of the tol left of the block\n\n for (int i = 0; i < regionSize; i++) {\n for (int j = 0; j < regionSize; j++) {\n\n /*\n i and j just define our offsets from topLeftOfBlockRow\n and topLeftOfBlockCol respectively\n */\n if (charToPlace == board[topLeftOfSubBoxRow + i][topLeftOfSubBoxCol + j]) {\n return false;\n }\n\n }\n }\n\n return true; // placement is valid\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***\n
3,599
Count and Say
count-and-say
The count-and-say sequence is a sequence of digit strings defined by the recursive formula: To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying. For example, the saying and conversion for digit string "3322251": Given a positive integer n, return the nth term of the count-and-say sequence.
String
Medium
The following are the terms from n=1 to n=10 of the count-and-say sequence: 1. 1 2. 11 3. 21 4. 1211 5. 111221 6. 312211 7. 13112221 8. 1113213211 9. 31131211131221 10. 13211311123113112211 To generate the nth term, just count and say the n-1th term.
74,196
259
**Solution 1** ... using a regular expression\n\n def countAndSay(self, n):\n s = '1'\n for _ in range(n - 1):\n s = re.sub(r'(.)\\1*', lambda m: str(len(m.group(0))) + m.group(1), s)\n return s\n\n---\n\n**Solution 2** ... using a regular expression\n\n def countAndSay(self, n):\n s = '1'\n for _ in range(n - 1):\n s = ''.join(str(len(group)) + digit\n for group, digit in re.findall(r'((.)\\2*)', s))\n return s\n\n---\n\n**Solution 3** ... using `groupby`\n\n def countAndSay(self, n):\n s = '1'\n for _ in range(n - 1):\n s = ''.join(str(len(list(group))) + digit\n for digit, group in itertools.groupby(s))\n return s
3,648
Count and Say
count-and-say
The count-and-say sequence is a sequence of digit strings defined by the recursive formula: To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying. For example, the saying and conversion for digit string "3322251": Given a positive integer n, return the nth term of the count-and-say sequence.
String
Medium
The following are the terms from n=1 to n=10 of the count-and-say sequence: 1. 1 2. 11 3. 21 4. 1211 5. 111221 6. 312211 7. 13112221 8. 1113213211 9. 31131211131221 10. 13211311123113112211 To generate the nth term, just count and say the n-1th term.
6,814
24
```\nclass Solution:\n def countAndSay(self, n: int) -> str:\n if n==1:\n return "1"\n x=self.countAndSay(n-1)\n s=""\n y=x[0]\n ct=1\n for i in range(1,len(x)):\n if x[i]==y:\n ct+=1\n else:\n s+=str(ct)\n s+=str(y)\n y=x[i]\n ct=1\n s+=str(ct)\n s+=str(y)\n return s\n```
3,665
Count and Say
count-and-say
The count-and-say sequence is a sequence of digit strings defined by the recursive formula: To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying. For example, the saying and conversion for digit string "3322251": Given a positive integer n, return the nth term of the count-and-say sequence.
String
Medium
The following are the terms from n=1 to n=10 of the count-and-say sequence: 1. 1 2. 11 3. 21 4. 1211 5. 111221 6. 312211 7. 13112221 8. 1113213211 9. 31131211131221 10. 13211311123113112211 To generate the nth term, just count and say the n-1th term.
2,963
22
```\nclass Solution:\n def countAndSay(self, n: int) -> str:\n if(n==1):\n return("1")\n x=self.countAndSay(n-1)\n i=0\n s=""\n while(i<len(x)):\n ch=x[i]\n ns=0\n while(i<len(x) and x[i]==ch):\n ns+=1\n i+=1\n s+=str(ns)\n s+=ch\n return(s)\n```
3,667