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/longest-palindromic-substring/discuss/2288241/simple-python-dp | class Solution:
def longestPalindrome(self, s):
longest_palindrome = ''
dp = [[0] * len(s) for _ in range(len(s))]
for i in range(len(s)):
dp[i][i] = True
longest_palindrome = s[i]
for i in range(len(s) - 1, -1, -1):
for j in range(i + 1, len(s)):
print("i: %d, j: %d" % (i,j))
if s[i] == s[j]: # if the chars mathces
if j - i == 1 or dp[i + 1][j - 1] is True:
dp[i][j] = True
if len(longest_palindrome) < len(s[i:j + 1]):
longest_palindrome = s[i:j + 1]
return longest_palindrome | longest-palindromic-substring | simple python dp | gasohel336 | 1 | 448 | longest palindromic substring | 5 | 0.324 | Medium | 200 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2251262/python3-oror-easy-oror-solution | class Solution:
def longestPalindrome(self, s: str) -> str:
res=""
resLen=0
finalLeftIndex=0
finalRightIndex=0
for i in range(len(s)):
#for odd length of palindromes
l,r=i,i
while l>=0 and r<len(s) and s[l]==s[r]:
if (r-l+1)>resLen:
# res=s[l:r+1]
finalLeftIndex=l
finalRightIndex=r+1
resLen=r-l+1
l-=1
r+=1
#for even length of palindromes
l,r=i,i+1
while l>=0 and r<len(s) and s[l]==s[r]:
if (r-l+1)>resLen:
# res=s[l:r+1]
finalLeftIndex=l
finalRightIndex=r+1
resLen=r-l+1
l-=1
r+=1
return s[finalLeftIndex:finalRightIndex] | longest-palindromic-substring | python3 || easy || solution | _soninirav | 1 | 231 | longest palindromic substring | 5 | 0.324 | Medium | 201 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2156912/Python3-or-Very-Easy-to-Understand-or-simple-approach | class Solution:
def longestPalindrome(self, s: str) -> str:
res = ''
n = len(s)
mxlen = 0
for i in range(n):
for j in range(max(i+1, i+mxlen), n+1):
if s[i]==s[j-1]:
sub = s[i: j]
if sub == sub[::-1] and len(sub)>len(res):
res=sub
mxlen = len(res)
return res | longest-palindromic-substring | Python3 | Very Easy to Understand | simple approach | H-R-S | 1 | 62 | longest palindromic substring | 5 | 0.324 | Medium | 202 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/1861817/Simple-Python-Solution-oror-85-Faster-oror-Memory-less-than-99 | class Solution:
def longestPalindrome(self, s: str) -> str:
def get_palindrome(s,l,r):
while l>=0 and r<len(s) and s[l]==s[r]: l-=1 ; r+=1
return s[l+1:r]
ans=''
for i in range(len(s)):
ans1=get_palindrome(s,i,i) ; ans2=get_palindrome(s,i,i+1)
ans=max([ans,ans1,ans2], key=lambda x:len(x))
return ans | longest-palindromic-substring | Simple Python Solution || 85% Faster || Memory less than 99% | Taha-C | 1 | 348 | longest palindromic substring | 5 | 0.324 | Medium | 203 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/1761378/Python-3-Expand-from-center | class Solution:
def longestPalindrome(self, s: str) -> str:
longest = 0
sub = ''
def expand(left, right):
nonlocal longest, sub
while left >= 0 and right < len(s) and s[left] == s[right]:
length = right-left+1
if length > longest:
longest = length
sub = s[left:right+1]
left -= 1
right += 1
for i in range(len(s)):
expand(i, i)
expand(i, i+1)
return sub | longest-palindromic-substring | [Python 3] Expand from center | leet4ever | 1 | 230 | longest palindromic substring | 5 | 0.324 | Medium | 204 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/1471768/PyPy3-Simple-solution-w-comments | class Solution:
def longestPalindrome(self, s: str) -> str:
# Check if a string is palindrome
# within the given index i to j
def isPal(s,i,j):
while i < j:
if s[i] != s[j]:
break
i += 1
j -= 1
else:
return True
return False
# Init
p = (0,0) # Portion of the string to be checked as palindrome
n = len(s)
# Base Case
if n == 1:
return s
# Base Case
if isPal(s,0,n-1):
return s
# For all other case
for j in range(n):
# Start from the begining
i = 0
# While current index i is less than
# end index j
while i < j:
# Check for palindrome only if
# first and last character of a portion
# of the string is similar
if s[i] == s[j]:
# Check if size of the current portion is
# greater then the last max palindrome string.
# Then check if this portion is palindrome.
# Update the portion with current indexes
if (p[1] - p[0]) < (j-i) and isPal(s,i,j):
p = (i,j)
i += 1
# Return the longest protion of the string found to be palindrome
return s[p[0]:p[1]+1] | longest-palindromic-substring | [Py/Py3] Simple solution w/ comments | ssshukla26 | 1 | 665 | longest palindromic substring | 5 | 0.324 | Medium | 205 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/756544/Simple-Python-code-oror-Faster-than-70.29-of-Python3 | class Solution:
def longestPalindrome(self, s: str) -> str:
answer = ""
for i in range(len(s)):
odd = self.palindrome(s, i, i)
even = self.palindrome(s, i, i+1)
large = odd if len(odd) > len(even) else even
answer = large if len(large) >= len(answer) else answer
return answer
def palindrome(self, s, left, right):
IndexL = 0
IndexR = 0
while left >= 0 and right < len(s):
if s[left] == s[right]:
IndexL = left
IndexR = right
else:
break
left -= 1
right += 1
return s[IndexL: IndexR+1] | longest-palindromic-substring | Simple Python code || Faster than 70.29% of Python3 | dharmakshii | 1 | 439 | longest palindromic substring | 5 | 0.324 | Medium | 206 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/249433/My-simple-and-easy-understanding-DP-Python-solution | class Solution:
def longestPalindrome(self, s: str) -> str:
length = len(s)
dp = {}
max_len = 1
start = 0
for _len in range(2, length + 1):
i = 0
while i <= length - _len:
j = i + _len - 1
if _len <= 3:
dp[(i, j)] = s[i] == s[j]
elif s[i] == s[j]:
dp[(i, j)] = dp[(i + 1, j - 1)]
else:
dp[(i, j)] = False
if dp[(i, j)] and _len > max_len:
max_len = _len
start = i
i += 1
return s[start:start + max_len] | longest-palindromic-substring | My simple and easy understanding DP Python solution | mazheng | 1 | 802 | longest palindromic substring | 5 | 0.324 | Medium | 207 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/249433/My-simple-and-easy-understanding-DP-Python-solution | class Solution:
def longestPalindrome(self, s: str) -> str:
length = len(s)
dp = {}
max_len = 1
start = 0
for _len in range(2, length + 1):
i = 0
while i <= length - _len:
j = i + _len - 1
if _len <= 3 and s[i] == s[j]:
dp[(i, j)] = True
if _len > max_len:
max_len = _len
start = i
elif s[i] == s[j] and dp.get((i + 1, j - 1)):
dp[(i, j)] = True
if _len > max_len:
max_len = _len
start = i
i += 1
return s[start:start + max_len] | longest-palindromic-substring | My simple and easy understanding DP Python solution | mazheng | 1 | 802 | longest palindromic substring | 5 | 0.324 | Medium | 208 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/249433/My-simple-and-easy-understanding-DP-Python-solution | class Solution:
def longestPalindrome(self, s: str) -> str:
length = len(s)
dp = {}
max_len = 1
start = 0
for _len in range(2, length + 1):
i = 0
while i <= length - _len:
j = i + _len - 1
if (_len <= 3 and s[i] == s[j]) or (s[i] == s[j] and dp.get((i + 1, j - 1))):
dp[(i, j)] = True
if _len > max_len:
max_len = _len
start = i
i += 1
return s[start:start + max_len] | longest-palindromic-substring | My simple and easy understanding DP Python solution | mazheng | 1 | 802 | longest palindromic substring | 5 | 0.324 | Medium | 209 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2845651/Python | class Solution:
def longestPalindrome(self, s: str) -> str:
if not s:
return ''
def extend(s:str, i:int, j:int) -> Tuple[int, int]:
while i>=0 and j < len(s):
if s[i] != s[j]:
break
i -= 1
j += 1
return i+1, j-1
indices = [0,0]
for i in range(len(s)):
l1, r1 = extend(s, i, i)
if r1-l1 > indices[1] - indices[0]:
indices = l1, r1
if i+1 < len(s) and s[i]== s[i+1]:
l2, r2 = extend(s, i, i+1)
if r2-l2 > indices[1] - indices[0]:
indices = l2, r2
return s[indices[0]:indices[1]+1] | longest-palindromic-substring | Python | Kishore1K | 0 | 2 | longest palindromic substring | 5 | 0.324 | Medium | 210 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2840979/Manacher's-Algorithm-oror-Python-oror-Beats-98-oror-O(n)-time | class Solution:
def longestPalindrome(self, text: str) -> str:
N = len(text)
if N == 0:
return
if N == 1:
return text
N = 2*N+1 # Position count
L = [0] * N
L[0] = 0
L[1] = 1
C = 1 # centerPosition
R = 2 # centerRightPosition
i = 0 # currentRightPosition
iMirror = 0 # currentLeftPosition
maxLPSLength = 0
maxLPSCenterPosition = 0
start = -1
end = -1
diff = -1
for i in range(2,N):
# get currentLeftPosition iMirror for currentRightPosition i
iMirror = 2*C-i
L[i] = 0
diff = R - i
# If currentRightPosition i is within centerRightPosition R
if diff > 0:
L[i] = min(L[iMirror], diff)
# Attempt to expand palindrome centered at currentRightPosition i
# Here for odd positions, we compare characters and
# if match then increment LPS Length by ONE
# If even position, we just increment LPS by ONE without
# any character comparison
try:
while ((i + L[i]) < N and (i - L[i]) > 0) and \
(((i + L[i] + 1) % 2 == 0) or \
(text[(i + L[i] + 1) // 2] == text[(i - L[i] - 1) // 2])):
L[i]+=1
except Exception as e:
pass
if L[i] > maxLPSLength: # Track maxLPSLength
maxLPSLength = L[i]
maxLPSCenterPosition = i
# If palindrome centered at currentRightPosition i
# expand beyond centerRightPosition R,
# adjust centerPosition C based on expanded palindrome.
if i + L[i] > R:
C = i
R = i + L[i]
# Uncomment it to print LPS Length array
# printf("%d ", L[i]);
start = (maxLPSCenterPosition - maxLPSLength) // 2
end = start + maxLPSLength - 1
return text[start:end+1] | longest-palindromic-substring | Manacher’s Algorithm || Python || Beats 98% || O(n) time | joetrankang | 0 | 5 | longest palindromic substring | 5 | 0.324 | Medium | 211 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2838180/Python-On2-solution-very-simple. | class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
res = ''
def find(i, j):
nonlocal res
while 0<=i<n and 0<=j<n:
ss = s[i: j+1]
if ss == ss[::-1]:
if len(ss) > len(res):
res = ss
i -= 1
j += 1
else:
break
for i in range(n):
find(i, i)
find(i, i+1)
return res | longest-palindromic-substring | Python On2 solution - very simple. | florinbasca | 0 | 7 | longest palindromic substring | 5 | 0.324 | Medium | 212 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2827771/Python-(Simple-Maths) | class Solution:
def is_palindrome(self,s,left,right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return s[left+1:right]
def longestPalindrome(self, s):
ans = []
for i in range(len(s)):
ans.append(self.is_palindrome(s,i,i))
ans.append(self.is_palindrome(s,i,i+1))
return max(ans, key = len) | longest-palindromic-substring | Python (Simple Maths) | rnotappl | 0 | 6 | longest palindromic substring | 5 | 0.324 | Medium | 213 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2825598/Python%3A-tracking-character-positions | class Solution:
def longestPalindrome(self, s: str) -> str:
positions = dict()
palindrome = s[0]
for j, char in enumerate(s):
if char in positions:
for i in positions[char]:
if (j - i + 1) <= len(palindrome):
break
candidate = s[i : j+1]
if candidate == candidate[::-1]:
palindrome = candidate
break
positions[char].append(j)
else:
positions[char] = [j]
return palindrome | longest-palindromic-substring | Python: tracking character positions | kwabenantim | 0 | 6 | longest palindromic substring | 5 | 0.324 | Medium | 214 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2825598/Python%3A-tracking-character-positions | class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
isPalindrome = [[False] * n for _ in range(n)]
for i in range(n-1):
isPalindrome[i][i] = True
if s[i] == s[i+1]:
isPalindrome[i+1][i] = True
isPalindrome[n-1][n-1] = True
iMax = jMax = 0
positions = dict()
for j, char in enumerate(s):
if char in positions:
for i in positions[char]:
if isPalindrome[i+1][j-1]:
isPalindrome[i][j] = True
if (j - i) > (jMax - iMax):
iMax, jMax = i, j
positions[char].append(j)
else:
positions[char] = [j]
return s[iMax:jMax+1] | longest-palindromic-substring | Python: tracking character positions | kwabenantim | 0 | 6 | longest palindromic substring | 5 | 0.324 | Medium | 215 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2823984/Manacher-Algorithm-faster-than-97-O(n) | class Solution:
def longestPalindrome(self, s: str) -> str:
# as you see we will use a string called t
# t will be our old s string but delimited by ^# and #$
# Between each character of s there will be #
t = "^#" + "#".join(s) + "#$"
size_t = len(t)
# p will contain for an index i the radius of the longest palindrome which can be find from this index
# so from i - p[i] to i + p[i] we are facing a palindrome
p = [0] * size_t
d = c = 0
# c will be our center
# and d the distance of the highest palindrome we can found at c index
for i in range(1, size_t - 1):
mirror = 2 * c - i # it is the index of the mirror of i by c. It is c - (i - c)
# it can be resumed at 2 * c - i
# given mirror the mirror of i by c,
# if i + p[mirror] <= d we can initalize p[i] with the value of p[mirror]
if i + p[mirror] <= d:
p[i] = p[mirror]
#we will make growth the palindrome
while (t[i + 1 + p[i]] == t[i - 1 - p[i]]):
p[i] += 1
#we will adjust the center if necessary
if i + p[i] > d:
d = i + p[i]
c = i
(k, i) = max((p[i], i) for i in range(1, size_t - 1))
# k is the size of the longest palindrome and i the index
# the longuest palindrome start at (i - k) // 2 and finish at ((i + k) // 2 )
#so we return the string going from the start to the end
return s[(i- k) // 2 : (i + k) // 2] | longest-palindromic-substring | Manacher Algorithm faster than 97% O(n) | diavollo | 0 | 12 | longest palindromic substring | 5 | 0.324 | Medium | 216 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2819045/Python-Slow-Solution-Beginner | class Solution:
def longestPalindrome(self, s: str) -> str:
if s == s[::-1]:
return s
check = []
l = 0
while l != len(s):
count = 0
for i in range(l,len(s)):
sub = s[l:len(s)- count]
if sub == sub[::-1]:
check.append([len(sub), sub])
count +=1
l+=1
return max(check)[1] | longest-palindromic-substring | Python Slow Solution Beginner | Jashan6 | 0 | 2 | longest palindromic substring | 5 | 0.324 | Medium | 217 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2811057/Two-Pointer-Approach-oror-Python | class Solution:
def longestPalindrome(self, s: str) -> str:
res = ''
length = 0
for i in range(len(s)):
# checking for odd length
left, right = i, i
while left >= 0 and right < len(s) and s[left] == s[right]:
if (right - left + 1) > length:
res = s[left:right + 1]
length = (right - left + 1)
left -= 1
right += 1
# checking for odd length
left, right = i, i + 1
while left >= 0 and right < len(s) and s[left] == s[right]:
if (right - left + 1) > length:
res = s[left:right + 1]
length = (right - left + 1)
left -= 1
right += 1
return res | longest-palindromic-substring | Two Pointer Approach || Python | darsigangothri0698 | 0 | 10 | longest palindromic substring | 5 | 0.324 | Medium | 218 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2808156/Counting-Ripples-in-a-Pond | class Solution:
def longestPalindrome(self, s: str) -> str:
start, extent = 0, 1
for i in range(len(s) - 1):
possLen = 2 * min(i + 1, len(s) - i)
if i >= len(s) // 2 and extent > possLen:
break
if possLen > extent:
j, jEnd = 0, min(len(s) - i - 1, i + 1)
while j < jEnd and s[i + j + 1] == s[i - j]:
j += 1
if 2 * j > extent:
start, extent = i - j + 1, 2 * j
if possLen - 1 > extent:
j, jEnd = 1, min(len(s) - i, i + 1)
while j < jEnd and s[i + j] == s[i - j]:
j += 1
if 2 * j - 1 > extent:
start, extent = i - j + 1, 2 * j - 1
return s[start:start + extent] | longest-palindromic-substring | Counting Ripples in a Pond | constantstranger | 0 | 5 | longest palindromic substring | 5 | 0.324 | Medium | 219 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2806129/Very-easy-python-solution-(ACCEPTED) | class Solution:
def longestPalindrome(self, s: str) -> str:
left = right = 0
palindrome = ""
while left < len(s) and (len(s)-left) > len(palindrome):
right = left
while right < len(s):
if s[left: right + 1] == s[left: right + 1][::-1]:
if len(s[left: right + 1]) > len(palindrome):
palindrome = s[left: right + 1]
right += 1
left += 1
return palindrome | longest-palindromic-substring | Very easy python solution (ACCEPTED) | nehavari | 0 | 23 | longest palindromic substring | 5 | 0.324 | Medium | 220 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2804789/hehe | class Solution:
def longestPalindrome(self, s: str) -> str:
pal = ''
temp = ''
f = 0
t = s[:-1]
if s == s[::-1]:
return s
for i in range(len(s)):
for j in range(f, len(s)+1):
if s[i:j] == (s[i:j])[::-1] and len(s[i:j]) > f:
pal = s[i:j]
f = len(pal)
return pal | longest-palindromic-substring | hehe | user0355Kw | 0 | 3 | longest palindromic substring | 5 | 0.324 | Medium | 221 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2803633/Palindrome-substring-Python-Solution-Time-complexity-O(n*n) | class Solution:
def longestPalindrome(self, s: str) -> str:
res=''
reslen=0
for i in range(len(s)):
l,r=i,i
while l>=0 and r<len(s) and s[l]==s[r]:
if (r-l+1) > reslen:
res=s[l:r+1]
reslen=r-l+1
l-=1
r+=1
l,r=i,i+1
while l>=0 and r<len(s) and s[l]==s[r]:
if (r-l+1) > reslen:
res=s[l:r+1]
reslen=r-l+1
l-=1
r+=1
return res | longest-palindromic-substring | Palindrome substring Python Solution Time complexity O(n*n) | Jai_Trivedi | 0 | 6 | longest palindromic substring | 5 | 0.324 | Medium | 222 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2798602/Longest-Palindrome-using-python3 | class Solution:
def longestPalindrome(self, s: str) -> str:
n=len(s)
def expand_pallindrome(i,j):
while 0<=i<=j<n and s[i]==s[j]:
i-=1
j+=1
return (i+1, j)
res=(0,0)
for i in range(n):
b1 = expand_pallindrome(i,i)
b2 = expand_pallindrome(i,i+1)
res=max(res, b1, b2,key=lambda x: x[1]-x[0]+1) # find max based on the length of the pallindrome strings.
return s[res[0]:res[1]] | longest-palindromic-substring | Longest Palindrome using python3 | user1885uW | 0 | 6 | longest palindromic substring | 5 | 0.324 | Medium | 223 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2790471/dynammic-programming-O(n2) | class Solution:
def longestPalindrome(self, s: str) -> str:
dp = [[False]*len(s) for _ in range(len(s))]
for i in range(len(s)):
dp[i][i] = True
ans=s[0]
for j in range(len(s)):
for i in range(j):
if s[i]==s[j] and (dp[i+1][j-1] or j == i+1):
dp[i][j]=True
if j - i+1 > len(ans):
ans = s[i:j+1]
return ans | longest-palindromic-substring | dynammic programming O(n^2) | haniyeka | 0 | 14 | longest palindromic substring | 5 | 0.324 | Medium | 224 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2790446/brute-force-python-O(n2) | class Solution:
def longestPalindrome(self, s: str) -> str:
res = ''
for i in range(len(s)):
pos = ''
neg = ''
for j in range(i, len(s)):
pos = pos + s[j]
neg = s[j] + neg
# print('pos is ', pos)
# print('neg is ', neg)
if pos == neg and len(pos)>len(res):
res = pos
return res | longest-palindromic-substring | brute force python O(n^2) | ben_wei | 0 | 3 | longest palindromic substring | 5 | 0.324 | Medium | 225 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2784909/Python-O(n)-95-faster-O(n)-Solution | class Solution:
def longestPalindrome(self, s: str) -> str:
# edge cases: for a char or less return str
# 2 pointers, from beginning and end
# if they == append to another list.
N = len(s)
if N <= 1:
return s
N = 2*N+1 # Position count
L = [0] * N
L[0] = 0
L[1] = 1
C = 1 # centerPosition
R = 2 # centerRightPosition
i = 0 # currentRightPosition
iMirror = 0 # currentLeftPosition
maxLPSLength = 0
maxLPSCenterPosition = 0
start = -1
end = -1
diff = -1
for i in range(2,N):
# get currentLeftPosition iMirror for currentRightPosition i
iMirror = 2*C-i
L[i] = 0
diff = R - i
# If currentRightPosition i is within centerRightPosition R
if diff > 0:
L[i] = min(L[iMirror], diff)
# Attempt to expand palindrome centered at currentRightPosition i
# Here for odd positions, we compare characters and
# if match then increment LPS Length by ONE
# If even position, we just increment LPS by ONE without
# any character comparison
try:
while ((i+L[i]) < N and (i-L[i]) > 0) and \
(((i+L[i]+1) % 2 == 0) or \
(s[(i+L[i]+1)//2] == s[(i-L[i]-1)//2])):
L[i]+=1
except Exception as e:
pass
if L[i] > maxLPSLength: # Track maxLPSLength
maxLPSLength = L[i]
maxLPSCenterPosition = i
if i + L[i] > R:
C = i
R = i + L[i]
start = (maxLPSCenterPosition - maxLPSLength) // 2
end = start + maxLPSLength - 1
return s[start:end+1] | longest-palindromic-substring | Python O(n) 95% faster O(n) Solution | mahsumkcby | 0 | 11 | longest palindromic substring | 5 | 0.324 | Medium | 226 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2777807/Python3-or-O(N2)-or-Easy-To-Understand | class Solution:
def longestPalindrome(self, A: str) -> str:
n = len(A)
res = "" # for storing longest palindrome
resLen = 0 # for storing length of longest palindrome
for i in range(0 , n):
# for odd length palindrome check
l , r = i, i
while (l >=0 and r < n and A[l] == A[r]):
if (r - l + 1) > resLen:
resLen = (r - l + 1)
res = A[l : r+1]
# decrement l and increment r and check if we can get palindrome of larger size
l -= 1
r += 1
# for even length palindrome
l , r = i , i + 1
while (l >= 0 and r < n and A[l] == A[r]):
if (r - l + 1) > resLen:
resLen = (r - l + 1)
res = A[l : r+1]
# decrement l and increment r and check if we can get palindrome of larger size
l -= 1
r += 1
return res | longest-palindromic-substring | Python3 | O(N2) | Easy To Understand | vishal7085 | 0 | 2 | longest palindromic substring | 5 | 0.324 | Medium | 227 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2755339/Simple-Python-Solution | class Solution:
def longestPalindrome(self, s: str) -> str:
res = ""
resLen = 0
for i in range(len(s)):
# odd cases
l, r = i, i
while l >= 0 and r < len(s) and s[l] == s[r]:
if (r-l+1)>resLen:
res = s[l:r+1]
resLen = r-l+1
l-=1
r+=1
# even cases
l, r = i, i+1
while l >= 0 and r < len(s) and s[l] == s[r]:
if (r-l+1 )> resLen:
res = s[l:r+1]
resLen = r-l+1
l-=1
r+=1
return res | longest-palindromic-substring | Simple Python Solution | ekomboy012 | 0 | 18 | longest palindromic substring | 5 | 0.324 | Medium | 228 |
https://leetcode.com/problems/longest-palindromic-substring/discuss/2752656/Palindromic-Subtring-(Best-90-by-Memory) | class Solution:
def longestPalindrome(self, s: str) -> str:
self.res = "";
self.resLen = 0;
for i in range(len(s)):
self.getPalindrome(s,i,i);
self.getPalindrome(s,i,i+1);
return self.res;
def getPalindrome(self,s,l,r):
while l >= 0 and r < len(s) and s[l] == s[r]:
if (r - l + 1) > self.resLen:
self.res = s[l:r+1];
self.resLen = len(self.res);
l -= 1;
r += 1; | longest-palindromic-substring | Palindromic Subtring (Best 90% by Memory) | mohidk02 | 0 | 13 | longest palindromic substring | 5 | 0.324 | Medium | 229 |
https://leetcode.com/problems/zigzag-conversion/discuss/817306/Very-simple-and-intuitive-O(n)-python-solution-with-explanation | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
row_arr = [""] * numRows
row_idx = 1
going_up = True
for ch in s:
row_arr[row_idx-1] += ch
if row_idx == numRows:
going_up = False
elif row_idx == 1:
going_up = True
if going_up:
row_idx += 1
else:
row_idx -= 1
return "".join(row_arr) | zigzag-conversion | Very simple and intuitive O(n) python solution with explanation | wmv3317 | 96 | 3,000 | zigzag conversion | 6 | 0.432 | Medium | 230 |
https://leetcode.com/problems/zigzag-conversion/discuss/791453/90-faster-and-90-less-space-%2B-explanation | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows < 2:
return s
i = 0
res = [""]*numRows # We will fill in each line in the zigzag
for letter in s:
if i == numRows-1: # If this is the last line in the zigzag we go up
grow = False
elif i == 0: #Otherwise we go down
grow = True
res[i] += letter #Add the letter to its row
i = (i+1) if grow else i-1 # We increment (add 1) if grow is True,
# and decrement otherwise
return "".join(res) # return the joined rows | zigzag-conversion | 90% faster and 90% less space + explanation | MariaMozgunova | 27 | 1,600 | zigzag conversion | 6 | 0.432 | Medium | 231 |
https://leetcode.com/problems/zigzag-conversion/discuss/2709075/97-BEATED! | class Solution:
def convert(self, s: str, numRows: int) -> str:
list_of_items = [[] for i in range(numRows)]
DOWN = -1
i = 0
if numRows == 1:
return s
for char in s:
list_of_items[i].append(char)
if i == 0 or i == numRows - 1:
DOWN *= -1
i += DOWN
list_of_items = list(chain(*list_of_items))
return ''.join(list_of_items) | zigzag-conversion | 97% BEATED! | lil_timofey | 2 | 435 | zigzag conversion | 6 | 0.432 | Medium | 232 |
https://leetcode.com/problems/zigzag-conversion/discuss/1645784/Python3-8-Lines-or-Clean-%2B-Simple-Solution-or-Time-O(n)-or-Space-O(1) | class Solution:
def convert(self, s: str, numRows: int) -> str:
rows, direction, i = [[] for _ in range(numRows)], 1, 0
for ch in s:
rows[i].append(ch)
i = min(numRows - 1, max(0, i + direction))
if i == 0 or i == numRows - 1: direction *= -1
return ''.join(''.join(row) for row in rows) | zigzag-conversion | [Python3] 8 Lines | Clean + Simple Solution | Time O(n) | Space O(1) | PatrickOweijane | 2 | 410 | zigzag conversion | 6 | 0.432 | Medium | 233 |
https://leetcode.com/problems/zigzag-conversion/discuss/2216401/O(n)-O(n)-A-simple-Python3-solution-to-an-annoyingly-confusing-problem | class Solution:
def convert(self, s: str, numRows: int) -> str:
# rules for columns that have a diagonal
diagcols = max(numRows-2,1) if numRows>2 else 0
# return diagcols
grid = [""]*numRows
# while the string isn't empty
while s:
# insert characters 1 by 1 into each row
for index in range(numRows):
if s:
grid[index] += s[0]
s = s[1:]
# insert 1 character into each appropriate designated diagonal row, starting from the bottom
for index in range(diagcols):
if s:
grid[diagcols-index] += s[0]
s = s[1:]
return ''.join(grid) | zigzag-conversion | O(n), O(n) A simple Python3 solution to an annoyingly confusing problem | StackingFrog | 1 | 115 | zigzag conversion | 6 | 0.432 | Medium | 234 |
https://leetcode.com/problems/zigzag-conversion/discuss/727686/Python3Simple-implementation-less-than-97.89 | class Solution:
def convert(self, s: str, numRows: int) -> str:
length = len(s)
if numRows == 1 or numRows >= length:
return s
step = 2*numRows - 2
ret = ""
for i in range(0, numRows):
j = i
step_one = step - 2*i
while j < length:
ret += s[j]
if i == 0 or i == numRows-1:
j += step
else:
j += step_one
#If it's not first or last row, you need to change step after get one character
step_one = step - step_one
return ret | zigzag-conversion | [Python3]Simple implementation less than 97.89% | abclzm1989 | 1 | 225 | zigzag conversion | 6 | 0.432 | Medium | 235 |
https://leetcode.com/problems/zigzag-conversion/discuss/2846241/Python-3-solution | class Solution:
def convert(self, s: str, numRows: int) -> str:
actual_row = 0
actual_col = 0
s = [letter for letter in s]
matriz = [[0]*(len(s)) for _ in range(numRows)]
while s:
if actual_row == 0:
for row in range(numRows):
if not s:
break
matriz[row][actual_col] = s.pop(0)
actual_row = row
if numRows == 1:
actual_col+=1
else:
actual_col+=1
actual_row-=1
if actual_row > 0:
matriz[actual_row][actual_col] = s.pop(0)
final_string = ""
for row in matriz:
for letter in row:
if letter != 0:
final_string+=letter
return final_string | zigzag-conversion | Python 3 solution | user0106Ez | 0 | 2 | zigzag conversion | 6 | 0.432 | Medium | 236 |
https://leetcode.com/problems/zigzag-conversion/discuss/2827899/Python-Solution-Using-Dictionnary | class Solution:
def convert(self, s: str, numRows: int) -> str:
numCols = (numRows * 2) - 1
d = {}
i = 0
col = 0
row = 0
zig = numRows
while i < len(s):
r = abs(row)
d[r] = d.get(r, '') + s[i]
del r
i += 1
row -= 1
if row == 0:
col += 1
if zig == 1:
col += 1
zig = numRows
if abs(row) == numRows:
row = (numRows - 2)
zig = 1
col += 1
return ''.join(d.values())
'''
example for numRows=4 using 2D Matrix
0 0,0
1 1,0
2 2,0
3 3,0
4 2,1 +
5 1,2 +
6 0,3
7 1,3
8 2,3
9 3,3
10 2,4
11 1,5
12 0,6
13 1,6
''' | zigzag-conversion | Python Solution Using Dictionnary | chiboubys | 0 | 2 | zigzag conversion | 6 | 0.432 | Medium | 237 |
https://leetcode.com/problems/zigzag-conversion/discuss/2813961/6.-Zigzag-Conversion-Python-solution-with-explanation-or-Iterate-array-in-zigzag-order | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
skip = (2 * numRows) - 2
res = []
for i in range(numRows): # use i to iterate vertically
j = 0 # use j to iterate horizontally
while i + j < len(s):
res.append(s[j + i]) # gives index of the current iteration
sec = (j - i) + skip # due to the nature of the zigzag, there would be a second character in the zigzag if its between second row and second to last row
if i != 0 and i != numRows - 1 and sec < len(s): # check if the row isn't the first or last and if the second element calculated isn't larger than the length of s
res += s[sec]
j += skip # iterate to the next element in the row when in zigzag form
return "".join(res) | zigzag-conversion | 6. Zigzag Conversion - Python solution with explanation | Iterate array in zigzag order | jonjon98 | 0 | 3 | zigzag conversion | 6 | 0.432 | Medium | 238 |
https://leetcode.com/problems/zigzag-conversion/discuss/2809942/Python-slick-solution-using-generator | class Solution:
def convert(self, s: str, numRows: int) -> str:
# I will use numRows = 4 to provide examples here
# There is nothing to do if numRows == 1
if numRows == 1:
return s
# Example: for n=4, generator yields numbers in pattern:
# 0 1 2 3 2 1 0 1 2 3 . . .
# yield works as return but the function doesn't stop entirely,
# instead it pauses until we call next() again
def generator(n):
while True:
for i in range(n-1):
yield i
for j in range(n-1,0,-1):
yield j
# create a new generator
gen = generator(numRows)
# Using List Comprehension to create
# a list of k lines where k = numRows
lines = ["" for k in range(numRows)]
# We append char s[0] to line lines[0]
# char s[1] to line lines[1]
# char s[2] to line lines[2]
# char s[3] to line lines[3]
# char s[4] to line lines[2]
# char s[5] to line lines[1] and so on
for char in s:
lines[next(gen)] += char
# Finally, we stitch the lines together to get the desired string
return "".join(lines) | zigzag-conversion | Python slick solution using generator | nbashkir | 0 | 4 | zigzag conversion | 6 | 0.432 | Medium | 239 |
https://leetcode.com/problems/zigzag-conversion/discuss/2804719/Clean-Python-code | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
res = [""] * numRows
cnt, period = 0, 2*numRows-2
for i in range(len(s)):
if cnt < numRows:
res[cnt] += s[i]
else:
res[period-cnt] += s[i]
cnt = (cnt + 1) % period
return "".join(res) | zigzag-conversion | Clean Python code | codebreakblock | 0 | 7 | zigzag conversion | 6 | 0.432 | Medium | 240 |
https://leetcode.com/problems/zigzag-conversion/discuss/2802918/Simple-Python-Solution | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
row_map = {row:"" for row in range(1,numRows+1)}
row = 1
down = True
for c in s:
row_map[row] += c
if row == 1 or ((row < numRows) and down):
row += 1
down = True
else:
row -= 1
down = False
converted = ""
for row in row_map:
converted += row_map[row]
return converted | zigzag-conversion | Simple Python Solution | ekomboy012 | 0 | 4 | zigzag conversion | 6 | 0.432 | Medium | 241 |
https://leetcode.com/problems/zigzag-conversion/discuss/2801123/Easy-to-Understand-O(n)-space-and-time-complexity-solution | class Solution:
def convert(self, s: str, numRows: int) -> str:
direction, row = "positive", -1
rows = [""] * numRows
for char in s:
row += 1 if direction is "positive" else -1
rows[row] += char
if row < 1:
direction = "positive"
if row == numRows - 1:
direction = "negative"
return "".join(rows) | zigzag-conversion | Easy to Understand O(n) space, and time complexity solution | Henok2011 | 0 | 8 | zigzag conversion | 6 | 0.432 | Medium | 242 |
https://leetcode.com/problems/zigzag-conversion/discuss/2800084/Python-3-easy-solution | class Solution:
def convert(self, s: str, numRows: int) -> str:
zigzag = [""] * numRows
row_num = 0
dirn = 1
for c in list(s):
zigzag[row_num] += c
if(row_num >= numRows-1):
dirn = -1
elif row_num <= 0:
dirn = 1
row_num += dirn
return "".join(zigzag) | zigzag-conversion | Python 3 easy solution | pranjal51193 | 0 | 5 | zigzag conversion | 6 | 0.432 | Medium | 243 |
https://leetcode.com/problems/zigzag-conversion/discuss/2790733/Simple-solution-in-python-for-any-interested | class Solution:
def convert(self, s: str, numRows: int) -> str:
###### Empty/Trivial case########
if len(s) <2 or s == "" or s == None or numRows == 1:
return s
#################################
ret = ""
rows = list()
for i in range(0,numRows):
rows.append("")
flag = 0
rowCount = 0
for i in range(0,len(s)):
rows[rowCount] = rows[rowCount] + s[i]
##handles increasing rows or down the zigzag
if flag == 0 and rowCount < (numRows-1):
rowCount +=1
elif flag == 0 and rowCount <=(numRows-1):
rowCount -=1
flag = 1
#############################################
##handles decreasing rows or going up the zigzag
elif flag == 1 and rowCount > 0:
rowCount -=1
elif flag == 1 and rowCount == 0:
rowCount +=1
flag = 0
for i in range(0,len(rows)):
print("row "+str(i)+" =" +rows[i])
ret = ret + rows[i] #mistyped ret+=blah and it was causing issues
return ret | zigzag-conversion | Simple solution in python for any interested | yqd5143 | 0 | 3 | zigzag conversion | 6 | 0.432 | Medium | 244 |
https://leetcode.com/problems/zigzag-conversion/discuss/2790431/Very-Easy-level-mapping-solution-or-95%2B | class Solution:
def convert(self, s: str, numRows: int) -> str:
if len(s)<=numRows or numRows==1:
return s
premap=defaultdict(str)
i=0
while i<len(s):
k=1
while k<numRows and i<len(s):
premap[k]+=s[i]
k+=1
i+=1
while k>1 and i<len(s):
premap[k]+=s[i]
k-=1
i+=1
ans=''
for v in premap.values():
ans+=v
return ans | zigzag-conversion | Very Easy level mapping solution | 95%+ | AbhayKadapa007 | 0 | 7 | zigzag conversion | 6 | 0.432 | Medium | 245 |
https://leetcode.com/problems/zigzag-conversion/discuss/2786880/Python-implementation-with-Slice | class Solution:
def convert(self, s: str, numRows: int) -> str:
n = 2 * numRows - 2
if n == 0:
return s
ans = s[::n]
for i in range(1, n//2):
x, y = s[i::n], s[n-i::n]
tmp = [None] *len(x+y)
tmp[::2] = x
tmp[1::2] = y
ans += "".join(tmp)
ans += s[n//2::n]
return ans | zigzag-conversion | Python implementation with Slice | derbuihan | 0 | 4 | zigzag conversion | 6 | 0.432 | Medium | 246 |
https://leetcode.com/problems/zigzag-conversion/discuss/2782777/Solve-ZigZag-Conversion-in-linear-time | class Solution:
def convert(self, s: str, numRows: int) -> str:
ans=[]
for i in range(numRows):
ans.insert(len(ans),[])
i=0
while i<len(s):
j=0
while i<len(s) and j<(numRows):
ans[j].insert(len(ans[j]),s[i])
i+=1
j+=1
k=0
while i<len(s) and k<(numRows-2):
ans[j-k-2].insert(len(ans[j-k-2]),s[i])
i+=1
k+=1
final=''
for a in ans:
final=final+''.join(a)
return final | zigzag-conversion | Solve ZigZag Conversion in linear time | sijan_stha016 | 0 | 1 | zigzag conversion | 6 | 0.432 | Medium | 247 |
https://leetcode.com/problems/zigzag-conversion/discuss/2765011/Quick-line-efficient-solution-in-Py3 | class Solution:
def convert(self, s: str, numRows: int) -> str:
solutionArray = [""] * numRows
row = 0
for ele in range(len(s)):
if (numRows == 1): return s
solutionArray[row] += s[ele]
if (row == 0): step = 1
elif (row == (numRows - 1)): step = -1
row += step
return ''.join(solutionArray) | zigzag-conversion | Quick, line efficient solution in Py3 | mantone6 | 0 | 5 | zigzag conversion | 6 | 0.432 | Medium | 248 |
https://leetcode.com/problems/zigzag-conversion/discuss/2756149/not-simple-python3 | class Solution:
def convert(self, s: str, numRows: int) -> str:
a = [""]*numRows
k = 0
boo = True
if numRows==1:
return s
for i in range(len(s)):
a[k] += s[i]
if boo == True:
if k<numRows:
if k==(numRows-1):
boo = False
else:
k += 1
else:
boo=False
if boo == False:
if k>0:
k -= 1
else:
k += 1
boo = True
return("".join(a)) | zigzag-conversion | not simple python3 | meetHadvani | 0 | 4 | zigzag conversion | 6 | 0.432 | Medium | 249 |
https://leetcode.com/problems/zigzag-conversion/discuss/2755195/Simple-Step-Algorithm-for-zigzag-pattern-using-python | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows <= 1: return s
res = ""
for i in range(numRows):
increment = 2 * (numRows - 1)
for j in range(i,len(s),increment):
res += s[j]
if (i > 0 and i < numRows - 1
and j + increment - 2*i < len(s)):
res += s[j + increment - 2*i]
return res | zigzag-conversion | Simple Step Algorithm for zigzag pattern using python | mohidk02 | 0 | 2 | zigzag conversion | 6 | 0.432 | Medium | 250 |
https://leetcode.com/problems/zigzag-conversion/discuss/2754172/Concise-Python-Solution-(Beats-95) | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
result = ["" for i in range(numRows)]
for i in range(len(s)):
if ((i // (numRows-1)) % 2) == 0:
result[i % (numRows-1)] += s[i]
else:
result[(numRows-1) - i % (numRows-1)] += s[i]
return "".join(result) | zigzag-conversion | Concise Python Solution (Beats 95%) | ivan_n | 0 | 1 | zigzag conversion | 6 | 0.432 | Medium | 251 |
https://leetcode.com/problems/zigzag-conversion/discuss/2749707/Simple-Python-Solution-with-Explanation-or-Beginner-Friendly-(Beats-90) | class Solution:
def convert(self, s: str, numRows: int) -> str:
# If there is only one row, save time and return the string itself
if numRows == 1:
return s
# Create an empty list containing lists, these represent each row
result = []
for x in range(numRows):
result.append([])
# Using two variables 'direction' and 'ptr', the current row will be tracked
# along with which row to add the next variable in. direction = 1 represents down.
# direction = 0 represents up
direction = 0
ptr = 0
for ch in s:
# If its the first row (ptr = 0), we can only move downwards
if ptr == 0:
result[ptr].append(ch)
ptr += 1
direction = 1
continue
# If its the last row (ptr = numRows - 1), we can only move upwards
if ptr == numRows - 1:
result[numRows - 1].append(ch)
ptr -= 1
direction = 0
continue
# Append and increase/decrease ptr based on direction
if direction == 1:
result[ptr].append(ch)
ptr += 1
else:
result[ptr].append(ch)
ptr -= 1
# Combine all the lists within the list to get the final string
final = ''
for x in result:
for c in x:
final += c
return final | zigzag-conversion | Simple Python Solution with Explanation | Beginner Friendly (Beats 90%) | vijaivir | 0 | 9 | zigzag conversion | 6 | 0.432 | Medium | 252 |
https://leetcode.com/problems/zigzag-conversion/discuss/2744027/O(N)-implementation-using-a-pattern | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
#distance between characters for the top row
d0 = 2*numRows - 2
s_res = ''
d = 0 #it will store a variable distance for subsequent rows, except top and bottom ones
#read 1st row
while d < len(s):
s_res += s[d]
d += d0
#read subsequent rows
for i in range(1, numRows-1):
d = i
cnt = 2*i
while d < len(s):
s_res += s[d]
d += d0 - cnt #calc new variable distance
cnt = d0 - cnt #update the variation
#read nth row
d = numRows - 1
while d < len(s):
s_res += s[d]
d += d0
return s_res | zigzag-conversion | O(N) implementation using a pattern | nonchalant-enthusiast | 0 | 4 | zigzag conversion | 6 | 0.432 | Medium | 253 |
https://leetcode.com/problems/zigzag-conversion/discuss/2720579/Easy-to-understand-Python-3-Solution | class Solution:
def convert(self, s: str, numRows: int) -> str:
zigzag = [""]*numRows
goingUp = False
i = 0
for ch in s:
if not goingUp:
zigzag[i] += ch
i += 1
if i == numRows:
goingUp = True
i-=2
continue
if goingUp:
zigzag[i] += ch
i -= 1
if i < 0:
goingUp = False
i+=2
continue
retstr = ""
for stri in zigzag:
retstr += stri
return retstr | zigzag-conversion | Easy to understand Python 3 Solution | thenewkiller | 0 | 5 | zigzag conversion | 6 | 0.432 | Medium | 254 |
https://leetcode.com/problems/zigzag-conversion/discuss/2719268/Easy-python-3-solutionBeats-89 | class Solution:
def convert(self, s: str, numRows: int) -> str:
b=[''] * numRows
i=0
for j in s:
b[i]+=j
if i==0 and i==(numRows-1):
return s
elif i==0:
swap=0
elif i==(numRows-1):
swap=1
if swap==0:
i+=1
elif swap==1:
i-=1
sol=''
for i in b:
for j in i:
sol+=j
return sol | zigzag-conversion | Easy python 3 solution,Beats 89% | joeljoby111 | 0 | 2 | zigzag conversion | 6 | 0.432 | Medium | 255 |
https://leetcode.com/problems/zigzag-conversion/discuss/2676023/Basic-Python-solution-easy-explanation | class Solution:
def convert(self, s: str, numRows: int) -> str:
newstr = ""
if numRows == 1: #one row -> thats just the input string
return s
#first row
j = 0
while j < len(s):
newstr += s[j]
j += 2 * (numRows - 1)
#middle rows
for i in range(1, numRows - 1): #i is the row we are constructing
down = True #we start by going down the zigzag
j = i
while j < len(s):
newstr += s[j]
if down: #count letters in the rows below
toadd = 2 * (numRows - (i + 1))
else: #count letters in the rows above
#amount of rows above = row index
toadd = 2 * i
down = not down #reverse direction
j += toadd
#last row
j = numRows - 1
while j < len(s):
newstr += s[j]
j += 2 * (numRows - 1)
return newstr | zigzag-conversion | Basic Python solution - easy explanation | mat1124 | 0 | 7 | zigzag conversion | 6 | 0.432 | Medium | 256 |
https://leetcode.com/problems/zigzag-conversion/discuss/2671340/Simple-Python-Solution-for-6.-Zigzag-Conversion | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows==1:
return s
ans = ['' for i in range(numRows)]
curr = 0
for i in s:
ans[curr] += i
if curr>=0:
curr+=1
if curr==numRows:
curr = -2
else:
curr-=1
if curr == (numRows+1)*(-1):
curr = 1
ans = ''.join(ans)
return ans | zigzag-conversion | Simple Python Solution for 6. Zigzag Conversion | Akkishanu | 0 | 4 | zigzag conversion | 6 | 0.432 | Medium | 257 |
https://leetcode.com/problems/zigzag-conversion/discuss/2667076/Simple-solution | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1 or len(s) == 1:
return s
res = ""
for r in range(numRows):
inc = 2 * (numRows - 1)
for i in range(r, len(s), inc):
res += s[i]
if r > 0 and r < numRows - 1 and (i + inc - 2*r) < len(s):
res += s[i + inc - (2 * r)]
return res | zigzag-conversion | Simple solution | CCsobu | 0 | 1 | zigzag conversion | 6 | 0.432 | Medium | 258 |
https://leetcode.com/problems/zigzag-conversion/discuss/2640621/python-solution | class Solution:
def convert(self, s: str, numRows: int) -> str:
if len(s) <= numRows:
return s
arr = []
s = list(s)
for i in range(numRows):
arr.append([s.pop(0)])
i -= 1
while i > 0 and s:
arr[i].append(s.pop(0))
i -= 1
n = len(s)
j = 0
while s:
#print(arr)
if j < numRows:
arr[j].append(s.pop(0))
j += 1
elif j == numRows:
j -= 2
while j>0 and s:
arr[j].append(s.pop(0))
j -= 1
ans = []
for i in arr:
ans.extend(i)
return "".join(ans) | zigzag-conversion | python solution | sarthakchawande14 | 0 | 5 | zigzag conversion | 6 | 0.432 | Medium | 259 |
https://leetcode.com/problems/zigzag-conversion/discuss/2628689/Python-double-99 | class Solution:
def convert(self, s: str, numRows: int) -> str:
arr = [""] * numRows
if numRows == 1:
return s
direction = 1
row = 0
for i in range(len(s)):
arr[row] += s[i]
row += direction
if row == numRows - 1:
direction = -1
elif row == 0:
direction = 1
return "".join(arr) | zigzag-conversion | Python double 99% | babyplutokurt | 0 | 44 | zigzag conversion | 6 | 0.432 | Medium | 260 |
https://leetcode.com/problems/zigzag-conversion/discuss/2598914/Python-9-line-Simple-Solution | class Solution:
def convert(self, s: str, numRows: int) -> str:
track = ["" for _ in range(numRows)]
period = numRows + max(0, numRows-2)
for index, char in enumerate(s):
rest = index%period
row = rest if rest<numRows else numRows-(rest-numRows)-2
track[row] += char
return ''.join(track) | zigzag-conversion | Python 9-line Simple Solution | ParkerMW | 0 | 146 | zigzag conversion | 6 | 0.432 | Medium | 261 |
https://leetcode.com/problems/zigzag-conversion/discuss/2564910/Easy-python-solution | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
elif numRows ==2:
rows=['']*numRows # Stores the letters of each rows
for i in range(0,len(s),2):
rows[0]+=s[i]
for i in range(1,len(s),2):
rows[1]+=s[i]
return rows[0]+rows[1]
else: # For more than 3 rows
rows=['']*numRows # Stores the letters of each rows
period = 2*numRows-2
for i in range(len(s)):
modulus = i%period
row_index = modulus if modulus<numRows else 2*numRows-modulus-2
rows[row_index] += s[i]
#Concatenate the return value
return_value = ''
for i in range(numRows):
return_value += rows[i]
return return_value | zigzag-conversion | Easy python solution | guojunfeng1998 | 0 | 53 | zigzag conversion | 6 | 0.432 | Medium | 262 |
https://leetcode.com/problems/zigzag-conversion/discuss/2564490/easy-python | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
res = [''] * numRows
# with function call
'''
cur = 0
def increase(num):
return num + 1
def decrease(num):
return num - 1
pattern = increase
for i in range(len(s)):
if cur == 0:
pattern = increase
if cur == numRows - 1:
pattern = decrease
res[cur] += s[i]
cur = pattern(cur)
'''
# without function call
cur, step = 0, 1
for i in range(len(s)):
if cur == 0:
step = 1
if cur == numRows - 1:
step = -1
res[cur] += s[i]
cur += step
return ''.join(res) | zigzag-conversion | easy python | MajimaAyano | 0 | 35 | zigzag conversion | 6 | 0.432 | Medium | 263 |
https://leetcode.com/problems/zigzag-conversion/discuss/2552704/Python3-O(n)-with-explanation | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
res = ""
for i in range(numRows):
col = i
while col < len(s):
res += s[col]
col_offset = 2 * (numRows - 1)
col_next = col + col_offset
diag = col + 2 * (numRows - 1 - col % col_offset)
if diag != col_next and diag != col and diag < len(s):
res += s[diag]
col = col_next
return res
if __name__=="__main__":
unittest.main() | zigzag-conversion | [Python3] O(n) with explanation | gdm | 0 | 90 | zigzag conversion | 6 | 0.432 | Medium | 264 |
https://leetcode.com/problems/zigzag-conversion/discuss/2483938/PYTHON-3-Simple-Clean-approach-beat-99 | class Solution:
def convert(self, s: str, numRows: int) -> str:
all_list = ['']*numRows
counter = 0
forward, backward = True, False
for i in s:
all_list[counter] = all_list[counter] + i
if forward:
if (counter < numRows-1):
counter+=1
else:
forward, backward = False, True
counter-=1
else:
if (counter>0):
counter-=1
else:
forward, backward = True, False
counter+=1
return "".join(all_list) | zigzag-conversion | ✅ [PYTHON 3] Simple, Clean approach beat 99% 🏆 | girraj_14581 | 0 | 170 | zigzag conversion | 6 | 0.432 | Medium | 265 |
https://leetcode.com/problems/zigzag-conversion/discuss/2416228/Python-Accurate-Fast-Solution-Matrix-Beats-96-oror-Documented | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1: return s # return s, given number of rows is 1
m = [[] for _ in range(numRows)] # create matrix with given rows
row = 0 # current row in which char to be add
inc = 1 # increment value
for c in s:
m[row].append(c) # add char to current row
row += inc # next current row
if row == 0 or row == numRows-1: # if reached at border,
inc = -inc # - negate the increment
words = ["".join(l) for l in m] # convert rows/(lists of char) into words
return "".join(words) # convert words into one string | zigzag-conversion | [Python] Accurate Fast Solution - Matrix - Beats 96% || Documented | Buntynara | 0 | 75 | zigzag conversion | 6 | 0.432 | Medium | 266 |
https://leetcode.com/problems/zigzag-conversion/discuss/2373621/Easy-Python-3-Solution | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
i = 0
ls = ['']*numRows
sign = 1
for ch in s:
ls[i]+= ch
i+=1*sign
if i == numRows:
i-=2
sign=-1
if i == -1:
i+=2
sign = 1
return ''.join(ls) | zigzag-conversion | Easy Python 3 Solution | harsh30199 | 0 | 171 | zigzag conversion | 6 | 0.432 | Medium | 267 |
https://leetcode.com/problems/zigzag-conversion/discuss/2324247/O(n)-time-O(n)-space-decent-array-solution | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
arr = [[]for _ in range(numRows)]
i, row = 0, -1 # row offset by one for proper zigzgging
while i < len(s):
while row < numRows-1 and i < len(s):
row += 1
arr[row].append(s[i])
i += 1
while row > 0 and i < len(s):
row -= 1
arr[row].append(s[i])
i += 1
res = ''
for row in arr:
res += ''.join(row)
return res | zigzag-conversion | O(n) time, O(n) space - decent array solution | mfarrill | 0 | 52 | zigzag conversion | 6 | 0.432 | Medium | 268 |
https://leetcode.com/problems/zigzag-conversion/discuss/2204988/Python3-solution-write-by-AI(Github-Copilot) | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
# create a list of lists
rows = [[] for _ in range(numRows)]
# print(rows)
# iterate through the string
# if the index is even, append to the first row
# if the index is odd, append to the last row
# if the index is even and the row is the last row, append to the first row
# if the index is odd and the row is the first row, append to the last row
# print(rows)
for i, c in enumerate(s):
if i % (2 * (numRows - 1)) == 0:
rows[0].append(c)
elif i % (2 * (numRows - 1)) == 1:
rows[numRows - 1].append(c)
elif i % (2 * (numRows - 1)) > 1 and i // (2 * (numRows - 1)) % 2 == 0:
rows[i // (2 * (numRows - 1))].append(c)
else:
rows[numRows - i // (2 * (numRows - 1)) - 1].append(c)
# print(rows)
# join the rows
return ''.join([''.join(row) for row in rows])
``` | zigzag-conversion | Python3 solution write by AI(Github Copilot) | aaron17 | 0 | 43 | zigzag conversion | 6 | 0.432 | Medium | 269 |
https://leetcode.com/problems/zigzag-conversion/discuss/2114039/Zigzag-Conversion | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
if len(s) == numRows:
return s
arr = [[] for i in range(numRows)]
row = 0
direction = 1
i = 0
while i < len(s):
arr[row] += s[i]
if row == len(arr)-1:
direction = -1
if row == 0:
direction = 1
if direction == 1:
row+=1
else:
row-=1
i+=1
s = ""
for j in arr:
for char in j:
s+=char
return s | zigzag-conversion | Zigzag Conversion | somendrashekhar2199 | 0 | 137 | zigzag conversion | 6 | 0.432 | Medium | 270 |
https://leetcode.com/problems/zigzag-conversion/discuss/2060194/Simple-FSM-or-python | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
temp = [[] for i in range(numRows)]
cnt = 0
turnBack = False
for i in s:
temp[cnt].append(i)
if not turnBack:
if cnt == numRows - 1:
turnBack = not turnBack
cnt -= 1
else:
cnt += 1
else:
if cnt == 0:
turnBack = not turnBack
cnt += 1
else:
cnt -= 1
retval = ""
for i in temp:
retval += ''.join(i)
return retval | zigzag-conversion | Simple FSM | python | skrrtttt | 0 | 95 | zigzag conversion | 6 | 0.432 | Medium | 271 |
https://leetcode.com/problems/zigzag-conversion/discuss/2005125/8-Lines-Python-Solution-oror-90-Faster-oror-Memory-less-than-80 | class Solution:
def convert(self, S: str, N: int) -> str:
if N==1 or N>=len(S): return S
ans=['']*N ; idx=0 ; step=1
for s in S:
ans[idx]+=s
if idx==0: step=1
elif idx==N-1: step=-1
idx+=step
return ''.join(ans) | zigzag-conversion | 8-Lines Python Solution || 90% Faster || Memory less than 80% | Taha-C | 0 | 82 | zigzag conversion | 6 | 0.432 | Medium | 272 |
https://leetcode.com/problems/zigzag-conversion/discuss/1987779/Python3-Simple-linear-solution-with-explanations | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1: return s
res = ""
for r in range(numRows):
increment = 2*(numRows - 1) # offset added to the next element on the same row
for i in range(r, len(s), increment): # for each element in the same row
res += s[i] # append even-index column element for each row
if (r > 0 and r < numRows-1 and i+increment-2*r < len(s)):
res += s[i+increment-2*r] # append odd-index column element for middle rows
return res | zigzag-conversion | [Python3] Simple linear solution with explanations | leqinancy | 0 | 59 | zigzag conversion | 6 | 0.432 | Medium | 273 |
https://leetcode.com/problems/zigzag-conversion/discuss/1924411/Zigzag-easily-understandable-Python3-solution | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
#Creating lines list with length numRows
lines = []
for i in range(numRows):
lines.append([])
#Seperating chars to their corresponding lines
idx = 0
flag = True
for i,v in enumerate(s):
lines[idx].append(v)
if idx == numRows-1:
flag = False
elif idx == 0:
flag = True
if flag == True:
idx += 1
else:
idx -= 1
#Combining all chars as required
result = ''
for i in lines:
result += ''.join(i)
return result | zigzag-conversion | Zigzag easily understandable Python3 solution | 2255141 | 0 | 43 | zigzag conversion | 6 | 0.432 | Medium | 274 |
https://leetcode.com/problems/zigzag-conversion/discuss/1874454/Python3-Solution-using-Dictionary | class Solution:
def convert(self, s: str, numRows: int) -> str:
dicto = {}
row = 1
rowPrev = row
for i in range(len(s)):
if row in dicto:
dicto[row] = dicto[row] + s[i]
else:
dicto[row] = s[i]
if row == numRows or row < rowPrev and row != 1:
rowPrev = row
row -= 1
elif row == 1 or row > rowPrev:
rowPrev = row
row += 1
holder = ""
theVals = list(dicto.values())
for i in range(len(theVals)):
holder = holder + theVals[i]
return holder | zigzag-conversion | Python3 Solution using Dictionary | mrpuffie | 0 | 65 | zigzag conversion | 6 | 0.432 | Medium | 275 |
https://leetcode.com/problems/zigzag-conversion/discuss/1873827/Simple-Python3-Solution | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
a = ['' for i in range(numRows)]
c = numRows
inc = False
for i in s:
a[numRows-c] += i # If numRows = 3, the range of numRows-c is [0, 2] as c is in the range of [1, 3]
if not inc:
c -= 1
if c == 1:
inc = True
else:
c += 1
if c == numRows:
inc = False
return ''.join(a) | zigzag-conversion | Simple Python3 Solution | rjnkokre | 0 | 54 | zigzag conversion | 6 | 0.432 | Medium | 276 |
https://leetcode.com/problems/reverse-integer/discuss/1061403/Clean-pythonic-solution | class Solution:
def reverse(self, x: int) -> int:
retval = int(str(abs(x))[::-1])
if(retval.bit_length()>31):
return 0
if x<0:
return -1*retval
else:
return retval | reverse-integer | Clean pythonic solution | njain07 | 20 | 3,300 | reverse integer | 7 | 0.273 | Medium | 277 |
https://leetcode.com/problems/reverse-integer/discuss/2803440/Python-or-Easy-Solution | class Solution:
def reverse(self, x: int) -> int:
if x not in range(-9,9):
x = int(str(x)[::-1].lstrip('0')) if x >= 0 else int(f"-{str(x)[:0:-1]}".lstrip('0'))
return x if (x < 2**31-1 and x > -2**31) else 0 | reverse-integer | Python | Easy Solution✔ | manayathgeorgejames | 5 | 1,500 | reverse integer | 7 | 0.273 | Medium | 278 |
https://leetcode.com/problems/reverse-integer/discuss/1071721/My-python3-solution | class Solution:
def reverse(self, x: int) -> int:
number = "".join(reversed(list(str(abs(x)))))
result = int("-" + number) if x < 0 else int(number)
if -2**31 <= result <= (2**31)-1:
return result
else:
return 0 | reverse-integer | My python3 solution | DmitriyL02 | 5 | 810 | reverse integer | 7 | 0.273 | Medium | 279 |
https://leetcode.com/problems/reverse-integer/discuss/670499/Python-line-by-line-explanation | class Solution:
def reverse(self, x: int) -> int:
# first convert it to string
x = str(x)
# if less than zero
if (int(x)<0) :
# first character is "-", so let's retain it
# reverse the rest of the characters, then add it up using "+"
# convert it back to integer
x = int(x[0]+x[1:][::-1])
# if it is zero or more
else:
# proceed to reverse the characters and convert back to integer
x =int(x[::-1])
# if they are -2^31 or 2^31 - 1, return 0. Else, return x
return x if -2147483648 <= x <= 2147483647 else 0 | reverse-integer | Python line by line explanation | derekchia | 5 | 738 | reverse integer | 7 | 0.273 | Medium | 280 |
https://leetcode.com/problems/reverse-integer/discuss/1645810/Python3-Checks-Overflow-or-Time-O(logx)-or-Space-O(1)-or-Abiding-by-all-Rules | class Solution:
def reverse(self, x: int) -> int:
sign = -1 if x < 0 else 1
x = abs(x)
maxInt = (1 << 31) - 1
res = 0
while x:
if res > (maxInt - x % 10) // 10: return 0
res = res * 10 + x % 10
x //= 10
return sign * res | reverse-integer | [Python3] Checks Overflow | Time O(logx) | Space O(1) | Abiding by all Rules | PatrickOweijane | 4 | 367 | reverse integer | 7 | 0.273 | Medium | 281 |
https://leetcode.com/problems/reverse-integer/discuss/1270724/Python-Simple-Solution-Easy-to-Read | class Solution:
def reverse(self, x: int) -> int:
negative = x < 0
ans = 0
if negative:
x = x*-1
while x > 0:
rem = x % 10
ans = (ans*10)+rem
x = x // 10
if negative:
ans = ans*-1
if ans > (2**31)-1 or ans < (-2)**31:
return 0
else:
return ans | reverse-integer | Python Simple Solution, Easy to Read | Khonshu | 3 | 436 | reverse integer | 7 | 0.273 | Medium | 282 |
https://leetcode.com/problems/reverse-integer/discuss/1048717/Clean-and-Elegant-Python-Solution-with-Overflow-Handled | class Solution:
def reverse(self, x: int) -> int:
if x == 0:
return 0
reversed_integer = 0
sign = 1 if x > 0 else -1
x = abs(x)
while x != 0:
current_number = x % 10
if reversed_integer * 10 + current_number > (2 **31) or reversed_integer * 10 + current_number < ((-2 ** 31) - 1):
return 0
reversed_integer = reversed_integer * 10 + current_number
x //= 10
return reversed_integer * sign | reverse-integer | Clean and Elegant Python Solution with Overflow Handled | jdshah | 3 | 268 | reverse integer | 7 | 0.273 | Medium | 283 |
https://leetcode.com/problems/reverse-integer/discuss/972410/Python3 | class Solution:
def reverse(self, x: int) -> int:
x = ','.join(str(x)).split(',')
sign = x.pop(0) if not x[0].isalnum() else None
x = ''.join(x[::-1])
res = sign+x if sign else x
res = int(res)
return res if -1*pow(2, 31) < res < pow(2, 31)-1 else 0 | reverse-integer | Python3 | mailolumide | 3 | 493 | reverse integer | 7 | 0.273 | Medium | 284 |
https://leetcode.com/problems/reverse-integer/discuss/2387574/Solution-that-respects-the-signed-32-bit-integer-constraint | class Solution:
def reverse(self, x: int) -> int:
if x == -2147483648: # -2**31
return 0
# -8463847412 is not a valid input
# hence result will never be -2147483648
# so we can work with positiv integers and multiply by the sign at the end
s = (x > 0) - (x < 0) # sign of x
x *= s
max_int = 2147483647 # 2**31-1
result = 0
while x:
if result <= max_int//10:
result *= 10
else:
return 0
if result <= max_int-(x%10):
result += x%10
else:
return 0
x //= 10
return s*result | reverse-integer | Solution that respects the signed 32-bit integer constraint | SpacePower | 2 | 243 | reverse integer | 7 | 0.273 | Medium | 285 |
https://leetcode.com/problems/reverse-integer/discuss/2323570/Python-oror-Two-Solutions-(Math-and-String)-with-explanations | class Solution:
def reverse(self, x: int) -> int:
pn = 1
if x < 0 :
pn = -1
x *= -1
x = int(str(x)[::-1]) * pn
#^Convert integer into string and reverse using slicing and convert it back to integer
return 0 if x < 2**31 * -1 or x > 2**31 -1 else x | reverse-integer | Python || Two Solutions (Math and String) with explanations | zhibin-wang09 | 2 | 264 | reverse integer | 7 | 0.273 | Medium | 286 |
https://leetcode.com/problems/reverse-integer/discuss/2323570/Python-oror-Two-Solutions-(Math-and-String)-with-explanations | class Solution:
def reverse(self, x: int) -> int:
ans,negative = 0,False
if x < 0:
negative = True
x *= -1
while x > 0:
ans *= 10 #Increse the length of answer
mod = int(x % 10) #Obtain last digit
ans += mod #Add last digit to answer
x = int(x /10) #Remove last digit
#^Obtain the last digit of x then move it to ans until x = 0.
return 0 if ans > 2**31-1 or ans < 2**31 *-1 else -ans if negative else ans | reverse-integer | Python || Two Solutions (Math and String) with explanations | zhibin-wang09 | 2 | 264 | reverse integer | 7 | 0.273 | Medium | 287 |
https://leetcode.com/problems/reverse-integer/discuss/2318304/Python-Solution-Faster-than-96.24 | class Solution:
def reverse(self, x: int) -> int:
sign = 1
if x < 0:
sign = -1
x *= -1
x = int(str(x)[::-1])
if x > 2**31-1 or x < 2**31 * -1:
return 0
return sign * x | reverse-integer | Python Solution Faster than 96.24% | zip_demons | 2 | 313 | reverse integer | 7 | 0.273 | Medium | 288 |
https://leetcode.com/problems/reverse-integer/discuss/1486100/Python3-oror-Simplest-and-Valid-oror-With-Explanation | class Solution:
def reverse(self, x: int) -> int:
# initiate answer as zero
# the way we are gonna solve this is by understanding the simple math behind reversing an integer
# the objective is to be able to code the mathematical logic; which is why the string approach is totally rubbish and invalid and not the right approach to coding
ans = 0
# coding for negative integer
negative = x<0
if negative:
x = x*-1
# the logic
while x>0:
rem = x%10
ans = (ans*10)+rem
x = x//10
# edge case
if ans > (2**31)-1 or ans < (-2)**31:
return 0
# negative int
elif negative:
return ans*-1
else:
return ans | reverse-integer | Python3 || Simplest and Valid || With Explanation | ajinkya2021 | 2 | 471 | reverse integer | 7 | 0.273 | Medium | 289 |
https://leetcode.com/problems/reverse-integer/discuss/1364007/99.55-Faster-Python-O(n)-Easily-understandable | class Solution:
def reverse(self, x: int) -> int:
if(x>0):
a = str(x)
a = a[::-1]
return int(a) if int(a)<=2**31-1 else 0
else:
x=-1*x
a = str(x)
a = a[::-1]
return int(a)*-1 if int(a)<=2**31 else 0 | reverse-integer | 99.55% Faster, Python, O(n), Easily understandable | unKNOWN-G | 2 | 1,200 | reverse integer | 7 | 0.273 | Medium | 290 |
https://leetcode.com/problems/reverse-integer/discuss/2796506/Python-Simple-Python-Solution-36-ms-faster-than-91.38 | class Solution:
def reverse(self, x: int) -> int:
def reverse_signed(num):
sum=0
sign=1
if num<0:
sign=-1
num=num*-1
while num>0:
rem=num%10
sum=sum*10+rem
num=num//10
if not -2147483648<sum<2147483647:
return 0
return sign*sum
return reverse_signed(x) | reverse-integer | [ Python ] 🐍🐍 Simple Python Solution ✅✅36 ms, faster than 91.38% | sourav638 | 1 | 103 | reverse integer | 7 | 0.273 | Medium | 291 |
https://leetcode.com/problems/reverse-integer/discuss/2659747/Python-O(n)-Time-Solution-with-full-working-explanation | class Solution: # Time: O(n) and Space: O(1)
def reverse(self, x: int) -> int:
MIN = -2147483648 # -2^31
MAX = 2147483647 # 2^31 - 1
res = 0
while x: # Loop will run till x have some value either than 0 and None
digit = int(math.fmod(x, 10))
x = int(x / 10)
if res > MAX // 10 or (res == MAX // 10 and digit >= MAX % 10):
return 0
if res < MIN // 10 or (res == MIN // 10 and digit <= MIN % 10):
return 0
res = (res * 10) + digit
return res | reverse-integer | Python O(n) Time Solution with full working explanation | DanishKhanbx | 1 | 233 | reverse integer | 7 | 0.273 | Medium | 292 |
https://leetcode.com/problems/reverse-integer/discuss/2275852/Python3-Math-solution | class Solution:
def reverse(self, x: int) -> int:
if x == 0:
return 0
elif x < 0:
sign = -1
x = abs(x)
flag = True
else:
sign = 1
flag = False
ans = 0
digits = int(math.log10(x)) # nubmer of digits - 1
for i in range(digits + 1):
ans += (10 ** (digits - i) * (int(x / (10 ** i)) % 10))
if ans > 2 ** 31 - 1:
return 0
return ans if not flag else sign * ans | reverse-integer | Python3 Math solution | frolovdmn | 1 | 56 | reverse integer | 7 | 0.273 | Medium | 293 |
https://leetcode.com/problems/reverse-integer/discuss/2082744/Python3-Runtime%3A-O(n)-oror-O(n)-Runtime%3A-34ms-86.01 | class Solution:
def reverse(self, x: int) -> int:
return self.reverseIntegerByList(x)
# O(n) || O(1) 34ms 86.01%
def reverseIntegerByList(self, value):
if value == 0:return value
isNeg = value < 0
value = abs(value)
numList = list()
newReverseNumber = 0
while value > 0:
k = value % 10
newReverseNumber = newReverseNumber * 10 + k
value //= 10
if newReverseNumber >= 2**31 or newReverseNumber >= 2**31 - 1:
return 0
return newReverseNumber if not isNeg else -newReverseNumber
# Brute force
# O(n) || O(m) 37ms 76.28%
# m stands for making it string
def reverseIntegerByString(self, value):
isNeg = value < 0
strVal = str(abs(value))
strVal = int(strVal[::-1])
if strVal >= 2**31 or strVal >= 2**31 - 1:
return 0
return -strVal if isNeg else strVal | reverse-integer | Python3 Runtime: O(n) || O(n) Runtime: 34ms 86.01% | arshergon | 1 | 101 | reverse integer | 7 | 0.273 | Medium | 294 |
https://leetcode.com/problems/reverse-integer/discuss/2025235/Python-compact-solution | class Solution:
def reverse(self, x: int) -> int:
if x > -1:
return int(str(x)[::-1]) if int(str(x)[::-1]) < 2147483647 else 0
else:
return int("-"+str(abs(x))[::-1]) if int("-"+str(abs(x))[::-1]) > -2147483647 else 0 | reverse-integer | Python compact solution | Yodawgz0 | 1 | 185 | reverse integer | 7 | 0.273 | Medium | 295 |
https://leetcode.com/problems/reverse-integer/discuss/1863788/python3-O(N) | class Solution:
def reverse(self, x: int) -> int:
sign = 1 if x >= 0 else -1
s = str(x*sign)
res = int(s[::-1])*sign
return 0 if(-2**31 > res or res > (2**31)-1) else res | reverse-integer | [python3] O(N) | Rahul-Krishna | 1 | 70 | reverse integer | 7 | 0.273 | Medium | 296 |
https://leetcode.com/problems/reverse-integer/discuss/1837832/Python-Simple-Slution | class Solution:
def reverse(self, x: int) -> int:
a = 1
if x < 0:
a = -1
x = abs(x)
s = 0
while x:
s *= 10
s += x%10
x //= 10
s = a*s
if s < -2**31 or s>2**31-1:
return 0
return s | reverse-integer | [Python] Simple Slution | zouhair11elhadi | 1 | 82 | reverse integer | 7 | 0.273 | Medium | 297 |
https://leetcode.com/problems/reverse-integer/discuss/1791782/Python-Solution-(only-4-Lines-of-Code) | class Solution:
def reverse(self, x: int) -> int:
flage=False
if(x<0):
flage=True
return((-int(str(abs(x))[::-1]) if flage else int(str(abs(x))[::-1])) if(-231<int(str(abs(x))[::-1])<231) else 0) | reverse-integer | Python Solution (only 4 Lines of Code) | aswin_thumati | 1 | 178 | reverse integer | 7 | 0.273 | Medium | 298 |
https://leetcode.com/problems/reverse-integer/discuss/1645357/Python-runtime-99.84-memory-98.89 | class Solution(object):
def reverse(self, x):
if x < 0:
y = 0-int(str(abs(x))[::-1])
if y <= -(pow(2,31)):
return 0
return y
else:
y = int(str(x)[::-1])
if y >= pow(2,31)-1:
return 0
return y | reverse-integer | Python runtime 99.84%, memory 98.89% | cwrli | 1 | 205 | reverse integer | 7 | 0.273 | Medium | 299 |
Subsets and Splits