post_href
stringlengths
57
213
python_solutions
stringlengths
71
22.3k
slug
stringlengths
3
77
post_title
stringlengths
1
100
user
stringlengths
3
29
upvotes
int64
-20
1.2k
views
int64
0
60.9k
problem_title
stringlengths
3
77
number
int64
1
2.48k
acceptance
float64
0.14
0.91
difficulty
stringclasses
3 values
__index_level_0__
int64
0
34k
https://leetcode.com/problems/isomorphic-strings/discuss/381930/Python-multiple-solutions
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: last_position = [0]*512 for idx in range(len(s)): if last_position[ord(s[idx])] != last_position[ord(t[idx]) + 256]: return False last_position[ord(s[idx])] = last_position[ord(t[idx]) + 256] = idx + 1 return True
isomorphic-strings
Python multiple solutions
amchoukir
7
1,700
isomorphic strings
205
0.426
Easy
3,400
https://leetcode.com/problems/isomorphic-strings/discuss/1058562/Python3-simple-and-explained-line-by-line
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: #corner case: because s and t are the same length, any string of 1 character is isomorphic if len(s) == 1: return True #Dictionary to map the characters from s with the characters of t charDict = {} #both arrays are the same size, with a ranged for loop we can consult both strings for i in range(0,len(s)): if s[i] not in charDict.keys():#Check first if the character is not there yet as a key if t[i] not in charDict.values():#It's important to check that before mapping a value, check if it has not yet been mapped charDict[s[i]] = t[i] else: return False #as the problem states, no two chars may map to the same character, therefore it is false else: if charDict[s[i]] != t[i]: #if the character is already mapped, but the char t[i] is not the same as the one already mapped, it is false return False return True #after going through all the conditionals, we can confirm the string is isomorphic ´´´
isomorphic-strings
Python3 simple and explained line by line
luisfmiranda97
5
576
isomorphic strings
205
0.426
Easy
3,401
https://leetcode.com/problems/isomorphic-strings/discuss/656556/Simple-Python-3-solution-runtime-beats-94.7-submissions
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: i = 0 h = {} while i < len(s): if t[i] not in h: if s[i] in h.values(): return False else: h[t[i]] = s[i] else: if h[t[i]] != s[i]: return False i = i + 1 return True
isomorphic-strings
Simple Python 3 solution; runtime beats 94.7% submissions
Swap24
4
233
isomorphic strings
205
0.426
Easy
3,402
https://leetcode.com/problems/isomorphic-strings/discuss/2377315/more-efficient-oror-using-Python-oror-very-small
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: z= zip(s,t) if len(set(z))==len(set(s))==len(set(t)): return True return False
isomorphic-strings
more efficient || using Python || very small 🤞
shane6123
3
130
isomorphic strings
205
0.426
Easy
3,403
https://leetcode.com/problems/isomorphic-strings/discuss/2350597/Python-solution-using-hash-function-to-compute-an-index-with-a-key-into-an-array-of-slots
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: if len(s)!=len(t) or len(set(s))!=len(set(t)): return False hashmap={} for i in range(len(s)): if s[i] not in hashmap: hashmap[s[i]]=t[i] if hashmap[s[i]]!=t[i]: return False return True
isomorphic-strings
Python solution using hash function to compute an index with a key into an array of slots
RohanRob
3
184
isomorphic strings
205
0.426
Easy
3,404
https://leetcode.com/problems/isomorphic-strings/discuss/2439195/Simple-One-Liner-or-Python
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: return len(set(zip(s,t))) == len(set(s)) == len(set(t))
isomorphic-strings
Simple One Liner | Python
Abhi_-_-
2
199
isomorphic strings
205
0.426
Easy
3,405
https://leetcode.com/problems/isomorphic-strings/discuss/2157200/Python-3-Set-a-dict-Memory-less-than-99.41
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: replace_dict = dict() dict_values = replace_dict.values() for char, rep_char in zip(s, t): if char not in replace_dict: if rep_char not in dict_values: replace_dict[char] = rep_char else: return False elif replace_dict[char] != rep_char: return False return True
isomorphic-strings
Python 3 - Set a dict - Memory less than 99.41%
thanhinterpol
2
89
isomorphic strings
205
0.426
Easy
3,406
https://leetcode.com/problems/isomorphic-strings/discuss/2709969/Easy-Python-Solution
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: m1 = [s.index(i) for i in s] m2 = [t.index(i)for i in t] return m1==m2
isomorphic-strings
Easy Python Solution
mariusep
1
4
isomorphic strings
205
0.426
Easy
3,407
https://leetcode.com/problems/isomorphic-strings/discuss/2179500/PYTHON-oror-Simple-and-Easy-Solution-%2B-65-faster
class Solution(object): def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ # LOGIC - Map the 1st string characters in correspondace to the 2nd one, simultaneously # check if the 2nd string characters are fit with the maping table or not. # Checking if length of strings are same or not after eliminating duplicate characters to see if 1st string can be fully mapped to the 2nd one or not if len(set(s)) != len(set(t)): print("len not same") return False #creating a dictonary to store the mapping characters iso_dict = {} #Mapping and simultaneously checking if the characters of 1st and 2nd string satisfies the mapping for i,j in zip(s,t): if i in iso_dict and iso_dict[i] != j: return False iso_dict[i] = j return True
isomorphic-strings
PYTHON || Simple and Easy Solution + 65% faster
navinchndr012
1
143
isomorphic strings
205
0.426
Easy
3,408
https://leetcode.com/problems/isomorphic-strings/discuss/2168026/most-easiest-python3-with-one-loop
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: st_dict, ts_dict = {}, {} for i,j in zip(s,t): st_dict[i]=j ts_dict[j]=i return list(st_dict.keys()) == list(ts_dict.values())
isomorphic-strings
most easiest python3 with one loop
lq291464
1
130
isomorphic strings
205
0.426
Easy
3,409
https://leetcode.com/problems/isomorphic-strings/discuss/2088126/python3-O(n)-oror-O(1)O(n)-55ms-54.84
class Solution: # O(N) || O(26n) or O(1) if we are granteed that s and t will be lowercase english letters else its O(n) # 55ms 54.84% def isIsomorphic(self, s: str, t: str) -> bool: return self.isomorphic(s) == self.isomorphic(t) def isomorphic(self, string): letterDict = dict() result = str() nextChar = 'a' for char in string: if char not in letterDict: letterDict[char] = nextChar nextChar = chr(ord(nextChar) + 1) result += letterDict[char] return result
isomorphic-strings
python3 O(n) || O(1)\O(n) 55ms 54.84%
arshergon
1
124
isomorphic strings
205
0.426
Easy
3,410
https://leetcode.com/problems/isomorphic-strings/discuss/1335531/Python%3A-Simple-solution-using-dictionary
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: d = {} for i, j in zip(s, t): if i not in d.keys(): d[i] = j for i, j in zip(s, t): if j != d[i] or len(list(d.values())) != len(list(set(list(d.values())))): return False return True
isomorphic-strings
Python: Simple solution using dictionary
farhan_kapadia
1
308
isomorphic strings
205
0.426
Easy
3,411
https://leetcode.com/problems/isomorphic-strings/discuss/746932/Python3%3A-Simple-faster-than-75
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: mappedChars = set() myDic = {} for idx in range(len(s)): if s[idx] in myDic: if t[idx] != myDic[s[idx]]: return False else: if t[idx] in mappedChars: return False myDic[s[idx]] = t[idx] mappedChars.add(t[idx]) return True
isomorphic-strings
Python3: Simple faster than 75%
nachiketsd
1
321
isomorphic strings
205
0.426
Easy
3,412
https://leetcode.com/problems/isomorphic-strings/discuss/733261/Python3-3-approaches
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: mps, mpt = {}, {} for i, (ss, tt) in enumerate(zip(s, t)): if mps.get(ss) != mpt.get(tt): return False mps[ss] = mpt[tt] = i return True
isomorphic-strings
[Python3] 3 approaches
ye15
1
163
isomorphic strings
205
0.426
Easy
3,413
https://leetcode.com/problems/isomorphic-strings/discuss/733261/Python3-3-approaches
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: return len(set(zip(s, t))) == len(set(s)) == len(set(t))
isomorphic-strings
[Python3] 3 approaches
ye15
1
163
isomorphic strings
205
0.426
Easy
3,414
https://leetcode.com/problems/isomorphic-strings/discuss/733261/Python3-3-approaches
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: fn = lambda x: tuple(map({}.setdefault, x, range(len(s)))) return fn(s) == fn(t)
isomorphic-strings
[Python3] 3 approaches
ye15
1
163
isomorphic strings
205
0.426
Easy
3,415
https://leetcode.com/problems/isomorphic-strings/discuss/551292/Python-simple-solution-20-ms-faster-than-96.70-O(n2)
class Solution(object): def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ char_dict = dict() for i in range(len(s)): if s[i] not in char_dict: if t[i] not in char_dict.values(): char_dict[s[i]] = t[i] else: return False new_str = ''.join([char_dict[char] for char in s]) return new_str == t
isomorphic-strings
Python simple solution 20 ms, faster than 96.70% , O(n^2)
hemina
1
391
isomorphic strings
205
0.426
Easy
3,416
https://leetcode.com/problems/isomorphic-strings/discuss/511504/Python-find-and-save-the-position-of-each-character
class Solution(object): def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ s_index = [ s.find(i) for i in s ] t_index = [ t.find(i) for i in t ] return s_index == t_index
isomorphic-strings
Python find and save the position of each character
kobewang
1
285
isomorphic strings
205
0.426
Easy
3,417
https://leetcode.com/problems/isomorphic-strings/discuss/359128/Solution-in-Python-3
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: S, T, j, k = {} ,{}, 0, 0 for a,b in zip(s,t): if a not in S: S[a], j = j, j + 1 if b not in T: T[b], k = k, k + 1 return all([S[s[i]] == T[t[i]] for i in range(len(s))]) - Junaid Mansuri (LeetCode ID)@hotmail.com
isomorphic-strings
Solution in Python 3
junaidmansuri
1
493
isomorphic strings
205
0.426
Easy
3,418
https://leetcode.com/problems/isomorphic-strings/discuss/2847272/Python-solution-T-C-%3A-0(str1-%2B-str2)
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: if len(s)!=len(t): return False dic1 = {} dic2 = {} for i, j in zip(s ,t): if i not in dic1 and j not in dic2: dic1[i] = j dic2[j] = i elif i in dic1 and j in dic2 and dic1[i] != j and dic2[j] != i: return False elif (i in dic1 and j not in dic2) or (i not in dic1 and j in dic2): return False return True
isomorphic-strings
Python solution T-C :- 0(str1 + str2)
kartik_5051
0
2
isomorphic strings
205
0.426
Easy
3,419
https://leetcode.com/problems/isomorphic-strings/discuss/2845992/Mapping-s-and-t
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: # character map the char from string s to string t for replacement # eg "egg" -> "add"; # e->a, g->d # if this mapping doesn't match then its not an isomorphic string mapS, mapT = {}, {} for cs, ct in zip(s, t): if ((cs in mapS and mapS[cs] != ct) or (ct in mapT and mapT[ct] != cs)): return False mapS[cs], mapT[ct] = ct, cs return True
isomorphic-strings
Mapping s and t
keshan-spec
0
1
isomorphic strings
205
0.426
Easy
3,420
https://leetcode.com/problems/isomorphic-strings/discuss/2837937/Isomorphic-Strings
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: return len(set(zip(s, t))) == len(set(s)) == len(set(t))
isomorphic-strings
Isomorphic Strings
arthur54342
0
1
isomorphic strings
205
0.426
Easy
3,421
https://leetcode.com/problems/isomorphic-strings/discuss/2832077/python-oror-simple-solution-oror-hashmapdictionary
class Solution: def isIsomorphic(self, s1: str, s2: str) -> bool: def f(s: str, d: dict) -> list[int]: ans = [] # answer cnt = 0 # count of diff chars in s # go through every char in s for c in s: # if we haven't seen c yet if c not in d: # new char, add it to d d[c] = cnt cnt += 1 # add key for this char to ans ans.append(d[c]) return ans # if array for s1 and s2 are the same return f(s1, {}) == f(s2, {})
isomorphic-strings
python || simple solution || hashmap/dictionary
wduf
0
8
isomorphic strings
205
0.426
Easy
3,422
https://leetcode.com/problems/isomorphic-strings/discuss/2830649/Isomorphic-Strings-in-Python
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: f = '' d = {} if len(set(s)) == len(set(t)): for i, j in enumerate(s): d[j] = t[i] for k in s: if k in d: f+=d[k] if f == t: return True else: return False
isomorphic-strings
Isomorphic Strings in Python
prink879
0
4
isomorphic strings
205
0.426
Easy
3,423
https://leetcode.com/problems/isomorphic-strings/discuss/2828049/Python-Get-and-compare-2-signatures-based-on-new-char-ordering
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: return self.signature(s) == self.signature(t) def signature(self, s): ''' The idea is we can isomorphise 2 strings by taking their new char oder As in, for "egg" and "add", it is 101111 and 101111, where 1st char is 10, every subsequent new char is +1 and joined together we get their signature We start from 10 instead of 1 to have consistent 2-digit values for every char else fails in test: "abcdefghijklmnopqrstuvwxyzva" "abcdefghijklmnopqrstuvwxyzck" ''' mapping = {} counter = 10 signature = [] for ch in s: if ch not in mapping: mapping[ch] = str(counter) counter += 1 signature.append(mapping[ch]) return ''.join(signature)
isomorphic-strings
[Python] Get and compare 2 signatures based on new char ordering
graceiscoding
0
5
isomorphic strings
205
0.426
Easy
3,424
https://leetcode.com/problems/isomorphic-strings/discuss/2827582/Python-Solution
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: m1=dict() m2=dict() for i in range(len(s)): if(s[i] in m1.keys() and t[i] not in m2.keys()): return False if(s[i] not in m1.keys() and t[i] in m2.keys()): return False if(s[i] in m1.keys() and t[i] in m2.keys()): if(m1.get(s[i])!=t[i] or m2.get(t[i])!=s[i]): return False else: m1[s[i]]=t[i] m2[t[i]]=s[i] return True
isomorphic-strings
Python Solution
CEOSRICHARAN
0
3
isomorphic strings
205
0.426
Easy
3,425
https://leetcode.com/problems/isomorphic-strings/discuss/2819042/Python3-Solution
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: char_map = {} new_chars = set() for i, char in enumerate(s): if char not in char_map: if t[i] in new_chars: return False new_chars.add(t[i]) char_map[char] = t[i] if char_map[char] != t[i]: return False return True
isomorphic-strings
Python3 Solution
patvera1
0
6
isomorphic strings
205
0.426
Easy
3,426
https://leetcode.com/problems/isomorphic-strings/discuss/2819032/Python-My-O(n)-Solution
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: char_mapping = {} t_chars_used = set() for i, (s_char, t_char) in enumerate(zip(s,t)): if s_char in char_mapping: # fail here if previous mapping does not hold if char_mapping[s_char] != t_char: return False else: # fail here if characters mapped to the same one if t_char in t_chars_used: return False char_mapping[s_char] = t_char t_chars_used.add(t_char) return True
isomorphic-strings
[Python] My O(n) Solution
manytenks
0
4
isomorphic strings
205
0.426
Easy
3,427
https://leetcode.com/problems/isomorphic-strings/discuss/2814161/Very-simple-python-O(n)
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: _map={} for i in range(len(s)): if s[i] in _map.keys(): if (_map[s[i]] != t[i]): return False _map[s[i]]=t[i] if len(set(list(_map.values()))) != len(set(list(_map.keys()))): return False return True
isomorphic-strings
Very simple python O(n)
ATHBuys
0
4
isomorphic strings
205
0.426
Easy
3,428
https://leetcode.com/problems/isomorphic-strings/discuss/2812080/python-easy-solution
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: map_dict = {} for i,j in zip(s, t): if i not in map_dict: map_dict[i] = j elif map_dict[i] != j: return False if len(set(map_dict.keys())) != len(set(map_dict.values())): return False else: return True
isomorphic-strings
python easy solution
cool_rabbit
0
5
isomorphic strings
205
0.426
Easy
3,429
https://leetcode.com/problems/isomorphic-strings/discuss/2811844/using-set-and-zip
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: return len(set(s)) == len(set(t)) ==len(set(zip(s,t)))
isomorphic-strings
using set and zip
roger880327
0
2
isomorphic strings
205
0.426
Easy
3,430
https://leetcode.com/problems/isomorphic-strings/discuss/2807240/Solved-with-Dictionary
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: x = {} for i in range(0,len(s)): if s[i] in x: # it is in x so check if the respecting t[i] is the same value as before if x[s[i]]== t[i]: # if yesit is good means the value is repecting the scheme continue else: # value is different than its supposed to be its not isomorphic hence abort return False if t[i] in x.values(): return False else: #no such key already we can assign relation x[s[i]] = t[i] return True
isomorphic-strings
Solved with Dictionary
user6407Ay
0
3
isomorphic strings
205
0.426
Easy
3,431
https://leetcode.com/problems/isomorphic-strings/discuss/2804329/hashmap-%2B-hash-set-0(n)-time%2Bspace-99-faster-Python3
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: if len(t)!=len(s): return False map = {} invalid = set() for i,c in enumerate(s): if c not in map: if t[i] in invalid: return False map[c] = t[i] invalid.add(t[i]) else: if t[i] != map[c]: return False return True
isomorphic-strings
hashmap + hash set 0(n) time+space 99% faster Python3
iSyqozz512
0
5
isomorphic strings
205
0.426
Easy
3,432
https://leetcode.com/problems/isomorphic-strings/discuss/2801213/Python-O(n)-solution-90
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: if len(s) != len(t): return true values = set() mappy={} for i in range(len(s)): a,b = s[i],t[i] if a in mappy: if mappy[a] != b: return False else: if b in values: return False mappy[a] = b values.add(b) return True
isomorphic-strings
Python O(n) solution 90%
shreeshail
0
3
isomorphic strings
205
0.426
Easy
3,433
https://leetcode.com/problems/isomorphic-strings/discuss/2800894/Python-or-single-line
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: return len(set(s))==len(set(t))==len(set(zip(s,t)))
isomorphic-strings
Python | single line
SAI_KRISHNA_PRATHAPANENI
0
1
isomorphic strings
205
0.426
Easy
3,434
https://leetcode.com/problems/isomorphic-strings/discuss/2791890/Solution%3A-Python3-98-faster
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: comDict = {} if len(s) != len(t): return False for i in range(len(s)): if s[i] in comDict.keys(): if comDict[s[i]] != t[i]: return False else: if t[i] in comDict.values(): return False comDict[s[i]] = t[i] return True
isomorphic-strings
Solution: Python3 98% faster
wanatabeyuu
0
4
isomorphic strings
205
0.426
Easy
3,435
https://leetcode.com/problems/isomorphic-strings/discuss/2791849/Python-Easy-solution-using-Hashmap-with-explaination.
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: if len(s) != len(t): return False if len(set(s)) != len(set(t)): return False conn = {} for i in range(len(s)): if s[i] not in conn: conn[s[i]] = t[i] elif conn[s[i]] != t[i]: return False return True
isomorphic-strings
✅ Python Easy solution using Hashmap with explaination. ✅
raghupalash
0
2
isomorphic strings
205
0.426
Easy
3,436
https://leetcode.com/problems/isomorphic-strings/discuss/2786767/Python-easy-solution
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: intS = 0 listS = [] dictS = {} for char in s: if char not in dictS: dictS[char] = intS intS += 1 listS.append(dictS[char]) intT = 0 listT = [] dictT = {} for char in t: if char not in dictT: dictT[char] = intT intT += 1 listT.append(dictT[char]) if listS == listT: return True else: return False
isomorphic-strings
Python easy solution
kamman626
0
3
isomorphic strings
205
0.426
Easy
3,437
https://leetcode.com/problems/isomorphic-strings/discuss/2785865/Isomorphic-Strings-or-Easy-Python-solution
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: mapST,mapTS = {}, {} if len(s) != len(t): return False else: for i in range(len(s)): if (s[i] in mapST) and mapST[s[i]] != t[i]: return False elif (t[i] in mapTS) and mapTS[t[i]] != s[i]: return False else: mapST[s[i]] = t[i] mapTS[t[i]] = s[i] return True
isomorphic-strings
Isomorphic Strings | Easy Python solution
nishanrahman1994
0
5
isomorphic strings
205
0.426
Easy
3,438
https://leetcode.com/problems/isomorphic-strings/discuss/2769178/Simple-Python-Solution
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: n = len(s) mapping = dict() seen = set() for i in range(n): if s[i] not in mapping: if t[i] in seen: return False else: mapping[s[i]] = t[i] else: if mapping[s[i]] != t[i]: return False seen.add(t[i]) return True
isomorphic-strings
Simple Python Solution
mansoorafzal
0
7
isomorphic strings
205
0.426
Easy
3,439
https://leetcode.com/problems/isomorphic-strings/discuss/2766221/Using-maps-and-array-easy-to-understand.
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: if len(s) != len(t): return False map = {} set = [] for i in range(len(s)): if s[i] not in map: if t[i] not in set: map[s[i]] = t[i] set.append(t[i]) else: return False else: if map[s[i]] != t[i]: return False return True
isomorphic-strings
Using maps and array, easy to understand.
karanvirsagar98
0
3
isomorphic strings
205
0.426
Easy
3,440
https://leetcode.com/problems/isomorphic-strings/discuss/2751659/Solution-using-ONE-HashTable
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: map = {} if len(s) == len(t): for i in range(len(s)): if t[i] in map.values(): if s[i] not in map.keys(): return False if s[i] not in map: map[s[i]] = t[i] if t[i] != map[s[i]]: return False return True return False
isomorphic-strings
Solution using ONE HashTable
zaberraiyan
0
5
isomorphic strings
205
0.426
Easy
3,441
https://leetcode.com/problems/isomorphic-strings/discuss/2749030/Simple-Python-Solution-using-length-and-zip
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: z = zip(s, t) return len(set(s)) == len(set(z)) == len(set(t))
isomorphic-strings
Simple Python Solution using length and zip
vivekrajyaguru
0
3
isomorphic strings
205
0.426
Easy
3,442
https://leetcode.com/problems/isomorphic-strings/discuss/2747260/python-Hashmap-solution
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: # O(n), O(n) st, ts = {}, {} for c1, c2 in zip(s, t): # for i in range(len(s)): # c1, c2 = s[i], t[i] if (c1 in st and st[c1] != c2 or c2 in ts and ts[c2] != c1): return False st[c1] = c2 ts[c2] = c1 return True
isomorphic-strings
python Hashmap solution
sahilkumar158
0
4
isomorphic strings
205
0.426
Easy
3,443
https://leetcode.com/problems/isomorphic-strings/discuss/2740162/simple-Python-solution-using-Dictionary
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: s_len = len(s) t_len = len(t) if s_len != t_len: return False else: diff_dict = {} for i in range(s_len): if s[i] in diff_dict and diff_dict[s[i]] != t[i]: return False if t[i] in diff_dict.values() and s[i] not in diff_dict: return False diff_dict[s[i]] = t[i] return True
isomorphic-strings
simple Python solution, using Dictionary
don_masih
0
4
isomorphic strings
205
0.426
Easy
3,444
https://leetcode.com/problems/isomorphic-strings/discuss/2737891/easy-way-in-python
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: d={} for i in range(len(s)): if s[i] not in d: if t[i] in d.values(): return False else: d[s[i]]=t[i] else: if d[s[i]]!=t[i]: return False return True
isomorphic-strings
easy way in python
sindhu_300
0
7
isomorphic strings
205
0.426
Easy
3,445
https://leetcode.com/problems/isomorphic-strings/discuss/2716910/Short-and-easy-Python-solution-with-dictionaries
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: #check that strings are of equal length if len(s) != len(t): return False n = len(s) if n == 0: return True D_s_t, D_t_s = dict(), dict() for i in range(n): if s[i] in D_s_t.keys() and D_s_t[s[i]] != t[i]: return False else: D_s_t[s[i]] = t[i] if t[i] in D_t_s.keys() and D_t_s[t[i]] != s[i]: return False else: D_t_s[t[i]] = s[i] return True
isomorphic-strings
Short and easy Python solution with dictionaries
tatiana_ospv
0
3
isomorphic strings
205
0.426
Easy
3,446
https://leetcode.com/problems/isomorphic-strings/discuss/2712155/Python-simple-solution-using-Dictionary
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: mapST,mapTS={},{} for c1,c2 in zip(s,t): if( (c1 in mapST and mapST[c1]!=c2) or (c2 in mapTS and mapTS[c2]!=c1) ): return False mapST[c1]=c2 mapTS[c2]=c1 return True
isomorphic-strings
Python simple solution using Dictionary
Raghunath_Reddy
0
10
isomorphic strings
205
0.426
Easy
3,447
https://leetcode.com/problems/isomorphic-strings/discuss/2710776/iterative-python-method-(most-unique-solution)
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: if not len(s)==len(t): return False s = list(s) t = list(t) hash = {} a=0 for i in s: if i in hash: hash[i].append(t[a]) if i not in hash: hash[i]=list(t[a]) a +=1 for x in hash: if len(hash[x])>1: i=0 while i<len(hash[x]): if hash[x][0]!=hash[x][i]: return False i+=1 count=0 for i in hash.values(): if i ==hash[x]: count+=1 if count>1: return False counter =0 for z in hash: if set(hash[x])==set(hash[z]): counter+=1 if counter>1: return False return True
isomorphic-strings
iterative python method (most unique solution)
sahityasetu1996
0
2
isomorphic strings
205
0.426
Easy
3,448
https://leetcode.com/problems/isomorphic-strings/discuss/2685418/Pythondictionary-Easy-understanding-by-record-each-position
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: dicS = {} dicT = {} for i in range(len(s)): if s[i] not in dicS: dicS[s[i]] = [i] else: dicS[s[i]].append(i) if t[i] not in dicT: dicT[t[i]] = [i] else: dicT[t[i]].append(i) if dicS[s[i]] != dicT[t[i]]: return False return True
isomorphic-strings
[Python/dictionary] Easy understanding by record each position
Allen_Huang
0
48
isomorphic strings
205
0.426
Easy
3,449
https://leetcode.com/problems/isomorphic-strings/discuss/2675105/Isomorphic-Strings
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: MAX_CHARS = 256 n = len(s) m = len(t) if n != m: return False marked = [False] * MAX_CHARS map = [-1] * MAX_CHARS for i in range(n): if map[ord(s[i])] == -1: if marked[ord(t[i])] == True: return False marked[ord(t[i])] = True map[ord(s[i])] = t[i] elif map[ord(s[i])] != t[i]: return False return True
isomorphic-strings
Isomorphic Strings
jashii96
0
6
isomorphic strings
205
0.426
Easy
3,450
https://leetcode.com/problems/reverse-linked-list/discuss/2458632/Easy-oror-0-ms-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-JS-C-Python3-(Recursive-and-Iterative)
class Solution(object): def reverseList(self, head): # Initialize prev pointer as NULL... prev = None # Initialize the curr pointer as the head... curr = head # Run a loop till curr points to NULL... while curr: # Initialize next pointer as the next pointer of curr... next = curr.next # Now assign the prev pointer to curr’s next pointer. curr.next = prev # Assign curr to prev, next to curr... prev = curr curr = next return prev # Return the prev pointer to get the reverse linked list...
reverse-linked-list
Easy || 0 ms || 100% || Fully Explained || Java, C++, Python, JS, C, Python3 (Recursive & Iterative)
PratikSen07
92
6,800
reverse linked list
206
0.726
Easy
3,451
https://leetcode.com/problems/reverse-linked-list/discuss/2458632/Easy-oror-0-ms-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-JS-C-Python3-(Recursive-and-Iterative)
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: # Initialize prev pointer as NULL... prev = None # Initialize the curr pointer as the head... curr = head # Run a loop till curr points to NULL... while curr: # Initialize next pointer as the next pointer of curr... next = curr.next # Now assign the prev pointer to curr’s next pointer. curr.next = prev # Assign curr to prev, next to curr... prev = curr curr = next return prev # Return the prev pointer to get the reverse linked list...
reverse-linked-list
Easy || 0 ms || 100% || Fully Explained || Java, C++, Python, JS, C, Python3 (Recursive & Iterative)
PratikSen07
92
6,800
reverse linked list
206
0.726
Easy
3,452
https://leetcode.com/problems/reverse-linked-list/discuss/469204/PythonJSJavaC%2B%2B-O(n)-by-recursion-w-Comment
class Solution: def helper(self, prev, cur): if cur: # locate next hopping node next_hop = cur.next # reverse direction cur.next = prev return self.helper( cur, next_hop) else: # new head of reverse linked list return prev def reverseList(self, head: ListNode) -> ListNode: return self.helper( None, head)
reverse-linked-list
Python/JS/Java/C++ O(n) by recursion [w/ Comment]
brianchiang_tw
7
1,400
reverse linked list
206
0.726
Easy
3,453
https://leetcode.com/problems/reverse-linked-list/discuss/469204/PythonJSJavaC%2B%2B-O(n)-by-recursion-w-Comment
class Solution: def reverseList(self, head: ListNode) -> ListNode: prev, cur = None, head while cur: # locate next hoppoing node next_hop = cur.next # reverse direction cur.next = prev prev = cur cur = next_hop # new head of reverse linked list return prev
reverse-linked-list
Python/JS/Java/C++ O(n) by recursion [w/ Comment]
brianchiang_tw
7
1,400
reverse linked list
206
0.726
Easy
3,454
https://leetcode.com/problems/reverse-linked-list/discuss/642637/faster-than-95.78-in-python-or-Iterative-Solution
class Solution: def reverseList(self, head: ListNode) -> ListNode: #I will use the following head, prev, temp prev = None while head: #while head is present then this loop executes #first I will assign the value of head to the temp variable temp = head #now head can be pused to the next element head = head.next #now using temp in such a way to reverse the direction of the pointers temp.next = prev #this changes the current nodes pointer direction from right to left #now making prev come to the current node so that this same cycle can be repeated prev = temp #this temp is the old value of temp that it carried before head gave and moved away return prev
reverse-linked-list
faster than 95.78% in python | Iterative Solution
pritomlily
6
633
reverse linked list
206
0.726
Easy
3,455
https://leetcode.com/problems/reverse-linked-list/discuss/2684169/Python-2-Easy-Way-To-Reverse-Linked-List-or-99-Faster-or-Fast-and-Simple-Solution
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: curr = head prev = None while curr: next = curr.next curr.next = prev prev = curr curr = next return prev
reverse-linked-list
✔️ Python 2 Easy Way To Reverse Linked List | 99% Faster | Fast and Simple Solution
pniraj657
4
706
reverse linked list
206
0.726
Easy
3,456
https://leetcode.com/problems/reverse-linked-list/discuss/2684169/Python-2-Easy-Way-To-Reverse-Linked-List-or-99-Faster-or-Fast-and-Simple-Solution
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head: return head stack = [] temp = head while temp: stack.append(temp) temp = temp.next head = temp = stack.pop() while len(stack)>0: temp.next = stack.pop() temp = temp.next temp.next = None return head
reverse-linked-list
✔️ Python 2 Easy Way To Reverse Linked List | 99% Faster | Fast and Simple Solution
pniraj657
4
706
reverse linked list
206
0.726
Easy
3,457
https://leetcode.com/problems/reverse-linked-list/discuss/2375440/Python-Accurate-Solution-Two-Pointers-oror-Documented
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: resultNode = ListNode() # reversed list container curNode = head while curNode: keyNode = curNode # before swapping links, take the backup curNode = curNode.next # move forward current node keyNode.next = resultNode.next # reversed list chained to keyNode resultNode.next = keyNode # update the reversed list container to point to keyNode return resultNode.next
reverse-linked-list
[Python] Accurate Solution - Two Pointers || Documented
Buntynara
4
190
reverse linked list
206
0.726
Easy
3,458
https://leetcode.com/problems/reverse-linked-list/discuss/1630780/Python3-Short-and-Simple-or-In-place-O(1)-space-or-Iterative
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: prev = None while head: nextHead = head.next head.next, prev = prev, head head = nextHead return prev
reverse-linked-list
[Python3] Short & Simple | In-place O(1) space | Iterative
PatrickOweijane
4
431
reverse linked list
206
0.726
Easy
3,459
https://leetcode.com/problems/reverse-linked-list/discuss/1049857/Python3
class Solution: def reverseList(self, head: ListNode) -> ListNode: curr=head prev=None while curr: next=curr.next curr.next=prev prev=curr curr=next return prev
reverse-linked-list
Python3
samarthnehe
4
511
reverse linked list
206
0.726
Easy
3,460
https://leetcode.com/problems/reverse-linked-list/discuss/2415236/Python-Iterative%3A-Beats-99-oror-Recursive%3A-Beats-87-with-full-working-explanation
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: # Time: O(n) and Space: O(1) prev, cur = None, head while cur: # let cur 3 temp = cur.next # nxt = 4 cur.next = prev # 3 -> 2 prev = cur # prev = 3 cur = temp # 5 <- cur(4) <- 3(prev) -> 2 -> 1 -> Null return prev
reverse-linked-list
Python [Iterative: Beats 99% || Recursive: Beats 87%] with full working explanation
DanishKhanbx
3
311
reverse linked list
206
0.726
Easy
3,461
https://leetcode.com/problems/reverse-linked-list/discuss/2415236/Python-Iterative%3A-Beats-99-oror-Recursive%3A-Beats-87-with-full-working-explanation
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: # Time: O(n) and Space: O(n) if head == None or head.next == None: # head = 2 &amp; 2 -> 3 return head newHead = self.reverseList(head.next) # newHead = Func(head=3) returns head = 3 head.next.next = head # head.next = 3 &amp; 3.next = 2 head.next = None # 2.next = None return newHead # returns newHead = 3 to when head = 1, and so on
reverse-linked-list
Python [Iterative: Beats 99% || Recursive: Beats 87%] with full working explanation
DanishKhanbx
3
311
reverse linked list
206
0.726
Easy
3,462
https://leetcode.com/problems/reverse-linked-list/discuss/1767848/Python-Simple-Python-Solution-Using-Iterative-Approach-With-While-Loop
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: current_node = head previous_node = None while current_node != None: next_node = current_node.next current_node.next = previous_node previous_node = current_node current_node = next_node return previous_node
reverse-linked-list
[ Python ] ✔✔ Simple Python Solution Using Iterative Approach With While Loop 🔥✌
ASHOK_KUMAR_MEGHVANSHI
3
228
reverse linked list
206
0.726
Easy
3,463
https://leetcode.com/problems/reverse-linked-list/discuss/2299710/Very-simple-python-solution
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: ans = None while head: ans = ListNode(head.val, ans) head = head.next return ans
reverse-linked-list
Very simple python solution
IshanKute
2
321
reverse linked list
206
0.726
Easy
3,464
https://leetcode.com/problems/reverse-linked-list/discuss/2249495/206.-My-Python-Solution
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: rev = None while head: temp = rev rev = head head = head.next rev.next = temp return rev
reverse-linked-list
206. My Python Solution
JunyiLin
2
130
reverse linked list
206
0.726
Easy
3,465
https://leetcode.com/problems/reverse-linked-list/discuss/2249495/206.-My-Python-Solution
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: rev = None return self.__reverse(head, rev) def __reverse(self, head, rev): if not head: return rev temp = rev rev = head head = head.next rev.next = temp return self.__reverse(head, rev)
reverse-linked-list
206. My Python Solution
JunyiLin
2
130
reverse linked list
206
0.726
Easy
3,466
https://leetcode.com/problems/reverse-linked-list/discuss/1987977/Python-easiest-recursion-O(n)
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: def helper(head): if not head.next: self.final = head return head # At the penultimate note, below will return the last node next_ = helper(head.next) # reversal happens here next_.next = head return head if not head: return None head = helper(head) head.next = None return self.final
reverse-linked-list
Python easiest recursion O(n)
diet_pepsi
2
293
reverse linked list
206
0.726
Easy
3,467
https://leetcode.com/problems/reverse-linked-list/discuss/1946364/Python-Solution-or-Iterative-or-Recursion-or-O(n)
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: # Two pointer solution itertaively where T O(n) and M O(1) prev, curr = None, head while curr: temp = curr.next curr.next = prev prev = curr curr = temp return prev
reverse-linked-list
Python Solution | Iterative | Recursion | O(n)
nikhitamore
2
229
reverse linked list
206
0.726
Easy
3,468
https://leetcode.com/problems/reverse-linked-list/discuss/1946364/Python-Solution-or-Iterative-or-Recursion-or-O(n)
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: #recursive T O(n) and M O(n) if not head: return None newHead = head if head.next: newHead = self.reverseList(head.next) head.next.next = head head.next = None return newHead
reverse-linked-list
Python Solution | Iterative | Recursion | O(n)
nikhitamore
2
229
reverse linked list
206
0.726
Easy
3,469
https://leetcode.com/problems/reverse-linked-list/discuss/1380420/Python3-faster-than-99.95
class Solution: def reverseList(self, head: ListNode) -> ListNode: if head is None or head.next is None: return head cur = head prev = None while cur is not None: p1 = cur cur = cur.next p1.next = prev prev = p1 return prev
reverse-linked-list
Python3 - faster than 99.95%
CC_CheeseCake
2
203
reverse linked list
206
0.726
Easy
3,470
https://leetcode.com/problems/reverse-linked-list/discuss/2314942/Python-solution-using-two-pointer-or-Reverse-Linked-List
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: prevNode, currNode = None, head while currNode: nextNode = currNode.next currNode.next = prevNode prevNode = currNode currNode = nextNode return prevNode
reverse-linked-list
Python solution using two pointer | Reverse Linked List
nishanrahman1994
1
192
reverse linked list
206
0.726
Easy
3,471
https://leetcode.com/problems/reverse-linked-list/discuss/2128833/Python3-Solution
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head or not head.next:#判断为空或长度为1时的情况 return head last = self.reverseList(head.next) #迭代的含义就是使head不停的前进,做reverse head.next.next = head # head.next = None # 调整None的位置 为反转后的链表补None return last
reverse-linked-list
Python3 Solution
qywang
1
80
reverse linked list
206
0.726
Easy
3,472
https://leetcode.com/problems/reverse-linked-list/discuss/2128833/Python3-Solution
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: rever = None while head: nextnode = head.next head.next = rever rever = head head = nextnode return rever
reverse-linked-list
Python3 Solution
qywang
1
80
reverse linked list
206
0.726
Easy
3,473
https://leetcode.com/problems/reverse-linked-list/discuss/1977436/Python3-Runtime%3A-43ms-66.97-memory%3A-15.5mb-57.44
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head: return head prev = None current = head while current is not None: next = current.next current.next = prev prev = current current = next head = prev return head
reverse-linked-list
Python3 Runtime: 43ms 66.97% memory: 15.5mb 57.44%
arshergon
1
100
reverse linked list
206
0.726
Easy
3,474
https://leetcode.com/problems/reverse-linked-list/discuss/1977436/Python3-Runtime%3A-43ms-66.97-memory%3A-15.5mb-57.44
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head: return head stack = [] current = head while current is not None: stack.append(current.val) current = current.next newCurrentNode = head while len(stack) > 0: nodeValue = stack.pop() newCurrentNode.val = nodeValue newCurrentNode = newCurrentNode.next return head
reverse-linked-list
Python3 Runtime: 43ms 66.97% memory: 15.5mb 57.44%
arshergon
1
100
reverse linked list
206
0.726
Easy
3,475
https://leetcode.com/problems/reverse-linked-list/discuss/1926119/Python-Simple-Elegant-Iterative-Solution-Memory-Less-Than-94.93-With-Comments
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: # prev will be the new head # curr used so we don't manipulate head prev, curr = None, head while curr: # To place current here after each proccesing temp = curr.next # reverse link direction curr.next = prev # move prev step ahead to repeat the process prev = curr # move curr step ahead to repeat the process curr = temp # return prev as it's point to the first element # Don't return head or curr they are standing at Null value return prev
reverse-linked-list
Python Simple Elegant Iterative Solution Memory Less Than 94.93%, With Comments,
Hejita
1
87
reverse linked list
206
0.726
Easy
3,476
https://leetcode.com/problems/reverse-linked-list/discuss/1510577/Python-or-Recursive-24-ms-or-Iterative-32-ms-or-Extra-List-28-ms
class Solution: def reverseList(self, head): if not head or not head.next: return head def rec(node): global new_head if not node.next: new_head = node return new_head rec(node.next).next = node return node rec(head) head.next = None return new_head
reverse-linked-list
Python | Recursive 24 ms | Iterative 32 ms | Extra List 28 ms
ocancemal1996
1
327
reverse linked list
206
0.726
Easy
3,477
https://leetcode.com/problems/reverse-linked-list/discuss/1510577/Python-or-Recursive-24-ms-or-Iterative-32-ms-or-Extra-List-28-ms
class Solution: def reverseList(self, head): if not head or not head.next: return head left = head right = head.next while left and right: right.next, left = left, right.next if left and right: left.next, right = right, left.next head.next = None return left or right
reverse-linked-list
Python | Recursive 24 ms | Iterative 32 ms | Extra List 28 ms
ocancemal1996
1
327
reverse linked list
206
0.726
Easy
3,478
https://leetcode.com/problems/reverse-linked-list/discuss/1510577/Python-or-Recursive-24-ms-or-Iterative-32-ms-or-Extra-List-28-ms
class Solution: def reverseList(self, head): if not head or not head.next: return head temp = head node_list = [] while temp: node_list.append(temp) temp = temp.next node_list[0].next = None for idx, node in enumerate(node_list[1:]): node.next = node_list[idx] return node_list[-1]
reverse-linked-list
Python | Recursive 24 ms | Iterative 32 ms | Extra List 28 ms
ocancemal1996
1
327
reverse linked list
206
0.726
Easy
3,479
https://leetcode.com/problems/reverse-linked-list/discuss/407408/Python-Easy-solution
class Solution: def reverseList(self, head: ListNode) -> ListNode: a = [] temp = head if not temp: return None while(temp): a.append(temp.val) temp = temp.next a = a[::-1] head = ListNode(a[0]) temp = head for i in range(1,len(a)): temp.next = ListNode(a[i]) temp = temp.next return head
reverse-linked-list
Python Easy solution
saffi
1
605
reverse linked list
206
0.726
Easy
3,480
https://leetcode.com/problems/reverse-linked-list/discuss/2834118/python-oror-simple-solution-oror-iterative
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: # if linkedlist empty or only one node if (not head) or (not head.next): return head # previous node, next node prev = next = None # iterate through list while head: # store next node next = head.next # set cur next node to previous node head.next = prev # set previous node to cur node prev = head # next node head = next return prev
reverse-linked-list
python || simple solution || iterative
wduf
0
6
reverse linked list
206
0.726
Easy
3,481
https://leetcode.com/problems/reverse-linked-list/discuss/2813071/python3-solution-with-simple-explanation
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: prev = None while head: head.next,head,prev = prev,head.next,head return prev
reverse-linked-list
python3 solution with simple explanation
pardunmeplz
0
4
reverse linked list
206
0.726
Easy
3,482
https://leetcode.com/problems/course-schedule/discuss/1627381/Simple-and-Easy-Topological-Sorting-code-beats-97.63-python-submissions
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: graph=defaultdict(list) indegree={} #initialising dictionary for i in range(numCourses): indegree[i]=0 #filling graph and indegree dictionaries for child,parent in prerequisites: graph[parent].append(child) indegree[child]+=1 queue=deque() for key,value in indegree.items(): if value==0: queue.append(key) courseSequence=[] while queue: course=queue.popleft() courseSequence.append(course) for neighbour in graph[course]: indegree[neighbour]-=1 if indegree[neighbour]==0: queue.append(neighbour) return len(courseSequence)==numCourses:
course-schedule
Simple and Easy Topological Sorting code, beats 97.63% python submissions
RaghavGupta22
11
1,400
course schedule
207
0.454
Medium
3,483
https://leetcode.com/problems/course-schedule/discuss/1802039/Python-Iterative-DFS
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: graph = { courseNum : [] for courseNum in range(numCourses) } for course, prerequisite in prerequisites: graph[course].append(prerequisite) Course = namedtuple('Course', ['number', 'backtrack']) for courseNum in range(numCourses): currCourse = Course(courseNum, False) stack = [currCourse] visited = set([currCourse.number]) while stack: currCourse = stack.pop() if currCourse.backtrack: graph[currCourse.number] = [] visited.discard(currCourse.number) continue stack.append(Course(currCourse.number, True)) visited.add(currCourse.number) for prereqCourseNum in graph[currCourse.number]: if prereqCourseNum in visited: return False stack.append(Course(prereqCourseNum, False)) return True
course-schedule
Python Iterative DFS
Rush_P
2
318
course schedule
207
0.454
Medium
3,484
https://leetcode.com/problems/course-schedule/discuss/1546562/Python3-Commented-Khans-Algorithm-code-85-Speed
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: #Data Structures and Variables in_degree = [0] * numCourses adj_list = [[] for x in range(numCourses)] queue = [] counter = 0 #building in_degree list and adj_list for course, prereq in prerequisites: in_degree[course] += 1 adj_list[prereq].append(course) #enqueing nodes with no dependencies for i in range(numCourses): if in_degree[i] == 0: queue.append(i) #Khans Algorithm #Remove Nodes without dependencies and decrement the in-degrees of the nodes #in their adj_list while(queue != []): node = queue.pop(0) counter += 1 for dependent in adj_list[node]: in_degree[dependent] += -1 if in_degree[dependent] == 0: queue.append(dependent) #check for cycle if counter != numCourses: return False return True
course-schedule
Python3- Commented Khans Algorithm code - 85% Speed
17pchaloori
2
206
course schedule
207
0.454
Medium
3,485
https://leetcode.com/problems/course-schedule/discuss/2642520/Python-DFS-a-stack-dict-and-visited-array
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: courseGraph = [[] for _ in range(numCourses)] for ai, bi in prerequisites: courseGraph[ai].append(bi) visited = [False] * numCourses stack = defaultdict(bool) for c in range(numCourses): if not self.process(c, courseGraph, visited, stack): return False return True def process(self, c, courseGraph, visited, stack): if stack[c]: # if present in running stack, it's a cycle return False stack[c] = True # add to running stack for prereq in courseGraph[c]: if visited[prereq] == True: # if this pre-req is already visited True, then it was fully processed in the past and no cycle going down this path, so we can skip now. continue if not self.process(prereq, courseGraph, visited, stack): return False stack[c] = False # remove from running stack visited[c] = True # mark it visited True when it is fully processed return True
course-schedule
Python DFS, a stack dict and visited array
hellboy11
1
263
course schedule
207
0.454
Medium
3,486
https://leetcode.com/problems/course-schedule/discuss/2505782/Python-Solution-using-DFS
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: #map each course with preq list preMap = {i : [] for i in range(numCourses)} for crs, preq in prerequisites: preMap[crs].append(preq) #visitSet visitSet = set() def dfs(crs): #found loop if crs in visitSet: return False # no prerequisites if preMap[crs] == []: return True visitSet.add(crs) for pre in preMap[crs]: if not dfs(pre): return False visitSet.remove(crs) preMap[crs] = [] # to set it true and skip the operation mentioned above return True for crs in range(numCourses): if not dfs(crs): return False return True
course-schedule
Python Solution using DFS
nikhitamore
1
88
course schedule
207
0.454
Medium
3,487
https://leetcode.com/problems/course-schedule/discuss/2318527/Python-DFS-Beats-92-with-full-working-explanation
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: # Time: O(Nodes(V) + Edges(prerequisites)) and Space: O(V + E) preMap = {i: [] for i in range(numCourses)} # init hashmap for storing course as a key for prerequisite as values for crs, pre in prerequisites: preMap[crs].append(pre) visitSet = set() # use it to find if there exists a cycle in the graph, if a crs pre is already in the set loop exits def dfs(crs): if crs in visitSet: # it states there is a cycle return False if preMap[crs] == []: # no further courses based on this course and already learned the prerequisite courses, so we can finally learn it now return True visitSet.add(crs) for pre in preMap[crs]:# values at key if not dfs(pre): # when dfs returns True, if loop will exit return False visitSet.remove(crs) # we will remove the course after studying its prerequisites and itself preMap[crs] = [] # indicates we studied all the prerequisites required for the course crs return True for crs in range(numCourses): # we will check for each course at a time if not dfs(crs): # when dfs returns true it will become false and will return true return False return True
course-schedule
Python [DFS / Beats 92%] with full working explanation
DanishKhanbx
1
141
course schedule
207
0.454
Medium
3,488
https://leetcode.com/problems/course-schedule/discuss/2117700/simple-iterative-dfs
class Solution: def canFinish(self, numCourses: int, req: List[List[int]]) -> List[int]: courses = [[] for _ in range(numCourses)] for c, pre in req: courses[c].append(pre) visiting = {} for i in range(numCourses): if visiting.get(i,0)==0: stack = [i] while(stack): node = stack[-1] if visiting.get(node, 0)==-1: stack.pop() visiting[node]=1 continue visiting[node] = -1 for course in courses[node]: if visiting.get(course, 0)==-1: return False if visiting.get(course,0)==0: stack.append(course) return True
course-schedule
simple iterative dfs
gabhinav001
1
60
course schedule
207
0.454
Medium
3,489
https://leetcode.com/problems/course-schedule/discuss/2000011/Python3-Runtime%3A-136ms-49.50-Memory%3A-17mb-34.96
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: reqMap = {i:[] for i in range(numCourses)} for crs, pre in prerequisites: reqMap[crs].append(pre) visited = set() def dfs(crs): if crs in visited: return False if reqMap[crs] == []: return True visited.add(crs) for pre in reqMap[crs]: if not dfs(pre): return False reqMap[crs] = [] visited.remove(crs) return True for pre in range(numCourses): if not dfs(pre): return False return True
course-schedule
Python3 Runtime: 136ms 49.50% Memory: 17mb 34.96%
arshergon
1
64
course schedule
207
0.454
Medium
3,490
https://leetcode.com/problems/course-schedule/discuss/1768311/Python3-solution-or-DFS-or-commmented
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: def dfs(graph, node, been): if not graph[node]: return False if node in been: return True # cycle detected been.add(node) for n in graph[node]: if dfs(graph, n, been): return True graph[node] = [] # this node leads to a dead end and not a cycle return False graph = {} if not prerequisites: return True for i in range(numCourses): if i not in graph: graph[i] = [] for i in range(len(prerequisites)): # building our graph graph[prerequisites[i][0]].append(prerequisites[i][1]) for i in range(numCourses): # finding a cycle in our graph means that it's impossible to attend at the both courses since they are linked to eachother | example: been = set() # first A than B and at the same time first B than A if dfs(graph, i, been): return False return True
course-schedule
Python3 solution | DFS | commmented
FlorinnC1
1
224
course schedule
207
0.454
Medium
3,491
https://leetcode.com/problems/course-schedule/discuss/1672351/Python3-BFS-97-or-Detailed-Explained-or-Beginner-Friendly
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: # init DAG: Course pre -> Course d = defaultdict(list) # indegree list: there are # courses as pre-requisites for takign Course A indeg = [0] * numCourses # c: course; p: pre for course for c, p in prerequisites: d[p].append(c) # p -> c will increase the indegree of c indeg[c] += 1 # BFS queue: enque all the 0 indegree courses q = deque([i for i, x in enumerate(indeg) if x == 0]) # milestone check, good habit # print(q) # learning path ans = [] while q: cur = q.popleft() # add it to our learning path ans.append(cur) # apply BFS to cur can yield the affected courses, decrease their indegree by 1 for c in d[cur]: indeg[c] -= 1 # if the indegree reach 0, enque if indeg[c] == 0: q.append(c) # print(ans) return len(ans) == numCourses
course-schedule
Python3 BFS 97% | Detailed Explained | Beginner Friendly
doneowth
1
188
course schedule
207
0.454
Medium
3,492
https://leetcode.com/problems/course-schedule/discuss/1394342/Clear-Python3-DFS-Solution-using-DFS-template-98-time
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: """ >>> sol = Solution() >>> numCourses = 2 >>> prerequisites = [[1,0]] >>> sol.canFinish(numCourses, prerequisites) True >>> numCourses = 2 >>> prerequisites = [[1,0],[0,1]] >>> sol.canFinish(numCourses, prerequisites) False """ # return False if cycle detected # produce adjacency list first adj_list = [set() for i in range(numCourses)] for i, j in prerequisites: # the prerequisite of j is i adj_list[j].add(i) # initialization # state: 0 undiscoved, 1 discovered, 2 processed state = [0] * numCourses finished = False def dfs(ls, u): nonlocal finished # terminate if finished: return # update the state state[u] = 1 # loop adjacent edges of u for e in ls[u]: # case: undiscovered, dfs if state[e] == 0: dfs(ls, e) # case: discovered, back edge found, cycle detected elif state[e] == 1: finished = True # terminate if finished: return # visited all adj vertices state[u] = 2 for i in range(numCourses): if state[i] == 0 and not finished: dfs(adj_list, i) return not finished
course-schedule
Clear Python3 DFS Solution using DFS template 98% time
alfrednerd
1
144
course schedule
207
0.454
Medium
3,493
https://leetcode.com/problems/course-schedule/discuss/1364906/Straightforward-%2B-Clean-Python
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: preqs = collections.defaultdict(set) graph = collections.defaultdict(set) for c, p in prerequisites: preqs[c].add(p) graph[c].add(p) graph[p].add(c) taken = set() q = collections.deque([]) for i in range(numCourses): if not preqs[i]: q.append(i) while q: c = q.popleft() taken.add(c) if len(taken) == numCourses: return True for cr in graph[c]: if c in preqs[cr]: preqs[cr].remove(c) if cr not in taken and not preqs[cr]: q.append(cr) return False
course-schedule
Straightforward + Clean Python
Pythagoras_the_3rd
1
166
course schedule
207
0.454
Medium
3,494
https://leetcode.com/problems/course-schedule/discuss/658915/Python3-topological-sort
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: graph = {} # digraph for u, v in prerequisites: graph.setdefault(v, []).append(u) def fn(x): """Return True if cycle is detected.""" if visited[x]: return visited[x] == 1 visited[x] = 1 for xx in graph.get(x, []): if fn(xx): return True visited[x] = 2 return False visited = [0]*numCourses for x in range(numCourses): if fn(x): return False return True
course-schedule
[Python3] topological sort
ye15
1
216
course schedule
207
0.454
Medium
3,495
https://leetcode.com/problems/course-schedule/discuss/658915/Python3-topological-sort
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: indeg = [0]*numCourses graph = {} for u, v in prerequisites: indeg[u] += 1 graph.setdefault(v, []).append(u) stack = [i for i, x in enumerate(indeg) if not x] ans = [] while stack: x = stack.pop() ans.append(x) for xx in graph.get(x, []): indeg[xx] -= 1 if indeg[xx] == 0: stack.append(xx) return len(ans) == numCourses
course-schedule
[Python3] topological sort
ye15
1
216
course schedule
207
0.454
Medium
3,496
https://leetcode.com/problems/course-schedule/discuss/2825170/Course-Schedule-DFS
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: #create a graph based on prerequisites graph = self.buildGraph(numCourses,prerequisites) #record visited nodes, record nodes in path self.visited = [False]*numCourses self.path = [False]*numCourses self.hasCycle = False #if the graph has a graph,then cannot learn all courses #start to traverse every class to see if exists cycle for v in range(numCourses): self.traverse(v,graph) return not self.hasCycle def traverse(self,v,graph): #if v is in path, then its a cycle if self.path[v]: self.hasCycle = True #if there is a cycle or v is already visited/learned, return if self.hasCycle or self.visited[v]: return #add v to visit &amp; path self.visited[v] = True self.path[v] = True #traverse classes that use v as prerequisite for w in graph[v]: self.traverse(w,graph) #end traverse v self.path[v] = False def buildGraph(self,numCourses,prerequisites): graph = [[] for _ in range(numCourses)] for prerequisite in prerequisites: #means if you need to learn a, need to learn b first: b-->a a = prerequisite[0] b = prerequisite[1] graph[b].append(a) return graph
course-schedule
Course Schedule DFS
Romantic_taxi_driver
0
5
course schedule
207
0.454
Medium
3,497
https://leetcode.com/problems/course-schedule/discuss/2815458/Python-Error-(Dictionary-changes-size-during-iteration)-Requires-Assistance
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: adjList = defaultdict(list) courses = {} for course, prereq in prerequisites: adjList[course].append(prereq) def dfs(course): if course in courses: return courses[course] courses[course] = False for prereq in adjList[course]: if not dfs(prereq): return False courses[course] = True return True for course in adjList: if course not in courses: if not dfs(course): return False return True
course-schedule
Python Error (Dictionary changes size during iteration) - Requires Assistance
BENJI_GAO
0
4
course schedule
207
0.454
Medium
3,498
https://leetcode.com/problems/course-schedule/discuss/2815409/Python-solution
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: # 0: Unchecked, 1:Checking, 2:Completed Status = [0] * numCourses Prerequisite = defaultdict(list) for cur, pre in prerequisites: Prerequisite[cur].append(pre) def CompleteTheCourse(num): if Status[num] == 2: return True elif Status[num] == 1: return False Status[num] = 1 for pre in Prerequisite[num]: if not CompleteTheCourse(pre): return False Status[num] = 2 return True for i in range(numCourses): if not CompleteTheCourse(i): return False return True
course-schedule
Python solution
maomao1010
0
9
course schedule
207
0.454
Medium
3,499