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 |
|---|---|---|---|---|---|---|---|
Simple Python Solution with Two Pointers | valid-palindrome | 0 | 1 | # Intuition\nTo check palindrom for alpha-numeric characters, there needs to be a check and removal for other characters. Rest is just checking first and last characters one by one. \n\n# Approach\nTake two position variables - start and end - and set them to first and last position of the string. Check for each charac... | 0 | A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_... | null |
Python3 Easy Solution | valid-palindrome | 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(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. $... | 0 | A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_... | null |
Beats 97.69% users in run time|| Just 2 lines of code | valid-palindrome | 0 | 1 | # Intuition\nSimple Solution using regex\n\n# Approach\nIt is very much self explanatory\n\n# Complexity\n- Time complexity:\n\n\n- Space complexity:\n\n\n# Code\n```\nimport re\nclass Solution:\n def isPalindrome(self, s: str) -> bool:\n slist =re.findall("[a-z0-9]",s.casefold())\n return slist==slist... | 0 | A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_... | null |
Simple List or string operation in Python | valid-palindrome | 0 | 1 | \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# About\n<!-- Describe your approach to solving the problem. -->\nYou can simply understand the solution by viewing the code\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add ... | 2 | A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_... | null |
Python code to check if a string is a valid palindrome or not. (TC&SC: O(n)) | valid-palindrome | 0 | 1 | \n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def isPalindrome(self, s: str) -> bool:\n s = s.lower()\n for i in s:\n if False == i.isalnum():\n s = s.replace(i,"")\n if s == s[::-1]:\n return True\n... | 3 | A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_... | null |
Simple Python 3 Solution || Beats 91% || 💻🧑💻🤖 | valid-palindrome | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def isPalindrome(self, s: str) -> bool:\n sen = ""\n for c in s:\n if c.isalnum():\n sen += c\n sen = sen.lower()\n return sen == sen[::-1]\n``` | 1 | A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_... | null |
2 liner code .99%.easy to understand code | valid-palindrome | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nDone through a very efficient built in function .isalnum()\n# Complexity\n- Time complexity:\nlinear O(n) time \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n... | 2 | A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_... | null |
Beats : 68.4% [18/145 Top Interview Question] | valid-palindrome | 0 | 1 | # Intuition\n*two pointers at the start and end and keep shifting as inwards as long as left < right and both the values in string falls under alphanumeric*\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis code checks whether a given string `s` is a palindrome or not. The approach used is to... | 7 | A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_... | null |
Speed is higher than 87%, Python3 | valid-palindrome | 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 | A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_... | null |
Simple solution with best time and space complexity | valid-palindrome | 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(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. $$... | 2 | A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_... | null |
Smartest solution using python (beats 97%) | valid-palindrome | 0 | 1 | # Intuition\nConvert the given string into a variable by convering it into lower case letter and avoiding the special characters and spaces.Then check if the resultant array is palindrome or not if True then return True else False. \n\n# Approach\nInitialize a variable with empty string then iterate over the given stri... | 3 | A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_... | null |
Simple Python Two Liner Solution | valid-palindrome | 0 | 1 | \nThis simple two liner approach to solving this problem relies on generator comprehension to make this a quick and concise solution.\n\n# Code\n```\n# The first line of code removes all non-alphanumeric characters and converts\n# the whole string to lowercase making it easy to reverse the string cleanly\n# using gener... | 6 | A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_... | null |
O(n * w) TIme and O(n^2 * w) Space Complexity, TLE and MLE Optimized!!! | word-ladder-ii | 0 | 1 | # Intuition\nFrom the problem statement, we had an idea of applying a BFS or DFS starting from beginWord and terminating at endWord. Later we also know that in this search, we\'ll have to pick the paths with minimum length. Also, to note that, there may be multiple ways to reach a particular intermediate/terminal word,... | 3 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
Easy Solution|| Beats 95% || Detailed Explanation🔥|| Easy 💯💯💯 | word-ladder-ii | 0 | 1 | Build Graph \uD83C\uDF10:\n\nCreate a graph where each word is connected to others with the same pattern.\nFor example, "hit" and "hot" are connected because the pattern is "h*t."\n\n\nInitialize Data Structures \uD83C\uDFD7\uFE0F:\n\nSet up data structures for the BFS and DFS.\nUse visited dictionaries to keep track o... | 1 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
✔️ Explanation with Animation - Accepted without TLE! | word-ladder-ii | 1 | 1 | # Intuition\nWe just need to record all possible words that can connect from the beginning, level by level, until we hit the end at a level.\n\n\n\nThen we will traverse backward from end via the words in the r... | 46 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
Python || Two Solutions || No TLE || BFS+DFS | word-ladder-ii | 0 | 1 | **Brute Force Solution using BFS (which gives TLE): In this we stored path directly in queue**\n\n```\ndef findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n wordList=set(wordList)\n if endWord not in wordList:\n return []\n q=deque()\n q.ap... | 1 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
Python | Clean Code | Proper Stages + Functions Explained | BFS | Parent Backtracking | word-ladder-ii | 0 | 1 | # Code\n```\nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n n = len(wordList)\n\n # Checking if beginWord is present in the dictionary or not\n # Checking if endWord is present and if not then returning 0\n isBeginInList = ... | 1 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
46ms Python 97 Faster Working Multiple solutions 95% memory efficient solution | word-ladder-ii | 0 | 1 | # Don\'t Forget To Upvote\n\n# 1. 97.81% Faster Solution:\n\n\t\tclass Solution:\n\t\t\tdef findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n\t\t\t\td = defaultdict(list)\n\t\t\t\tfor word in wordList:\n\t\t\t\t\tfor i in range(len(word)):\n\t\t\t\t\t\td[word[:i]+"*"+word[i+1:]]... | 40 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
BFS + DFS, the solution that should be easily understandable | word-ladder-ii | 0 | 1 | # Intuition\nBFS + DFS\n\nBFS is for getting all the parent of current node,\nmake sure to maintain a depth variable(step in the case),\neven tho the child may be visited before, but if it\'s direct children,\nwe still need to add it in the the parent hash.\n\ndfs is just to backtracking all parent to construct result\... | 1 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
BFS + DFS + Memo | word-ladder-ii | 0 | 1 | ```python\nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n word_set = set(wordList)\n if endWord not in word_set:\n return []\n # bfs build graph + dfs memo\n graph = defaultdict(set)\n queue = Deque([begin... | 2 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
[Python3] Breadth first search | word-ladder | 0 | 1 | ```\nInput:\nbeginWord = "hit",\nendWord = "cog",\nwordList = ["hot","dot","dog","lot","log","cog"]\nOutput: 5\n```\n1. Only one letter can be changed at a time.\nIn the example, from begin word, you can change one letter in 3 ways. 3 is the length of the word.\n```\n\t\t\t\t hit\n\t\t / | \\\n\t\t *it ... | 134 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
PYthon solution Accepted Only Code | word-ladder | 0 | 1 | # Code\n```\n def ladderLength(self, beginWord:str,endWord:str,wordList: List[str])->int:\n q = deque();\n q.append((beginWord,1));\n hmap = defaultdict(int)\n for word in wordList: hmap[word] = 1;\n hmap[beginWord] = 0\n while( len(q) > 0 ):\n #print(q);\n ... | 2 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
Prefix-Postfix-Letter Index | word-ladder | 0 | 1 | # Approach\nOverall the solution employs the same BFS. The only problem is to build the adjacency map.\n\nAll the words that differ only in one letter at some position, can be split into the same prefix and postfix with different letters in between:\n\npr-e-fix\npr-o-fix\npr-a-fix\npr-u-fix\n\nAll of these words have p... | 1 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
✅[Python] Simple and Clean✅ | word-ladder | 0 | 1 | ### Please upvote if you find this helpful. \u270C\n<img src="https://assets.leetcode.com/users/images/b8e25620-d320-420a-ae09-94c7453bd033_1678818986.7001078.jpeg" alt="Cute Robot - Stable diffusion" width="200"/>\n\n# Intuition\nThe idea behind bidirectional BFS is to search from both the `beginWord` and the `endWord... | 1 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
Python || Easy || BFS Solution | word-ladder | 0 | 1 | ```\ndef ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n wordList=set(wordList)\n if endWord not in wordList:\n return 0\n q=deque()\n q.append((beginWord,1))\n while q:\n word,step=q.popleft()\n for i in range(len(begin... | 9 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
Graph With BFS Approach | word-ladder | 0 | 1 | ```\nclass Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n if endWord not in wordList:\n return 0\n nei=defaultdict(list)\n wordList.append(beginWord)\n for word in wordList:\n for j in range(len(word)):\n ... | 5 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
127: Solution with step by step explanation | word-ladder | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe time complexity of this algorithm is O(M^2 * N), where M is the length of each word and N is the total number of words in the list. The space complexity is also O(M^2 * N) due to the use of the set and queue.\n\n# Comple... | 6 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
95% fast python, with comments and explanation | word-ladder | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n if endWord not in wordList:\n return 0\n nei = collections.defaultdict(list) #to create a dictionary with empty list \n wordList.append(beginWord)\n #adjacen... | 1 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
o(n) solution,using string hashing,hashmap,bfs | word-ladder | 0 | 1 | # Intuition\ntry doing brute force\n\n# Approach\n1>Go for brute force\n2>use bfs as memoization.\n3>use hashing for matching and changing string.\n\n# Complexity\n- Time complexity:\nlength of wordList(o(n))\n\n- Space complexity:\nspace of the dictionary i.e. o(n)\n\n# Code\n```\nfrom collections import deque\ndef ha... | 7 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
📌 Python3 BFS | word-ladder | 0 | 1 | ```\nfrom string import ascii_lowercase\n\nclass Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n wordList = set(wordList)\n \n queue = [(beginWord,1)]\n \n while queue:\n curr, count = queue.pop(0)\n if curr == e... | 2 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
Algorithm Explained | BFS | HASHSET | | word-ladder | 1 | 1 | # BFS\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSo, in a typicall Breadth-First-Search we utilize the queue and it\'s going to store each string that in our sequence & then we also going to have integer value called changes which will be eventually return from our function, whi... | 2 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
Minimal Explanation, using BFS | word-ladder | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe sub each character of the current word with every character in the letters, if the new word matches a word in wordList, we add it to the exploration queue, and delete it from the wordList (to avoid infinite loops).\n\n******\n### Note:... | 1 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
Intuitive solution without the wildcard logic, only 9% faster though | word-ladder | 0 | 1 | ```\nclass Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n \n """\n approach:\n 1. make the adjacency list\n 2. run bfs\n """\n wordList.insert(0, beginWord)\n wordList = set(wordList)\n visitedDic = {}\n ... | 1 | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need ... | null |
Solution | longest-consecutive-sequence | 1 | 1 | ```C++ []\nint a[100000];\n\nint init = [] {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n ofstream out("user.out");\n for (string s; getline(cin, s); out << \'\\n\') {\n if (s.length() == 2) {\n out << 0;\n continue;\n }\n int n = 0;\n for (int ... | 459 | Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
You must write an algorithm that runs in `O(n)` time.
**Example 1:**
**Input:** nums = \[100,4,200,1,3,2\]
**Output:** 4
**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefor... | null |
✅Python3 || C++|| Java✅[Intervals,Greedy and DP] without any sort | longest-consecutive-sequence | 1 | 1 | Let\'s break down the code and its logic in more detail:\n\n1. `std::unordered_map<int, std::pair<int, int>> mp;`\n\n- `mp` is an unordered map used to store intervals (ranges) of consecutive numbers. Each key represents the right endpoint of an interval, and the corresponding value is a pair `(r, l)` where `r` is the ... | 58 | Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
You must write an algorithm that runs in `O(n)` time.
**Example 1:**
**Input:** nums = \[100,4,200,1,3,2\]
**Output:** 4
**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefor... | null |
97% Faster Python3 easy O(n) solution with explanation | longest-consecutive-sequence | 0 | 1 | # Intuition\nFor every element we need to check if it has a sequence. If yes, what are it\'s sequential numbers and sequence\'s length? Also, when we visit a number, since we know it\'s sequential numbers, we can skip checking them.\n\nUsually a search operation like `in` takes longer time on lists vs sets. Average sea... | 6 | Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
You must write an algorithm that runs in `O(n)` time.
**Example 1:**
**Input:** nums = \[100,4,200,1,3,2\]
**Output:** 4
**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefor... | null |
Easy if you just store the different states | longest-consecutive-sequence | 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(n... | 0 | Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
You must write an algorithm that runs in `O(n)` time.
**Example 1:**
**Input:** nums = \[100,4,200,1,3,2\]
**Output:** 4
**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefor... | null |
Python easy O(n) solution | longest-consecutive-sequence | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nAdd numbers into a set.\nIterate through the list and for each element do the following verifications:\n\n1. Is this element an element that starts a sequence? To do that, just check if element-1 is in the set.\n2. If the el... | 2 | Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
You must write an algorithm that runs in `O(n)` time.
**Example 1:**
**Input:** nums = \[100,4,200,1,3,2\]
**Output:** 4
**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefor... | null |
😍 Simplest Python solution with O(n) time complexity and O(n) space complexity | longest-consecutive-sequence | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nPython solution with a simple algorithm to find solution in O(n) time complexity with O(n) space complexity. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Convert list to set using inbuilt set function.\n2. C... | 31 | Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
You must write an algorithm that runs in `O(n)` time.
**Example 1:**
**Input:** nums = \[100,4,200,1,3,2\]
**Output:** 4
**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefor... | null |
Easy To Understand | Python Solution | longest-consecutive-sequence | 0 | 1 | \n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def longestConsecutive(self, nums):\n """\n :type nums: List[int]\n :... | 1 | Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
You must write an algorithm that runs in `O(n)` time.
**Example 1:**
**Input:** nums = \[100,4,200,1,3,2\]
**Output:** 4
**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefor... | null |
📌 Python solution keeping track of current max and current count | longest-consecutive-sequence | 0 | 1 | ```\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n nums = sorted(set(nums))\n \n cur_max = 0\n cur_count = 0\n prev = None\n for i in nums:\n if prev is not None:\n if prev+1 == i:\n cur_count += 1\n ... | 3 | Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
You must write an algorithm that runs in `O(n)` time.
**Example 1:**
**Input:** nums = \[100,4,200,1,3,2\]
**Output:** 4
**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefor... | null |
Python3 | C++ | Brute-force > Better > Optimal | Full Explanation | longest-consecutive-sequence | 0 | 1 | - Approach\n - Brute-force\n - For each element count its consecutive elements present in the array\n - Time Complexity: $O(n^3)$\n - Space Complexity: $O(1)$\n - Better\n - Sort the array and check for consecutive elements\n - Time Complexity: $O(nlogn)$\n - Space Comple... | 3 | Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
You must write an algorithm that runs in `O(n)` time.
**Example 1:**
**Input:** nums = \[100,4,200,1,3,2\]
**Output:** 4
**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefor... | null |
Best Python3 Solution || Upto 99 % Faster || Easy to Read || Commented | sum-root-to-leaf-numbers | 0 | 1 | # Intuition\nWe take the paths into a list and then make path number (take 1 Path and make it the number like 1->2->3 into 123) and finally sum of the all those path numbers.\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.... | 1 | You are given the `root` of a binary tree containing digits from `0` to `9` only.
Each root-to-leaf path in the tree represents a number.
* For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`.
Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer w... | null |
Recursion | DFS | Beats 90% | sum-root-to-leaf-numbers | 0 | 1 | # Complexity\n- Time complexity: O(V + E)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(h)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n ans = 0\n def sumNumbers(self, root: Optional[TreeNode]) -> int: \n def dfs(root,tmp):... | 1 | You are given the `root` of a binary tree containing digits from `0` to `9` only.
Each root-to-leaf path in the tree represents a number.
* For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`.
Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer w... | null |
DFS Solution Python | surrounded-regions | 0 | 1 | \n# Code\n```\nclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n def dfs(i,j,mark):\n nonlocal board\n if( (i < 0) or (j < 0 ) or (i >= m) or (j >= n) ):\n print(f\'returned on {i,j}\')\n return False;\n elif(board[i][j] == \'X\... | 2 | Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "... | null |
Binbin eternal god in DFS | surrounded-regions | 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 `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "... | null |
Easy to understand PYTHON solution beats 93% with proper comments | surrounded-regions | 0 | 1 | # Intuition\nReverse Thinking - we will use this way of thinking.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach \n\n1.) First we will write a DFS method.\n2.) Then we will capture unsurrounded region(O->T) changing all the O\'s to T in the border rows and columns and their adjacent... | 1 | Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "... | null |
Click this if you're confused | surrounded-regions | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition is simple: a region of "O"s is unsurrounded if one of its "O"s is at the border. We can solve this problem simply by iterating the border tiles and traversing all "O" regions, treat them as connected graphs. These "O" region... | 2 | Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "... | null |
Python Solution (DFS) | surrounded-regions | 0 | 1 | # Code\n```\nclass Solution:\n def solve(self, board):\n nrows = len(board)\n ncols = len(board[0])\n not_surrounded = set()\n\n def dfs(row, col):\n if row not in range(nrows) or col not in range(ncols) or board[row][col] == "X" or (row, col) in not_surrounded:\n ... | 1 | Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "... | null |
Easy Explained Solution With 🏞 (Images) | surrounded-regions | 1 | 1 | \n\n time | O(N) Space | surrounded-regions | 0 | 1 | This problem could be solved two ways:\n1. Identify all isolated `\'O\'` cells and mark them as `\'X\'` then.\n2. Mark all accessible from boarders `\'O\'` and then turn all inaccessible ones into `\'X\'`.\n\nThis solution is about the **second way**.\n\nTo mark cells as "reachable", algorithm changing their values to ... | 53 | Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "... | null |
Python way - Simple DFS | surrounded-regions | 1 | 1 | \tclass Solution:\n\t\tdef solve(self, mat: List[List[str]]) -> None:\n\t\t\tn=len(mat)\n\t\t\tm=len(mat[0])\n\n\t\t\tdef dfs(i,j):\n\t\t\t\tvisited[i][j]=1\n\t\t\t\tdir = [[-1,0],[0,1],[1,0],[0,-1]]\n\t\t\t\tfor a,b in dir:\n\t\t\t\t\trow = a+i\n\t\t\t\t\tcol = b+j\n\t\t\t\t\tif row>=0 and row<n and col>=0 and col<m a... | 1 | Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "... | null |
(Python) Count Good Nodes in Binary Tree | surrounded-regions | 0 | 1 | # Intuition\nOne approach to solve this problem is to use depth-first search (DFS) to mark all the regions that are not surrounded by \'X\'. The regions that are not marked are the regions that need to be flipped.\n# Approach\n1. First, we check the corner elements of the board (1st row, 1st column, last row, and last ... | 2 | Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "... | null |
Easy & Clear Solution Python 3 Beat 99.8% | surrounded-regions | 0 | 1 | \n# Code\n```\nclass Solution:\n def solve(self, b: List[List[str]]) -> None:\n m=len(b)\n n=len(b[0])\n def dfs(i,j):\n if b[i][j]=="O":\n b[i][j]="P"\n if i<m-1:\n dfs(i+1,j)\n if i>0:\n dfs(i-1,j)\n ... | 4 | Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "... | null |
Easy to understand Python3 Solution | surrounded-regions | 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 | Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "... | null |
Python || 97.64% Faster || BFS || DFS || Two Approaches | surrounded-regions | 0 | 1 | **BFS Approach:**\n```\ndef solve(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n """\n m=len(board)\n n=len(board[0])\n q=deque()\n for i in range(m):\n for j in range(n):\n if i==0 or i==... | 6 | Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "... | null |
MOST OPTIMIZED PYTHON SOLUTION | palindrome-partitioning | 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(N^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N)$$\n<!-- Add your space complexity he... | 2 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
Polindromic Partioning(Python3).. | palindrome-partitioning | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nCheck the every possible partition in the string and check whether the given string is polindrome or not...\n\n# Code\n```\nclass Solution:\n def partition(self, s: str) -> List[List[str]]:\n res=[]\n part=[]\n def dfs(i):\n ... | 1 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
Python3 Simple Recursive Solution | palindrome-partitioning | 0 | 1 | **Note: This approach could be sped up with dp** (I was just too lazy)\n\n```\nclass Solution:\n def partition(self, s: str) -> List[List[str]]:\n n = len(s)\n ans = []\n if n == 0:\n return [[]]\n for i in range(1, n + 1):\n if s[:i] != s[:i][::-1]:\n ... | 1 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
Solution | palindrome-partitioning | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<vector<string>> partition(string s) {\n vector<vector<string>> pars;\n vector<string> par;\n partition(s, 0, par, pars);\n return pars;\n }\nprivate: \n void partition(string& s, int start, vector<string>& par, vector<vector<string>>& pa... | 211 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
✅ [Python] Simple Recursion || Detailed Explanation || Easy to Understand | palindrome-partitioning | 0 | 1 | **PLEASE UPVOTE if you like** \uD83D\uDE01 **If you have any question, feel free to ask.** \n* Find answer recursively and memory trick can save some time\n* traverse and check every prefix `s[:i]` of `s`\n\t* if prefix `s[:i]` is a palindrome, then process the left suffix `s[i:]` recursively\n\t* since the suffix `s[i... | 262 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
Python3 || Easy to understand solution || Explained & Commented || With Sketch | palindrome-partitioning | 0 | 1 | # Explanation\nThe main trick is backtracking.\nFor each position of the string, you have at most 2 options: You either 1) check if the current substring is a palindrome and add it to the partition list, or 2) you don\'t add it to the list\n\nThe current substring is the letter of the current position plus the substrin... | 0 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
the best solution ever all -Python | palindrome-partitioning | 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 a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
131: Solution with step by step explanation | palindrome-partitioning | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n- Use a backtracking approach to generate all the possible palindrome partitions.\n- For each character of the string, consider all possible substrings starting at the current character and check if it\'s a palindrome.\n- If... | 3 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
Python || 97.14% Faster || Backtracking || Easy | palindrome-partitioning | 0 | 1 | ```\nclass Solution:\n def partition(self, s: str) -> List[List[str]]:\n def valid(ip):\n if ip==ip[-1::-1]:\n return True\n return False\n \n def solve(ip,op):\n if ip==\'\':\n ans.append(op[:])\n return\n ... | 2 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
Palindrome Partitioning. Python3 | palindrome-partitioning | 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 a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
python3, simple dfs (659 ms, faster than 85.12%) | palindrome-partitioning | 0 | 1 | ERROR: type should be string, got "https://leetcode.com/submissions/detail/883354080/ \\nRuntime: **659 ms**, faster than 85.12% of Python3 online submissions for Palindrome Partitioning. \\nMemory Usage: 28.2 MB, less than 99.36% of Python3 online submissions for Palindrome Partitioning. \\n```\\nclass Solution:\\n def partition(self, s: str) -> List[List[str]]:\\n partitions, lst, l = [], [([], 0)], len(s)\\n while lst: ## dfs\\n pals, i = lst.pop()\\n for j in range(i+1, l+1):\\n sub = s[i:j]\\n if sub==sub[::-1]: ## if sub is a palindrome\\n if j==l: ## reach the end\\n partitions.append(pals+[sub])\\n else:\\n lst.append((pals+[sub], j))\\n return partitions\\n```\\n" | 5 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
Click this if you're confused. | palindrome-partitioning | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA valid partitioning of `s` results in substrings of `s` that are palindromes. Palindromes are easy. What if we were to just return all distinct partitions of `s` with the constraint that a substring had to at least be one character?\n\nF... | 1 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
Python3: Simple Backtracking Approach | palindrome-partitioning | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn this problem DP can be considered but as we are not calculating number of solutions but to return all the possible solutions.So it is better to backtrack. \n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Conside... | 27 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
🎉3 Solutions🎉 ||Deep Explaination👀🤔👀||Backtracking✅|| C++|| Java || Python3 | palindrome-partitioning | 1 | 1 | # Approach : Backtracking\n```\nExample - xxyy\n```\n\n\n# Complexity :\n- Time Complexity :- BigO(N*2^N)\n- Space Complexity :- BigO(N)\n\n# Request \uD83D... | 16 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
Python solution using recursion beats 90% time complexity :-) | palindrome-partitioning | 0 | 1 | # Complexity\n- Time complexity: O(2^n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def partition(self, s: str) -> List[List[str]]:\n def checkPalindrome(str, startIndex, lastIndex)... | 1 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
using backtracking, with explanation | palindrome-partitioning | 0 | 1 | \'\'\'\nclass Solution:\n def partition(self, s: str) -> List[List[str]]:\n\t\n \n partition=[] # for storing each partition\'s substrings\n index=0\n res=[] # each individual partitions will store in res\n self.helper(s,partition,index,res)\n return res\n \n def h... | 1 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
🔥Python🔥Backtracking🔥Beats 91.1% in runtime, 78.51% in memory🔥 | palindrome-partitioning | 0 | 1 | \n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe partition method of the Solution class is solving the problem of finding all possible partitions of a gi... | 3 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
[Python] ✅🔥 Clear, Simple Backtracking Solution! | palindrome-partitioning | 0 | 1 | ## **Please upvote/favourite/comment if you like this solution!**\n\n# Code\n```\nclass Solution:\n def isPalindrome(self, s):\n i, j = 0, len(s)-1\n while i <= j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n\n def backtra... | 4 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
Python Code with Documentation - 99% runtime O(n^2) solution | palindrome-partitioning | 0 | 1 | # Intuition\nWe can break down the problem into two sub-problems:\n1. Find all palindromes in the string\n2. Starting from the start of the string, combine palindromes together to form all the valid partitions\n\n# Approach\nWe can complete 1. using the same approach as in https://leetcode.com/problems/longest-palindro... | 2 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1... | null |
[Python] Simple Top-down DP Solution O(N^2) | palindrome-partitioning-ii | 0 | 1 | # Approach\nWe first precompute the valid palindromes from start to end value. We use the idea that if s[i:j] is a palindrome, then s[i+1:j-1] must be a palindrome and s[i] must equal s[j]. After this our recursive function will just iterate through the string from the previous cut to the end and perform a cut at every... | 3 | Given a string `s`, partition `s` such that every substring of the partition is a palindrome.
Return _the **minimum** cuts needed for a palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab "
**Output:** 1
**Explanation:** The palindrome partitioning \[ "aa ", "b "\] could be produced using 1 cut.
**... | null |
Python || MCM DP || Recursion->Tabulation | palindrome-partitioning-ii | 0 | 1 | ```\n#Recursion \n#Time Complexity: O(Exponential)\n#Space Complexity: O(n)\nclass Solution1:\n def minCut(self, s: str) -> int:\n def solve(ind):\n if ind==n:\n return 0\n temp=\'\'\n mini=maxsize\n for j in range(ind,n):\n temp+=s[j]\... | 3 | Given a string `s`, partition `s` such that every substring of the partition is a palindrome.
Return _the **minimum** cuts needed for a palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab "
**Output:** 1
**Explanation:** The palindrome partitioning \[ "aa ", "b "\] could be produced using 1 cut.
**... | null |
132: Solution with step by step explanation | palindrome-partitioning-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTo solve this problem, we can use dynamic programming. We can first preprocess the string to determine which substrings are palindromes. Then, we can use dynamic programming to determine the minimum cuts needed to partition ... | 6 | Given a string `s`, partition `s` such that every substring of the partition is a palindrome.
Return _the **minimum** cuts needed for a palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab "
**Output:** 1
**Explanation:** The palindrome partitioning \[ "aa ", "b "\] could be produced using 1 cut.
**... | null |
✔ Python3 Solution | DP | O(n^2) | palindrome-partitioning-ii | 0 | 1 | # Complexity\n- Time complexity: $$O(n^2)$$\n- Space complexity $$O(n)$$\n\n# Code\n```\nclass Solution:\n def minCut(self, S):\n N = len(S)\n dp = [-1] + [N] * N\n for i in range(2 * N - 1):\n l = i // 2\n r = l + (i & 1)\n while 0 <= l and r < N and S[l] == S[r... | 4 | Given a string `s`, partition `s` such that every substring of the partition is a palindrome.
Return _the **minimum** cuts needed for a palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab "
**Output:** 1
**Explanation:** The palindrome partitioning \[ "aa ", "b "\] could be produced using 1 cut.
**... | null |
✔️ [Python3] ITERATIVE BFS (beats 98%) ,、’`<(❛ヮ❛✿)>,、’`’`,、, Explained | clone-graph | 0 | 1 | **UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nTo solve this problem we need two things: \n\n1. BFS to traverse the graph\n2. A hash map to keep track of already visited and already cloned nodes\n\nWe push a node in the queue and make sure that the node is alread... | 321 | Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`)... | null |
python3 Solution | clone-graph | 0 | 1 | \n```\n"""\n# Definition for a Node.\nclass Node:\n def __init__(self, val = 0, neighbors = None):\n self.val = val\n self.neighbors = neighbors if neighbors is not None else []\n"""\n\nclass Solution:\n def cloneGraph(self, node: \'Node\') -> \'Node\':\n oldToNew={}\n def dfs(node):\n... | 4 | Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`)... | null |
Simple and Easy Solution 🔥🔥🔥 | clone-graph | 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 a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`)... | null |
Simple and Fast Python Solution | clone-graph | 0 | 1 | # Code\n```\n"""\n# Definition for a Node.\nclass Node:\n def __init__(self, val = 0, neighbors = None):\n self.val = val\n self.neighbors = neighbors if neighbors is not None else []\n"""\n\nclass Solution:\n def cloneGraph(self, node: \'Node\') -> \'Node\':\n if node == None:\n r... | 1 | Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`)... | null |
Click this if you're confused. | clone-graph | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor each node, we must create its copy, then create copies of the neighbors and set our copy\'s "neighbors" property to these copied neighbors. We also must use the neighbors to traverse the graph, so that we can repeat this copy process ... | 1 | Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`)... | null |
Using DFS with Hashmap | clone-graph | 0 | 1 | ```\nclass Solution:\n def cloneGraph(self, node: \'Node\') -> \'Node\':\n if not node: return node\n dic={}\n def dfs(node):\n if node in dic:\n return dic[node]\n copy=Node(node.val)\n dic[node]=copy\n for nei in node.neighbors:\n ... | 3 | Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`)... | null |
Python Elegant & Short | DFS | HashMap | clone-graph | 0 | 1 | # Complexity\n- Time complexity: $$O(V + E)$$\n- Space complexity: $$O(V)$$\n\n# Code\n```\nclass Solution:\n def cloneGraph(self, node: Node | None) -> Node | None:\n return self.dfs(node, {None: None})\n\n def dfs(self, node: Node | None, graph: dict) -> Node | None:\n if node not in graph:\n ... | 3 | Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`)... | null |
✅✅Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand🔥 | clone-graph | 1 | 1 | # Please UPVOTE \uD83D\uDC4D\n\n**!! 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 week. I planned to give for next 10,000 Subscribers a... | 20 | Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`)... | null |
✅[Python] Simple and Clean, beats 94.55%✅ | clone-graph | 0 | 1 | ### Please upvote if you find this helpful. \u270C\n<img src="https://assets.leetcode.com/users/images/b8e25620-d320-420a-ae09-94c7453bd033_1678818986.7001078.jpeg" alt="Cute Robot - Stable diffusion" width="200"/>\n\n*This is an NFT*\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->... | 3 | Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`)... | null |
Python | Easy | Clean Code | clone-graph | 0 | 1 | **PLEASE DO UPVOTE IF U GET THIS**\n```\n\nclass Solution:\n \n def helper(self, node, visited):\n if node is None:\n return None\n \n newNode = Node(node.val)\n visited[node.val] = newNode\n \n for adjNode in node.neighbors:\n if adjNode.val not in ... | 47 | Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`)... | null |
Day 98 || DFS + Hash Table || Easiest Beginner Friendly Sol | clone-graph | 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 :\n*This problem is about cloning a given connected undirected graph. Given a reference to a node in the graph, we need to create a deep c... | 7 | Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`)... | null |
✅✅Python🔥C++🔥Java🔥 Both DFS and BFS approach explained ☑️☑️ | clone-graph | 1 | 1 | # DFS APPROACH\n# Intuition\nThe algorithm uses depth-first search (DFS) to traverse the original graph and create a copy of each node and its neighbors. A map is used to keep track of the nodes that have already been cloned. This helps to avoid creating duplicate copies of nodes and ensures that the cloned graph is id... | 5 | Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`)... | null |
Solution | gas-station | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n int n = cost.size(), bal = 0, start = 0, deficit = 0;\n\n for(int i = 0; i< n; i++){\n bal += gas[i] - cost[i];\n\n ... | 211 | There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`.
You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations.
Gi... | null |
Python 3 || 2-6 lines, w/ explanation and example || T/M: 99% / 98% | gas-station | 0 | 1 | Here\'s the plan:\n\n- First, it is possible to complete the circuit if and only if the total amount of gas on the circuit is sufficient to drive the circuit. More formally: `sum(gas) >= sum(cost)`.\n- The starting station can be determined by starting at some station`a`(say, `a = 0`) and noting whether a station `b` o... | 80 | There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`.
You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations.
Gi... | null |
Easy_python | gas-station | 0 | 1 | # Code\n```\nclass Solution:\n def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:\n rem=0\n st=0\n t_gas=0\n for p in range(len(gas)):\n dif=gas[p]-cost[p]\n t_gas+=dif\n rem+=dif\n if rem<0:\n st=p+1\n ... | 5 | There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`.
You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations.
Gi... | null |
Python Solution Time O(n) Space O(1) | gas-station | 0 | 1 | # Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:\n\n start = 0\n slicer = 0\n sum = 0\n while slicer - start < len(gas):\n sum += gas[slicer] - cost[slicer]\... | 1 | There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`.
You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations.
Gi... | null |
Python simple and very short explained solution - O(n), O(1) - faster than 98% | gas-station | 0 | 1 | 1. If sum of gas is less than sum of cost, then there is no way to get through all stations. So while we loop through the stations we sum up, so that at the end we can check the sum.\n2. Otherwise, there must be one unique solution, so the first one I find is the right one. If the tank becomes negative, we restart beca... | 145 | There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`.
You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations.
Gi... | null |
Simple Python solution | gas-station | 0 | 1 | # Complexity\n- Time complexity:\n73.70 %\n\n- Space complexity:\n49.17 %\n\n# Code\n```\nclass Solution:\n def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:\n if sum(gas) < sum(cost):\n return -1\n a = len(gas)\n s = 0\n result = 0\n for i in range(a... | 1 | There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`.
You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations.
Gi... | null |
✔️ [Python3] DEBIT AND CREDIT, O(1) SPACE, ᕕ( ᐛ )ᕗ ⛽, Explained | gas-station | 0 | 1 | **UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nConsider this example: `----+++`, where \xAB-\xBB are parts of the way where we don\'t have enough gas to travel to the next station, and \xAB+\xBB are vice versa. Imagine that we could borrow the gas for those \xAB... | 53 | There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`.
You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations.
Gi... | null |
✅ 99.20% Greedy Two & One Pass | candy | 1 | 1 | # Comprehensive Guide to Solving "Candy": Distributing Candies Like a Pro\n\n## Introduction & Problem Statement\n\nHey there, coding enthusiasts! Welcome back to another exciting coding session. Today\'s problem is a treat\u2014literally! We\'re going to solve the "Candy" problem. Imagine you have a bunch of kids line... | 192 | There are `n` children standing in a line. Each child is assigned a rating value given in the integer array `ratings`.
You are giving candies to these children subjected to the following requirements:
* Each child must have at least one candy.
* Children with a higher rating get more candies than their neighbors.... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.