title stringlengths 1 100 | titleSlug stringlengths 3 77 | Java int64 0 1 | Python3 int64 1 1 | content stringlengths 28 44.4k | voteCount int64 0 3.67k | question_content stringlengths 65 5k | question_hints stringclasses 970
values |
|---|---|---|---|---|---|---|---|
One liner Python Solution | number-of-segments-in-a-string | 0 | 1 | # Intuition\n\nThe purpose of this method is to count the number of segments in a given string `s`, where a "segment" is defined as a continuous sequence of non-space characters. The method achieves this by utilizing the `split()` function on the input string `s`, which splits the string into a list of substrings based... | 0 | Given a string `s`, return _the number of segments in the string_.
A **segment** is defined to be a contiguous sequence of **non-space characters**.
**Example 1:**
**Input:** s = "Hello, my name is John "
**Output:** 5
**Explanation:** The five segments are \[ "Hello, ", "my ", "name ", "is ", "John "\]
**Exam... | null |
simple one line code | beats 70% | number-of-segments-in-a-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nreturn the number of the words in a string. They are separated by empty spaces\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.convert the string into list and find its lenght\n# Complexity\n- Time complexity:\n<!-... | 0 | Given a string `s`, return _the number of segments in the string_.
A **segment** is defined to be a contiguous sequence of **non-space characters**.
**Example 1:**
**Input:** s = "Hello, my name is John "
**Output:** 5
**Explanation:** The five segments are \[ "Hello, ", "my ", "name ", "is ", "John "\]
**Exam... | null |
Simple Python solution | non-overlapping-intervals | 0 | 1 | \n# Code\n```\nclass Solution:\n def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:\n cnt = 0\n inn = sorted(intervals, key=lambda x: x[0], reverse=True)\n ans = [inn[0]]\n for s, e in inn[1:]:\n if ans[-1][0] >= e: \n ans.append([s, e])\n ... | 3 | Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed ... | null |
One-line solution | non-overlapping-intervals | 0 | 1 | Very simple one line solution:\n\n# Code\n```\nclass Solution:\n def eraseOverlapIntervals(self, intervals: List[List[int]], pointer=-inf, answer=0) -> int:\n return answer \\\n if not intervals \\\n else self.eraseOverlapIntervals(sorted(intervals, key=lambda x: x[1])[1:], sorted(interv... | 1 | Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed ... | null |
Easy Python Solution 99% pass | non-overlapping-intervals | 0 | 1 | \n# Code\n```\nclass Solution:\n def eraseOverlapIntervals(self, points: List[List[int]]) -> int:\n ans = 0\n arrow = -math.inf\n\n for point in sorted(points, key = lambda x:x[1]):\n if(point[0] >= arrow):\n arrow = point[1]\n else:\n ans+=1\n... | 1 | Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed ... | null |
Python | Easy to Understand | Medium Problem | 435. Non-overlapping Intervals | non-overlapping-intervals | 0 | 1 | # Python | Easy to Understand | Medium Problem | 435. Non-overlapping Intervals\n```\nclass Solution:\n def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:\n intervals.sort()\n @cache\n def dfs(idx):\n if idx==len(intervals):\n return 0\n\n ta... | 1 | Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed ... | null |
✅Beat's 100% || C++ || JAVA || PYTHON || Beginner Friendly🔥🔥🔥 | non-overlapping-intervals | 1 | 1 | # Intuition:\n1. Minimum number of intervals to remove .\n2. Which is nothing but maximum number of intervals we can should keep.\n3. Then it comes under Maximum Meeting we can attend.\n\n<details>\n<summary><strong>In Detail</strong></summary>\n\n1. Removing minimum number of intervals is the same as KEEPING maximum n... | 133 | Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed ... | null |
✅Python3 || C++|| Java✅[Greedy,Sorting and DP] Easy and understand | non-overlapping-intervals | 1 | 1 | 1. `intervals = sorted(intervals, key = lambda x:x[1])`: This line sorts the intervals list of lists based on the second element of each `interval`. It uses the `sorted` function with a custom sorting key specified by the lambda function `lambda x: x[1]`, which means sorting based on the second element of the sublists ... | 32 | Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed ... | null |
Fast solution | C++ | Java | Python | non-overlapping-intervals | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nif we sort according to end time we can do max activity.\n\nFor detailed explanation you can refer to my youtube channel (hindi Language)\nhttps://youtu.be/Uuq0eJKwMzk\n or link in my profile.Here,you can find any solution in playlists mo... | 34 | Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed ... | null |
Ex-Amazon explains a solution with a video, Python, JavaScript, Java and C++ | non-overlapping-intervals | 1 | 1 | # Intuition\nThe algorithm sorts intervals based on their end points, then iterates through them, counting overlapping intervals, and returns the count.\n\n# Solution Video\n\nhttps://youtu.be/gJjmZ6VpXRk\n\n# *** Please upvote and subscribe to my channel from here. I have 226 videos as of July 19th***\nhttp://www.yout... | 6 | Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed ... | null |
Python 3 Easy Solution | non-overlapping-intervals | 0 | 1 | \n# Complexity\n- Time complexity: **O(nlogn)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(1)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n \n\n# Code\n```\nclass Solution:\n def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:\n intervals.s... | 1 | Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed ... | null |
Python sort + greedy solution | non-overlapping-intervals | 0 | 1 | # Approach\nSort -> greedy\n\n\n# Complexity\n- Time complexity: $$O(n*\\log n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: (x[0], x[1]))\n prev_end = float("-inf")\n counte... | 1 | Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed ... | null |
Python Solution (✅Greedy) | O(nlogn) | non-overlapping-intervals | 0 | 1 | ## Intuition\nThe problem requires finding the minimum number of intervals that need to be removed to avoid overlaps. Sorting the intervals by their end times provides an efficient way to handle this problem. By iterating through the sorted intervals, we can check if the start time of the current interval is greater th... | 2 | Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed ... | null |
Easy Solution with explanation | Python 3 | non-overlapping-intervals | 0 | 1 | # Algorithm\n- Sort intervals array\n- create a default pointer for pe for storing end of previous interval \n- create a variable for storing result\n- loop over sorted intervals array and check if end >= pe\n - if condition is true then update pe pointer with current end\n - else update result with +1\n- return ... | 2 | Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed ... | null |
Python Simple O(NLogN) | non-overlapping-intervals | 0 | 1 | # 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)$$ --... | 0 | Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed ... | null |
Python3 Sort+DP | non-overlapping-intervals | 0 | 1 | # Intuition\n- Sort the intervals first\n- There are two choices in each idx: remove it or keep it.\n- Remove it: add count 1 and move to next index\n- Keep it: should find the next valid index, count the number of skipping indices\n * Use binary search to find the next first element which start is larger than the c... | 1 | Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed ... | null |
FULL Explanation Of Everything | find-right-interval | 0 | 1 | \n## Question\n```\nintervals = [[3,4],[2,3],[1,2]]\nNote : Here each value is a \'list\'.\n\nFor x = [3,4] : \nIs there any value/list whose first value ([f,_]) is EQUAL OR GREATER THAN x[1] (4) ? \n No! "-1"\nFor x = [2,3] : Say y = [3,4], so for x[1] (3), y[0] is >= x[1].\n So answer is t... | 10 | You are given an array of `intervals`, where `intervals[i] = [starti, endi]` and each `starti` is **unique**.
The **right interval** for an interval `i` is an interval `j` such that `startj >= endi` and `startj` is **minimized**. Note that `i` may equal `j`.
Return _an array of **right interval** indices for each int... | null |
436: Solution with step by step explanation | find-right-interval | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Create a dictionary called start_points to store the start points of intervals and their corresponding indices. Initialize it to an empty dictionary.\n2. Iterate over the list of intervals using enumerate. For each interv... | 6 | You are given an array of `intervals`, where `intervals[i] = [starti, endi]` and each `starti` is **unique**.
The **right interval** for an interval `i` is an interval `j` such that `startj >= endi` and `startj` is **minimized**. Note that `i` may equal `j`.
Return _an array of **right interval** indices for each int... | null |
Python sort, binary search and hashmap | find-right-interval | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA variant of LeetCode 744.\n# Approach\n1. The start of each interval is unique, so create a hashmap to map the start of each interval to the index of each interval in intervals.\n2. Sort the list of intervals.\n3. Similar to LeetCode 744... | 1 | You are given an array of `intervals`, where `intervals[i] = [starti, endi]` and each `starti` is **unique**.
The **right interval** for an interval `i` is an interval `j` such that `startj >= endi` and `startj` is **minimized**. Note that `i` may equal `j`.
Return _an array of **right interval** indices for each int... | null |
sorted + bin search NlogN | find-right-interval | 0 | 1 | # 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: $NlogN$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O... | 0 | You are given an array of `intervals`, where `intervals[i] = [starti, endi]` and each `starti` is **unique**.
The **right interval** for an interval `i` is an interval `j` such that `startj >= endi` and `startj` is **minimized**. Note that `i` may equal `j`.
Return _an array of **right interval** indices for each int... | null |
Python Dictionary + Binary Search | find-right-interval | 0 | 1 | # Complexity\n- Time complexity:\nO(NlogN)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def findRightInterval(self, arr: List[List[int]]) -> List[int]:\n f=float(\'-inf\')\n d,n,l={f:-1},len(arr),[i[0] for i in arr]\n l.sort()\n for i in range(n):\n d[arr[i][0... | 0 | You are given an array of `intervals`, where `intervals[i] = [starti, endi]` and each `starti` is **unique**.
The **right interval** for an interval `i` is an interval `j` such that `startj >= endi` and `startj` is **minimized**. Note that `i` may equal `j`.
Return _an array of **right interval** indices for each int... | null |
✅Easiest of all Solution for beginners using bisect✅ | find-right-interval | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nYou require reasoning to understand why this???\nans.append(start.index(start_sorted[index]))\n\nIf you have any doubts fell free to comment.\n\n# Complexity\n- Time c... | 0 | You are given an array of `intervals`, where `intervals[i] = [starti, endi]` and each `starti` is **unique**.
The **right interval** for an interval `i` is an interval `j` such that `startj >= endi` and `startj` is **minimized**. Note that `i` may equal `j`.
Return _an array of **right interval** indices for each int... | null |
Tedha hai par mera hai | find-right-interval | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIski complexity O(nlogn) se kam nahi hogi chahe jo kar lo apana ne saab tarah se implement karke dekh liya.\nApna funda sidha tha but question thoda tedah tha, sort karna padha phir binary search lagana pada phir jake hua ye question.\n\n... | 0 | You are given an array of `intervals`, where `intervals[i] = [starti, endi]` and each `starti` is **unique**.
The **right interval** for an interval `i` is an interval `j` such that `startj >= endi` and `startj` is **minimized**. Note that `i` may equal `j`.
Return _an array of **right interval** indices for each int... | null |
Iterative O(N) Python Solution | path-sum-iii | 0 | 1 | # Intuition\n\nThe key to a linear solution is the realization that...\n\n**If at a given node, the sum of all the nodes from the current node to root subtracted by k is equal to a sum to the root that was observed previously on this path, then there are paths that sum to k equal to the number of times `sumToRoot - k` ... | 2 | Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
**Example 1:**
**In... | null |
437: Space 93.92%, Solution with step by step explanation | path-sum-iii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define the function with the given input parameters: a binary tree root node and an integer targetSum. The function should return an integer representing the number of paths in the tree that sum to the targetSum.\n\n2. Cr... | 12 | Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
**Example 1:**
**In... | null |
[Python] One-pass DFS, faster than 99% | path-sum-iii | 0 | 1 | Please feel free to give suggestions or ask questions. **Upvote** if you like the solution.\nO(h) space if we delete zero-valued items from sums.\n\n**Idea**: Maintain prefix sums while doing dfs from root to leaf. If currentSum-prefixSum=targetSum, then we\'ve found a path that has a value of target. If we encountered... | 33 | Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
**Example 1:**
**In... | null |
[ Python ] | Simple & Clean Solution | path-sum-iii | 0 | 1 | # Code\n```\nclass Solution:\n def pathSum(self, root: Optional[TreeNode], k: int) -> int:\n def helper(root, currSum):\n if not root: return \n \n nonlocal paths\n\n currSum += root.val\n if m[currSum - k] != 0:\n paths += m[currSum - k]\n... | 4 | Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
**Example 1:**
**In... | null |
Python DFS Recursive Solution | path-sum-iii | 0 | 1 | ```\nclass Solution:\n cnt = 0\n def pathSum(self, root: TreeNode, sum: int) -> int:\n def dfs(root, start, s):\n if not root:\n return\n s -= root.val \n if s==0:\n self.cnt+=1\n dfs(root.left,False, s)\n dfs(root.right,F... | 34 | Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
**Example 1:**
**In... | null |
Easy python solution | BFS | Recursion | path-sum-iii | 0 | 1 | # Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\n# 1. accu from root\n# 2. then accu from root.left adn root.right \nclass Solution:\n def pathSum(self,... | 2 | Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
**Example 1:**
**In... | null |
Python Solution | path-sum-iii | 0 | 1 | What I found helps with this problem is to have two recursive functions:\n- `dfs` simply recurses through each node of the tree\n- `find_path_from_node` tries to find paths starting from the given node\n\nI ran into problems when I tried to merge these functions into one. A lesson for me is to split up recursive functi... | 20 | Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
**Example 1:**
**In... | null |
✔️ [Python3] SLIDING WINDOW + HASH TABLE, Explained | find-all-anagrams-in-a-string | 0 | 1 | **UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nFirst, we have to create a hash map with letters from `p` as keys and its frequencies as values. Then, we start sliding the window `[0..len(s)]` over the `s`. Every time a letter gets out of the window, we increase t... | 168 | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
*... | null |
✔️ Python3 easy solution 116ms🔥🔥🔥| Explained in Detailed | find-all-anagrams-in-a-string | 0 | 1 | # Approach\n\n<!-- Describe your approach to solving the problem. -->\n- make $$hashmap(dictionary)$$ of $$string(p)$$ and frequency of characters in it.\n- iterate over $$length$$ of $$string(s)$$.\n- $$... | 6 | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
*... | null |
Python short and clean. Optimised Sliding-Window. | find-all-anagrams-in-a-string | 0 | 1 | # Approach\nSame as [567. Permutation in String](https://leetcode.com/problems/permutation-in-string/solutions/3142159/python-short-and-clean-optimised-sliding-window/).\n\nInstead of returning `True` after finding the first anagram, store the start index and continue finding the next.\n\n# Complexity\n- Time complexit... | 2 | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
*... | null |
python3 Easy to understand | find-all-anagrams-in-a-string | 0 | 1 | # Intuition\n- Base case -If length of string s is smaller than p, return empty list.\n- Count the number of occurrences of characters in string p.\n- Search string s in chunks of length p, counting the occurrences of characters in each chunk.\n- Add the starting index of the chunk to the result list if the character c... | 3 | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
*... | null |
O(N) sliding window | find-all-anagrams-in-a-string | 0 | 1 | # Code\n```\nclass Solution:\n def findAnagrams(self, s: str, p: str) -> List[int]:\n if len(s) < len(p):\n return []\n \n need = Counter(p)\n cur, lo = 0, 0\n ret = []\n\n for i, c in enumerate(s):\n need[c] -= 1\n cur += 1\n whil... | 3 | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
*... | null |
easy & simple sliding window with freq. cnt beats 85% | find-all-anagrams-in-a-string | 0 | 1 | # Sliding Window\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```\nclass Solution:\n def findAnagrams(self, s: str, p: str) -> List[int]:\n s1_len = len(s)\... | 2 | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
*... | null |
Easy Approach | Sorting | Sliding Window | O(n) | Complete | find-all-anagrams-in-a-string | 0 | 1 | \n# Approach\nhere I have used sliding window approach for checking each word and sorting for anagram checking. The solution is simple but not optimal one.\n# Complexity\n- Time complexity:\no(n)\n\n- Space complexity:\no(n)\n\n\n\nplease upvote if you like\n\n\n# Code\n```\nclass Solution:\n def findAnagrams(self, ... | 10 | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
*... | null |
Sliding window technquie ... | find-all-anagrams-in-a-string | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nWe use sliding window approach for this the window size is fixed as the second string and just add the element to the window and just remove the character from the starting and just add the index of the removed character...\n\ns1="abcdefcba"\ns2="abc"... | 1 | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
*... | null |
📌📌Python3 || ⚡82 ms, faster than 99.35% of Python3 | find-all-anagrams-in-a-string | 0 | 1 | \n```\ndef findAnagrams(self, s: str, p: str) -> List[int]:\n LS, LP, S, P, A = len(s), len(p), 0, 0, []\n if LP > LS: \n return []\n for i in range(LP): S, P = S + hash(s[i]), P... | 15 | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
*... | null |
Real O(n+m) solution independent of vocabulary size | find-all-anagrams-in-a-string | 0 | 1 | # **Intuition**\n<!-- Describe your first thoughts on how to solve this problem. -->\nOur task is to find all the start indices of **p**\'s anagrams in **s**.\n```\nm = len(p)\nn = len(s)\nk = len(alphabet)\n```\nThe baseline is: \n- store the counts of **p**\'s letters in a dictionary or array\n- go over **s** with a ... | 2 | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
*... | null |
Solution | k-th-smallest-in-lexicographical-order | 1 | 1 | ```C++ []\nclass Solution {\n public:\n int findKthNumber(long n, int k) {\n auto getGap = [&n](long a, long b) {\n long gap = 0;\n while (a <= n) {\n gap += min(n + 1, b) - a;\n a *= 10;\n b *= 10;\n }\n return gap;\n };\n\n long currNum = 1;\n\n for (int i = 1; i ... | 207 | Given two integers `n` and `k`, return _the_ `kth` _lexicographically smallest integer in the range_ `[1, n]`.
**Example 1:**
**Input:** n = 13, k = 2
**Output:** 10
**Explanation:** The lexicographical order is \[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9\], so the second smallest number is 10.
**Example 2:**
**Inp... | null |
440: Space 96.85%, Solution with step by step explanation | k-th-smallest-in-lexicographical-order | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define a function named "findKthNumber" that takes in two parameters: "n" and "k". This function will return an integer, which is the kth lexicographically smallest integer in the range [1, n].\n\n2. Initialize a variable... | 2 | Given two integers `n` and `k`, return _the_ `kth` _lexicographically smallest integer in the range_ `[1, n]`.
**Example 1:**
**Input:** n = 13, k = 2
**Output:** 10
**Explanation:** The lexicographical order is \[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9\], so the second smallest number is 10.
**Example 2:**
**Inp... | null |
[Python3] traverse denary trie | k-th-smallest-in-lexicographical-order | 0 | 1 | \n```\nclass Solution:\n def findKthNumber(self, n: int, k: int) -> int:\n \n def fn(x): \n """Return node counts in denary trie."""\n ans, diff = 0, 1\n while x <= n: \n ans += min(n - x + 1, diff)\n x *= 10 \n diff *= 10 \n... | 7 | Given two integers `n` and `k`, return _the_ `kth` _lexicographically smallest integer in the range_ `[1, n]`.
**Example 1:**
**Input:** n = 13, k = 2
**Output:** 10
**Explanation:** The lexicographical order is \[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9\], so the second smallest number is 10.
**Example 2:**
**Inp... | null |
Python3 Explanation | k-th-smallest-in-lexicographical-order | 0 | 1 | # Intuition\nInitially, the problem seems like it could be solved by generating all the lexicographical permutations and then simply indexing the \\(k\\)th one. However, that approach is immediately dismissed because it would be impractical for large values of \\(n\\). A better intuition is to treat the problem as if n... | 0 | Given two integers `n` and `k`, return _the_ `kth` _lexicographically smallest integer in the range_ `[1, n]`.
**Example 1:**
**Input:** n = 13, k = 2
**Output:** 10
**Explanation:** The lexicographical order is \[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9\], so the second smallest number is 10.
**Example 2:**
**Inp... | null |
Solution to 440. K-th Smallest in Lexicographical Order | k-th-smallest-in-lexicographical-order | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves finding the k-th lexicographically smallest integer in the range [1, n]. Instead of generating the entire lexicographical order, the code efficiently explores the numbers in the order, incrementing the current value b... | 0 | Given two integers `n` and `k`, return _the_ `kth` _lexicographically smallest integer in the range_ `[1, n]`.
**Example 1:**
**Input:** n = 13, k = 2
**Output:** 10
**Explanation:** The lexicographical order is \[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9\], so the second smallest number is 10.
**Example 2:**
**Inp... | null |
Python3 | Explained | k-th-smallest-in-lexicographical-order | 0 | 1 | # Intuition\nThe lexicographical order of numbers can be thought of as a preorder traversal of a 10-ary tree (a tree where each node has up to 10 children). At the top level, we have numbers from 1 to 9 (we exclude 0 because numbers don\'t start with 0). Each of these numbers can be considered as the root of a subtree ... | 0 | Given two integers `n` and `k`, return _the_ `kth` _lexicographically smallest integer in the range_ `[1, n]`.
**Example 1:**
**Input:** n = 13, k = 2
**Output:** 10
**Explanation:** The lexicographical order is \[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9\], so the second smallest number is 10.
**Example 2:**
**Inp... | null |
Python3 beats 96% | k-th-smallest-in-lexicographical-order | 0 | 1 | \nOPT(dig) is given the substring \'dig\' how many substrings less than n start with that substring\n\n# Code\n```\nclass Solution:\n def findKthNumber(self, n: int, k: int) -> int:\n if k == 1:\n return 1\n nstr = str(n)\n\n @cache\n def opt(i, dig):\n if i == len(n... | 0 | Given two integers `n` and `k`, return _the_ `kth` _lexicographically smallest integer in the range_ `[1, n]`.
**Example 1:**
**Input:** n = 13, k = 2
**Output:** 10
**Explanation:** The lexicographical order is \[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9\], so the second smallest number is 10.
**Example 2:**
**Inp... | null |
DFS | k-th-smallest-in-lexicographical-order | 0 | 1 | # Code\n```\nclass Solution:\n def findKthNumber(self, n: int, k: int) -> int:\n def countPrefixes(prefix: int, n: int) -> int:\n count = 0\n curr = prefix\n next = prefix + 1\n\n while curr <= n:\n count += min(n + 1, next) - curr\n cu... | 0 | Given two integers `n` and `k`, return _the_ `kth` _lexicographically smallest integer in the range_ `[1, n]`.
**Example 1:**
**Input:** n = 13, k = 2
**Output:** 10
**Explanation:** The lexicographical order is \[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9\], so the second smallest number is 10.
**Example 2:**
**Inp... | null |
(Python) Kth Lexicographically Smallest Integer in Range | k-th-smallest-in-lexicographical-order | 0 | 1 | # Intuition\nWe can observe that the lexicographical order of the integers from 1 to n form a trie where the root is the empty string, and the children of a node represent the digits that can come after the digit sequence represented by the node. We can use this trie to find the kth lexicographically smallest integer b... | 0 | Given two integers `n` and `k`, return _the_ `kth` _lexicographically smallest integer in the range_ `[1, n]`.
**Example 1:**
**Input:** n = 13, k = 2
**Output:** 10
**Explanation:** The lexicographical order is \[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9\], so the second smallest number is 10.
**Example 2:**
**Inp... | null |
Fast Python solution. Beats 100% | k-th-smallest-in-lexicographical-order | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is asking to find the kth number in the lexicographic order of all the numbers from 1 to n. The idea is to use a combination of breadth-first search and dynamic programming to find the kth number in a fast and efficient manner... | 0 | Given two integers `n` and `k`, return _the_ `kth` _lexicographically smallest integer in the range_ `[1, n]`.
**Example 1:**
**Input:** n = 13, k = 2
**Output:** 10
**Explanation:** The lexicographical order is \[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9\], so the second smallest number is 10.
**Example 2:**
**Inp... | null |
Python | 100% Speed | BinCount Histogram Method | O( log(n)^2 ) | k-th-smallest-in-lexicographical-order | 0 | 1 | **Python | 100% Speed | BinCount Histogram Method | O( log(n)^2 )**\n\nThe Python code below corresponds to a highly efficient solution, which achieves a speed rating of 100% on LeetCode.\n\nHighlights:\n\n1. The code is inspired by the concept of "BinCount" Histograms, where we group numbers based on certain boundarie... | 3 | Given two integers `n` and `k`, return _the_ `kth` _lexicographically smallest integer in the range_ `[1, n]`.
**Example 1:**
**Input:** n = 13, k = 2
**Output:** 10
**Explanation:** The lexicographical order is \[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9\], so the second smallest number is 10.
**Example 2:**
**Inp... | null |
🐍 | | Binary Search | | Fastest | | Bisect Function | arranging-coins | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is the basic binary search problem.\n\n```First go trying brute force```: Number of coins that can fit in 1st row ,2nd row ...for nth row we need ```n*(n+1)/2``` coins in total. Check the value of it for each row and find when it is ... | 2 | You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the `ith` row has exactly `i` coins. The last row of the staircase **may be** incomplete.
Given the integer `n`, return _the number of **complete rows** of the staircase you will build_.
**Example 1:**
**I... | null |
Solution | arranging-coins | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int arrangeCoins(int n) {\n return (-1 + sqrt(1 + 8 * (long)n)) / 2;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def arrangeCoins(self, n: int) -> int:\n f = 1\n l = n\n\n while f<=l:\n mid = (f+l)//2\n temp = (mid*(m... | 3 | You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the `ith` row has exactly `i` coins. The last row of the staircase **may be** incomplete.
Given the integer `n`, return _the number of **complete rows** of the staircase you will build_.
**Example 1:**
**I... | null |
4 Lines of Code --->Binary Search and Normal For Loop Approach | arranging-coins | 0 | 1 | # 1. Using while Loop \n```\nclass Solution:\n def arrangeCoins(self, n: int) -> int: \n i=0\n while n>=0:\n i+=1\n n=n-i\n return i-1\n\n #please upvote me it would encourage me alot\n\n```\n# 2. using For Loop\n```\nclass Solution:\n def arrangeCoins(self, n: i... | 24 | You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the `ith` row has exactly `i` coins. The last row of the staircase **may be** incomplete.
Given the integer `n`, return _the number of **complete rows** of the staircase you will build_.
**Example 1:**
**I... | null |
[C++] [Python] Brute Force with Optimized Approach || Too Easy || Fully Explained | arranging-coins | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nSuppose we have the input value `n = 8`.\n\n1. Initialize `num` as 8 and `count` as 0.\n2. Start the outer loop with `i = 1`:\n - On the first iteration:\n - Start the inner loop with `j = 0`.\n - Since `j` is less than `i` and `num` (8) i... | 4 | You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the `ith` row has exactly `i` coins. The last row of the staircase **may be** incomplete.
Given the integer `n`, return _the number of **complete rows** of the staircase you will build_.
**Example 1:**
**I... | null |
441: Space 93.37%, Solution with step by step explanation | arranging-coins | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize two pointers left and right to 1 and n, respectively.\n2. While left <= right, compute the midpoint mid between left and right.\n3. Compute the total number of coins required to build mid complete rows using th... | 9 | You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the `ith` row has exactly `i` coins. The last row of the staircase **may be** incomplete.
Given the integer `n`, return _the number of **complete rows** of the staircase you will build_.
**Example 1:**
**I... | null |
By applying Quadratic equation formula | arranging-coins | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBasically here indirectly the n which was given to us is the sum of numbers \nSo we have let reult be x\nx(x+1)=n\nby solving this quadratic equation we have \nx^2+x-n=0\nOn applying the formula for roots we have\nx=-1+math.sqrt(1+8*n))/2... | 1 | You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the `ith` row has exactly `i` coins. The last row of the staircase **may be** incomplete.
Given the integer `n`, return _the number of **complete rows** of the staircase you will build_.
**Example 1:**
**I... | null |
one line Code,Easiest binary Search,Math Formula,normal solution | arranging-coins | 0 | 1 | # 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)$$ --... | 2 | You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the `ith` row has exactly `i` coins. The last row of the staircase **may be** incomplete.
Given the integer `n`, return _the number of **complete rows** of the staircase you will build_.
**Example 1:**
**I... | null |
Python3 O(1) Solution | arranging-coins | 0 | 1 | \n\n# Complexity\n- Time complexity:\n0(1)\n\n- Space complexity:\n0(1)\n\n# Code\n```\nclass Solution:\n def arrangeCoins(self, n: int) -> int:\n return int(sqrt(2 * n + 0.25) - 0.50)\n``` | 5 | You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the `ith` row has exactly `i` coins. The last row of the staircase **may be** incomplete.
Given the integer `n`, return _the number of **complete rows** of the staircase you will build_.
**Example 1:**
**I... | null |
Python Simple Binary Search | arranging-coins | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBrute force - Binary search as we are dealing with sorted numbers.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSum of numbers = x(x+1)/2\ntried to solve the equation by using substitution of numbers.\nThe num... | 3 | You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the `ith` row has exactly `i` coins. The last row of the staircase **may be** incomplete.
Given the integer `n`, return _the number of **complete rows** of the staircase you will build_.
**Example 1:**
**I... | null |
Python solution using counter method | find-all-duplicates-in-an-array | 0 | 1 | # 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)$$ --... | 1 | Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_.
You must write an algorithm that runs in `O(n)` time and uses only constant extra space.
**Example 1:**
... | null |
Easy marking O(n), O(1) solution | find-all-duplicates-in-an-array | 0 | 1 | # Intuition\nDouble way marking, mark the index and if the index you check next is already marked, visited.\n\n# Code\n```\nclass Solution:\n def findDuplicates(self, nums: List[int]) -> List[int]:\n\n res = []\n for i in nums:\n if nums[abs(i) - 1] < 0:\n res.append(abs(i))\n... | 4 | Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_.
You must write an algorithm that runs in `O(n)` time and uses only constant extra space.
**Example 1:**
... | null |
Python || Hash Table || Beats 95% Time Complexity 🔥 | find-all-duplicates-in-an-array | 0 | 1 | \n# Code\n```\nclass Solution:\n def findDuplicates(self, nums: List[int]) -> List[int]:\n ordmap = [0] * (len(nums)+1)\n arr = []\n if len(nums) <= 1: return []\n for i in range(len(nums)):\n ordmap[nums[i]] += 1\n if ordmap[nums[i]] == 2:\n arr.appen... | 1 | Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_.
You must write an algorithm that runs in `O(n)` time and uses only constant extra space.
**Example 1:**
... | null |
Python3|| Beats 96.18% runtime|| Hash Approach / List Comprehension | find-all-duplicates-in-an-array | 0 | 1 | # Please upvote!\n\n\n# Code\n```\n#HASH APPROACH\nclass Solution:\n def findDuplicates(self, nums: List[int]) -> List[int]:\n c = Counter(nums)\n lst=[]\n for i,j in c.items():\n ... | 9 | Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_.
You must write an algorithm that runs in `O(n)` time and uses only constant extra space.
**Example 1:**
... | null |
Solution | find-all-duplicates-in-an-array | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<int> findDuplicates(vector<int>& nums) {\n vector<int>ans; \n for(int i=0;i<nums.size();i++){\n if(nums[i]==nums.size()){\n nums[0]+=nums.size();\n continue;\n }\n nums[nums[i]%nums.size()]+=num... | 2 | Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_.
You must write an algorithm that runs in `O(n)` time and uses only constant extra space.
**Example 1:**
... | null |
Python: Using hashmap, beats 77% | find-all-duplicates-in-an-array | 0 | 1 | # 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)$$ --... | 1 | Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_.
You must write an algorithm that runs in `O(n)` time and uses only constant extra space.
**Example 1:**
... | null |
🐍 / Linear Time / String traversal solution / ~90% fastest | string-compression | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- We first have to traverse through the given list of characters and store the character and its continuous occurence in a list \'d\'.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Then in the list \'d\' create... | 2 | Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The co... | How do you know if you are at the end of a consecutive group of characters? |
[Python] 2 pointers; Explained | string-compression | 0 | 1 | We maintain two pointers for the char list:\n(1) the first one is for sweep the current list from 0 to len(chars);\n(2) the second one is for writer pointer that write the new content to the list\n\nIt works the same as the typical two pointer problem. the only difference is we only write the number to the list if the ... | 1 | Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The co... | How do you know if you are at the end of a consecutive group of characters? |
Python Easy Approach | string-compression | 0 | 1 | # Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def compress(self, chars: List[str]) -> int:\n c=0\n res=""\n ch=chars[0]\n for i in range(len(chars)):\n if(chars[i]!=ch):\n if(c==1):\n res+... | 1 | Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The co... | How do you know if you are at the end of a consecutive group of characters? |
Python short and clean. Functional programming. | string-compression | 0 | 1 | # Approach\n1. Iterate through `chars` and group by chars.\n\n2. Count the length, say `n`, of each group to make an iterable of `(ch, n)` pairs. Let\'s call this iterable `ch_counts`.\n\n3. For each pair map `(ch, n)` to `ch + str(n) if n > 1 else ch`.\n\n4. Chain the results into a single iterable, say `compressed`.\... | 2 | Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The co... | How do you know if you are at the end of a consecutive group of characters? |
Clean Codes🔥🔥|| Full Explanation✅|| Two Pointers✅|| C++|| Java|| Python3 | string-compression | 1 | 1 | # Intuition :\n- Given an array of characters, compress it in-place. The length after compression must always be smaller than or equal to the original array. Every element of the array should be a character (not int) of length 1.\n- Example:\n```\nInput:\n["a","a","b","b","c","c","c"]\nOutput:\nReturn 6, and the first ... | 94 | Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The co... | How do you know if you are at the end of a consecutive group of characters? |
Day 61 || Two Pointer || O(1) space and O(1) time || Easiest Beginner Friendly Sol | string-compression | 1 | 1 | **NOTE - PLEASE READ INTUITION AND APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n# Intuition of this Problem:\nThe implementation uses two pointers, i and j, to traverse the character array. The variable i is used to iterate over the array, while ... | 5 | Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The co... | How do you know if you are at the end of a consecutive group of characters? |
String Compression | string-compression | 0 | 1 | # 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)$$ --... | 1 | Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The co... | How do you know if you are at the end of a consecutive group of characters? |
Two pointer approach || TC=O(n) , Sc = O(1) || Faster than 100% in java and cpp 60% in python | string-compression | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind the code is to compress the given array of characters by counting consecutive repeating characters. If the count of a character is greater than 1, append the character followed by the count to the resulting compressed... | 3 | Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The co... | How do you know if you are at the end of a consecutive group of characters? |
🚩🚩🔥🔥100% solution ,Easy and Unique Approach 🚩🚩🔥🔥 | string-compression | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBasically,Normal frequency we find and form a string and then to list.But it fails in case where a different alphabet come and breaks the frequency and repeated character in dictionary will be added and gives you wrong output.To get these... | 3 | Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The co... | How do you know if you are at the end of a consecutive group of characters? |
Simple Diagram Explanation | string-compression | 1 | 1 | # Idea\n---\n- Here are some things we want to ask ourselves:\n - What to do when a character group is of length 1?\n - What to do when a character ground is length > 1?\n - How do I solve this in-place (for constant space complexity)?\n\n---\n- The reason the question is called **string compression** could be... | 31 | Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The co... | How do you know if you are at the end of a consecutive group of characters? |
Two Pointer Approach: Beats 96% submissions in Time Complexity | string-compression | 0 | 1 | # Intuition\nThe two pointer approach is the most effective strategy that comes to mind. \n\n# Approach\nWe initiate both left and right pointer at the beginning. We iterate the right pointer from left either to end or till we have similar character as the left pointer is pointing.\nOnce we get the count, remove all t... | 3 | Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The co... | How do you know if you are at the end of a consecutive group of characters? |
Python with comments (Explained) | string-compression | 0 | 1 | https://github.com/paulonteri/data-structures-and-algorithms\n```\nclass Solution(object):\n\n def compress(self, chars):\n\n length = len(chars)\n\n # make it a bit faster\n if length < 2:\n return length\n\n # the start position of the contiguous group of characters we are cu... | 101 | Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The co... | How do you know if you are at the end of a consecutive group of characters? |
443: Solution with step by step explanation | string-compression | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize a write index write_idx and a read index i to 0.\n2. While i is less than the length of chars, do the following:\n 1. Initialize a read index j to i + 1.\n 2. While j is less than the length of chars and ch... | 3 | Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The co... | How do you know if you are at the end of a consecutive group of characters? |
Python - Using itertools.groupby | string-compression | 0 | 1 | ```\nclass Solution:\n def compress(self, chars: List[str]) -> int:\n s = []\n for key, group in groupby(chars):\n #print(k, list(g))\n count = len(list(group))\n s.append(key)\n if count > 1: s.extend(list(str(count)))\n chars[:] = s\n\n``` | 14 | Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The co... | How do you know if you are at the end of a consecutive group of characters? |
Python 3 || 13 lines, iteration with pointer || T/M: 96% / 97% | string-compression | 0 | 1 | ```\nclass Solution:\n def compress(self, chars: list[str]) -> int:\n\n n, ptr, cnt = len(chars), 0, 1\n\n for i in range(1,n+1):\n\n if i < n and chars[i] == chars[i-1]: cnt += 1\n\n else:\n chars[ptr] = chars[i-1]\n ptr+= 1\n\n if cnt... | 3 | Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The co... | How do you know if you are at the end of a consecutive group of characters? |
Easy to follow | Python | Two pointer | string-compression | 0 | 1 | # Intuition\nNeed a pointer to fill the new value in the `chars` list. The placement of the character and it\'s counts happens whenever a new character is observed. \n\n# Approach\n- Start with `ptr=0` and note the char at 0-th index in `prev_char` and mark the `cnt=1` as you have already observed one character.\n- Mov... | 4 | Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The co... | How do you know if you are at the end of a consecutive group of characters? |
Python3 Solution | add-two-numbers-ii | 0 | 1 | \n```\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 addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n num1,num2=0,0\n while l1!... | 3 | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itsel... | null |
Python | Left pad, then recursion | add-two-numbers-ii | 0 | 1 | # Intuition\nIf we made sure the lists were the same length, it would simplify the problem. We can do that with a way to measure length and then left pad 0 values for the difference\n\n# Approach\n1. Determine the lengths of both linked lists\n2. prepend pad 0 value nodes on the smaller list to get lists of equal lengt... | 3 | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itsel... | null |
easy | add-two-numbers-ii | 0 | 1 | \n```\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 addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n p, o = "", ""\n \n\n #... | 1 | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itsel... | null |
Without reversing inputs, using stack | add-two-numbers-ii | 0 | 1 | # 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(max(m,n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m+n)$$\n<!-- Add your space comple... | 1 | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itsel... | null |
Add Two Numbers || | add-two-numbers-ii | 0 | 1 | # 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)$$ --... | 1 | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itsel... | null |
Easy python solution | add-two-numbers-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nconvert both lists to numbers, add, and convert to a linkedlist \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. $$... | 1 | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itsel... | null |
Python short and clean. Functional programming. | add-two-numbers-ii | 0 | 1 | # Complexity\n- Time complexity: $$O(max(n1, n2))$$\n\n- Space complexity: $$O(n1 + n2)$$\n\nwhere,\n`n1 is length of l1`,\n`n2 is length of l2`.\n\n# Code\n```python\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n def to_int(ll: ListNode) -> int:\n n = 0\n ... | 2 | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itsel... | null |
Ex-Amazon explains a solution with a video, Python, JavaScript, Java and C++ | add-two-numbers-ii | 1 | 1 | # Intuition\nUsing two stacks to make calculation easy.\n\n# Solution Video\n\nhttps://youtu.be/DP1oVjE5t6o\n\n# *** Please Upvote and subscribe to my channel from here. I have 224 LeetCode videos as of July 17th, 2023. ***\n\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n---\n\n# Approa... | 6 | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itsel... | null |
Python Without Reversing-Recursive-padding | add-two-numbers-ii | 0 | 1 | # Intuition\nPad the Input lists with leading zeros so each of the input lists have equal length.\n\n# Approach\nRecursively get the carry and the resultant summation for the next nodes and calculate the same for the current node.\n\n# Complexity\n- Time complexity:\nAs we are only Traversing the lists without any nes... | 1 | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itsel... | null |
✅Beat's 100% || 2 Method's || C++ || JAVA || PYTHON || Beginner Friendly🔥🔥🔥 | add-two-numbers-ii | 1 | 1 | # Intuition:\nThe stack-based approach for adding two numbers represented by linked lists involves using stacks to process the digits in reverse order. By pushing the digits of the linked lists onto separate stacks, we can simulate iterating through the numbers from the least significant digit to the most significant d... | 85 | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itsel... | null |
445: Solution with step by step explanation | add-two-numbers-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize two stacks stack1 and stack2 to store the values of each linked list.\n2. Traverse the first linked list l1 and push its values onto stack1.\n3. Traverse the second linked list l2 and push its values onto stack... | 3 | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itsel... | null |
Easy python3 solution, no recursion, no reverse | add-two-numbers-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. First convert the linkedlist 1 as an integer number.\n2. Again convert the linkedlist 2 as another integer number like step 1.\n3. Add both integer number and conve... | 3 | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itsel... | null |
OMG binbin's best solution ever! Beats 98.5% for runtime and 66% for memory | add-two-numbers-ii | 0 | 1 | # 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)$$ --... | 2 | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itsel... | null |
🔥🔥Easy Python and Java Solution with Explanation Beats 99% 🚀🚀 | add-two-numbers-ii | 1 | 1 | # Approach 1 => Using Stack\n- Create 2 stacks `s1` and `s2` for both the numbers and append the numbers in the respective stacks.\n- After that create a variable named `carry` which will take care of our carry values and one more variable as `root` which will be assigned to none so that we can return head of the list ... | 4 | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itsel... | null |
🔥[Python3] Using 2 stacks | add-two-numbers-ii | 0 | 1 | ```python3 []\nclass Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n st1, st2 = [], []\n\n while l1:\n st1.append(l1.val)\n l1 = l1.next\n while l2:\n st2.append(l2.val)\n l2 = l2.next\n\n ... | 9 | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itsel... | null |
99.41% faster solution | arithmetic-slices-ii-subsequence | 0 | 1 | ```\nclass Solution:\n def numberOfArithmeticSlices(self, nums: List[int]) -> int:\n res = 0\n dp = [defaultdict(int) for i in range(len(nums))]\n\t\t\n for i in range(1, len(nums)):\n for j in range(i):\n dif = nums[i]-nums[j]\n dp[i][dif] += 1\n ... | 3 | Given an integer array `nums`, return _the number of all the **arithmetic subsequences** of_ `nums`.
A sequence of numbers is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same.
* For example, `[1, 3, 5, 7, 9]`, `[7, 7, 7, 7]`, and ... | null |
446: Time 96.27% and Space 98.14%, Solution with step by step explanation | arithmetic-slices-ii-subsequence | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize a variable n to the length of the input array nums.\n\n2. Create an array dp of n empty dictionaries to store the number of arithmetic subsequences for each index.\n\n3. Initialize a variable res to 0 to store ... | 2 | Given an integer array `nums`, return _the number of all the **arithmetic subsequences** of_ `nums`.
A sequence of numbers is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same.
* For example, `[1, 3, 5, 7, 9]`, `[7, 7, 7, 7]`, and ... | null |
🔥🔥 Easy, short, Fast Python/Swift DP | arithmetic-slices-ii-subsequence | 0 | 1 | **Python**\n```\nclass Solution:\n def numberOfArithmeticSlices(self, nums: List[int]) -> int:\n total, n = 0, len(nums)\n dp = [defaultdict(int) for _ in nums]\n for i in range(1, n):\n for j in range(i):\n diff = nums[j] - nums[i]\n dp[i][diff] += dp[j]... | 10 | Given an integer array `nums`, return _the number of all the **arithmetic subsequences** of_ `nums`.
A sequence of numbers is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same.
* For example, `[1, 3, 5, 7, 9]`, `[7, 7, 7, 7]`, and ... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.